Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backend: Dev Modules #2011

Merged
merged 3 commits into from
Jun 9, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ class ModuleProcessor(private val codeGenerator: CodeGenerator, private val logg
return symbol
}

//TODO remove when KMixins added as it contains KSP annotation helpers.
private fun isDevAnnotation(klass: KSClassDeclaration): Boolean {
val annotation = klass.annotations.find { it.shortName.asString() == "SkyHanniModule" } ?: return false
return annotation.arguments.find { it.name?.asString() == "devOnly" }?.value as? Boolean ?: false
}

private fun generateFile(symbols: List<KSClassDeclaration>) {
val dependencies = symbols.mapNotNull { it.containingFile }.toTypedArray()
val deps = Dependencies(true, *dependencies)
Expand All @@ -53,13 +59,18 @@ class ModuleProcessor(private val codeGenerator: CodeGenerator, private val logg
OutputStreamWriter(file).use {
it.write("package at.hannibal2.skyhanni.skyhannimodule\n\n")
it.write("object LoadedModules {\n")
it.write(" val modules: List<Any> = listOf(\n")
it.write(" val isDev: Boolean = at.hannibal2.skyhanni.utils.system.PlatformUtils.isDevEnvironment\n")
it.write(" val modules: List<Any> = buildList {\n")

symbols.forEach { symbol ->
it.write(" ${symbol.qualifiedName!!.asString()},\n")
if (isDevAnnotation(symbol)) {
it.write(" if (isDev) add(${symbol.qualifiedName!!.asString()})\n")
} else {
it.write(" add(${symbol.qualifiedName!!.asString()})\n")
}
}

it.write(" )\n")
it.write(" }\n")
it.write("}\n")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@ package at.hannibal2.skyhanni.skyhannimodule

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class SkyHanniModule
annotation class SkyHanniModule(
/**
* If the module will only be loaded in a development environment.
*/
val devOnly: Boolean = false,
)
5 changes: 3 additions & 2 deletions src/main/java/at/hannibal2/skyhanni/config/ConfigManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import at.hannibal2.skyhanni.utils.LorenzLogger
import at.hannibal2.skyhanni.utils.LorenzUtils
import at.hannibal2.skyhanni.utils.SimpleTimeMark
import at.hannibal2.skyhanni.utils.json.BaseGsonBuilder
import at.hannibal2.skyhanni.utils.system.PlatformUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
Expand Down Expand Up @@ -127,7 +128,7 @@ class ConfigManager {
}
val configLink = field.getAnnotation(ConfigLink::class.java)
if (configLink == null) {
if (LorenzUtils.isInDevEnvironment()) {
if (PlatformUtils.isDevEnvironment) {
var name = "${field.declaringClass.name}.${field.name}"
name = name.replace("at.hannibal2.skyhanni.config.", "")
if (name !in ignoredMissingConfigLinks) {
Expand Down Expand Up @@ -170,7 +171,7 @@ class ConfigManager {
val jsonObject = lenientGson.fromJson(bufferedReader.readText(), JsonObject::class.java)
val newJsonObject = ConfigUpdaterMigrator.fixConfig(jsonObject)
val run = { lenientGson.fromJson(newJsonObject, defaultValue.javaClass) }
if (LorenzUtils.isInDevEnvironment()) {
if (PlatformUtils.isDevEnvironment) {
try {
run()
} catch (e: Throwable) {
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/at/hannibal2/skyhanni/data/ChatManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import at.hannibal2.skyhanni.utils.IdentityCharacteristics
import at.hannibal2.skyhanni.utils.LorenzLogger
import at.hannibal2.skyhanni.utils.LorenzUtils
import at.hannibal2.skyhanni.utils.ReflectionUtils.getClassInstance
import at.hannibal2.skyhanni.utils.ReflectionUtils.getModContainer
import at.hannibal2.skyhanni.utils.ReflectionUtils.makeAccessible
import at.hannibal2.skyhanni.utils.StringUtils.removeColor
import at.hannibal2.skyhanni.utils.chat.Text.send
import at.hannibal2.skyhanni.utils.system.PlatformUtils.getModInstance
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.ChatLine
import net.minecraft.client.gui.GuiNewChat
Expand Down Expand Up @@ -83,10 +83,10 @@ object ChatManager {
val message = packet.message
val component = ChatComponentText(message)
val originatingModCall = event.findOriginatingModCall()
val originatingModContainer = originatingModCall?.getClassInstance()?.getModContainer()
val originatingModContainer = originatingModCall?.getClassInstance()?.getModInstance()
val hoverInfo = listOf(
"§7Message created by §a${originatingModCall?.toString() ?: "§cprobably minecraft"}",
"§7Mod id: §a${originatingModContainer?.modId}",
"§7Mod id: §a${originatingModContainer?.id}",
"§7Mod name: §a${originatingModContainer?.name}"
)
val stackTrace =
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/at/hannibal2/skyhanni/events/LorenzEvent.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import at.hannibal2.skyhanni.mixins.hooks.setValue
import at.hannibal2.skyhanni.mixins.transformers.AccessorEventBus
import at.hannibal2.skyhanni.test.command.ErrorManager
import at.hannibal2.skyhanni.utils.ChatUtils
import at.hannibal2.skyhanni.utils.LorenzUtils
import at.hannibal2.skyhanni.utils.system.PlatformUtils
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.fml.common.eventhandler.Event
import net.minecraftforge.fml.common.eventhandler.IEventListener
Expand All @@ -26,7 +26,7 @@ abstract class LorenzEvent : Event() {
return 0
}
}
val isInGuardedEventHandler get() = eventHandlerDepth > 0 || LorenzUtils.isInDevEnvironment()
val isInGuardedEventHandler get() = eventHandlerDepth > 0 || PlatformUtils.isDevEnvironment
}

fun postAndCatchAndBlock(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package at.hannibal2.skyhanni.events

import net.minecraftforge.fml.common.ModContainer
import at.hannibal2.skyhanni.utils.system.ModInstance
import net.minecraftforge.fml.common.eventhandler.Cancelable

@Cancelable
class MessageSendToServerEvent(
val message: String,
val splitMessage: List<String>,
val originatingModContainer: ModContainer?
val originatingModContainer: ModInstance?
) : LorenzEvent()
2 changes: 1 addition & 1 deletion src/main/java/at/hannibal2/skyhanni/utils/ChatUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ object ChatUtils {
fun MessageSendToServerEvent.isCommand(commandsWithSlash: Collection<String>) =
splitMessage.takeIf { it.isNotEmpty() }?.get(0) in commandsWithSlash

fun MessageSendToServerEvent.senderIsSkyhanni() = originatingModContainer?.modId == "skyhanni"
fun MessageSendToServerEvent.senderIsSkyhanni() = originatingModContainer?.id == "skyhanni"

fun MessageSendToServerEvent.eventWithNewMessage(message: String) =
MessageSendToServerEvent(message, message.split(" "), this.originatingModContainer)
Expand Down
4 changes: 0 additions & 4 deletions src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import net.minecraft.client.entity.EntityPlayerSP
import net.minecraft.client.gui.inventory.GuiEditSign
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.SharedMonsterAttributes
import net.minecraft.launchwrapper.Launch
import net.minecraft.util.AxisAlignedBB
import net.minecraft.util.ChatComponentText
import net.minecraftforge.fml.common.FMLCommonHandler
Expand Down Expand Up @@ -327,9 +326,6 @@ object LorenzUtils {

inline fun <reified T : Enum<T>> T.isAnyOf(vararg array: T): Boolean = array.contains(this)

// TODO move to val by lazy
fun isInDevEnvironment() = ((Launch.blackboard ?: mapOf())["fml.deobfuscatedEnvironment"] as Boolean?) ?: true

fun shutdownMinecraft(reason: String? = null) {
System.err.println("SkyHanni-${SkyHanniMod.version} forced the game to shutdown.")
reason?.let {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/at/hannibal2/skyhanni/utils/NEUItems.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import at.hannibal2.skyhanni.utils.NumberUtil.isInt
import at.hannibal2.skyhanni.utils.PrimitiveItemStack.Companion.makePrimitiveStack
import at.hannibal2.skyhanni.utils.json.BaseGsonBuilder
import at.hannibal2.skyhanni.utils.json.fromJson
import at.hannibal2.skyhanni.utils.system.PlatformUtils
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import com.google.gson.TypeAdapter
Expand Down Expand Up @@ -135,7 +136,7 @@ object NEUItems {
name = name.removePrefix("§7[lvl 1➡100] ")

if (name.contains("[lvl 1➡100]")) {
if (LorenzUtils.isInDevEnvironment()) {
if (PlatformUtils.isDevEnvironment) {
error("wrong name: '$name'")
}
println("wrong name: '$name'")
Expand Down
16 changes: 0 additions & 16 deletions src/main/java/at/hannibal2/skyhanni/utils/ReflectionUtils.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package at.hannibal2.skyhanni.utils

import net.minecraftforge.fml.common.Loader
import net.minecraftforge.fml.common.ModContainer
import java.lang.reflect.Constructor
import java.lang.reflect.Field
import java.lang.reflect.Modifier
Expand Down Expand Up @@ -66,19 +64,5 @@ object ReflectionUtils {
return Class.forName(this.className)
}

private val packageLookup by lazy {
Loader.instance().modList
.flatMap { mod -> mod.ownedPackages.map { it to mod } }
.toMap()
}

val Class<*>.shPackageName
get() =
canonicalName?.substringBeforeLast('.')

fun Class<*>.getModContainer(): ModContainer? {
return packageLookup[shPackageName]
}

fun Class<*>.getDeclaredFieldOrNull(name: String): Field? = declaredFields.firstOrNull { it.name == name }
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import at.hannibal2.skyhanni.events.RepositoryReloadEvent
import at.hannibal2.skyhanni.skyhannimodule.SkyHanniModule
import at.hannibal2.skyhanni.test.command.ErrorManager
import at.hannibal2.skyhanni.utils.ConditionalUtils.afterChange
import at.hannibal2.skyhanni.utils.LorenzUtils
import at.hannibal2.skyhanni.utils.RegexUtils.matches
import at.hannibal2.skyhanni.utils.StringUtils
import at.hannibal2.skyhanni.utils.StringUtils.substringBeforeLastOrNull
import at.hannibal2.skyhanni.utils.system.PlatformUtils
import net.minecraft.launchwrapper.Launch
import net.minecraftforge.fml.common.FMLCommonHandler
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
Expand Down Expand Up @@ -76,7 +76,7 @@ object RepoPatternManager {
}
}

val localLoading: Boolean get() = config.forceLocal.get() || (!insideTest && LorenzUtils.isInDevEnvironment())
val localLoading: Boolean get() = config.forceLocal.get() || (!insideTest && PlatformUtils.isDevEnvironment)

/**
* Crash if in a development environment, or if inside a guarded event handler.
Expand Down
31 changes: 31 additions & 0 deletions src/main/java/at/hannibal2/skyhanni/utils/system/PlatformUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package at.hannibal2.skyhanni.utils.system

import net.minecraft.launchwrapper.Launch
import net.minecraftforge.fml.common.Loader
import net.minecraftforge.fml.common.ModContainer

/**
* This object contains utilities for all platform specific operations.
* i.e. operations that are specific to the mod loader or the environment the mod is running in.
*/
object PlatformUtils {

private val modPackages: Map<String, ModContainer> by lazy {
Loader.instance().modList
.flatMap { mod -> mod.ownedPackages.map { it to mod } }
.toMap()
}

val isDevEnvironment: Boolean by lazy {
Launch.blackboard?.get("fml.deobfuscatedEnvironment") as? Boolean ?: true
}

fun getModFromPackage(packageName: String?): ModInstance? = modPackages[packageName]?.let {
ModInstance(it.modId, it.name, it.version)
}

fun Class<*>.getModInstance(): ModInstance? = getModFromPackage(canonicalName?.substringBeforeLast('.'))

}

data class ModInstance(val id: String, val name: String, val version: String)
Loading