Skip to content

Commit

Permalink
refactor: regroup the modules
Browse files Browse the repository at this point in the history
  • Loading branch information
SettingDust committed Apr 18, 2024
1 parent 13fbf8c commit fd64553
Show file tree
Hide file tree
Showing 39 changed files with 364 additions and 318 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -40,36 +40,29 @@ object ModSetsConfig {
fun load() {
try {
configDir.createDirectories()
} catch (_: Exception) {
}
} catch (_: Exception) {}

try {
disabledModsPath.createFile()
} catch (_: Exception) {
}
} catch (_: Exception) {}

try {
commonConfigPath.createFile()
} catch (_: Exception) {
}
} catch (_: Exception) {}

try {
disabledMods.clear()
disabledMods.addAll(json.decodeFromStream(disabledModsPath.inputStream()))
} catch (_: Exception) {
}
} catch (_: Exception) {}

try {
common = json.decodeFromStream(commonConfigPath.inputStream())
} catch (_: Exception) {
}
} catch (_: Exception) {}
save()
}

fun save() {
commonConfigPath.outputStream().use {
json.encodeToStream(common, it)
}
commonConfigPath.outputStream().use { json.encodeToStream(common, it) }
disabledModsPath.outputStream().use {
json.encodeToStream(
disabledMods,
Expand Down
7 changes: 7 additions & 0 deletions common/config/src/main/kotlin/settingdust/modsets/ModSets.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package settingdust.modsets

import org.apache.logging.log4j.LogManager

object ModSets {
val LOGGER = LogManager.getLogger()
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import java.util.*
interface PlatformHelper {
companion object {
@JvmStatic
val INSTANCE = ServiceLoader.load(PlatformHelper::class.java, Companion::class.java.classLoader).first()!!
val INSTANCE =
ServiceLoader.load(PlatformHelper::class.java, Companion::class.java.classLoader)
.first()!!

val configDir: Path
get() = INSTANCE.configDir
Expand Down
2 changes: 1 addition & 1 deletion ingame/build.gradle.kts → common/ingame/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ dependencies {
"maven.modrinth:kinecraft-serialization:${catalog.kinecraft.serialization.get().version}-fabric"
)

api(project(":config"))
api(project(":common:config"))
}

tasks {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ data class CyclingRule(val mods: List<String>) : RuleController {
}
.toList()
if (enabledModSet.size > 1) {
ModSets.logger.warn(
ModSets.LOGGER.warn(
"More than one mod is enabled in cycling list: ${enabledModSet.joinToString()}. Will take the first and disable the others"
)
ModSets.config.disabledMods.addAll(
Expand All @@ -176,7 +176,7 @@ data class CyclingRule(val mods: List<String>) : RuleController {
)
return@generic enabledModSet.first()
} else if (enabledModSet.isEmpty()) {
ModSets.logger.warn(
ModSets.LOGGER.warn(
"None mod is enabled in cycling list: ${mods.joinToString()}. Will take the first and disable the others"
)
}
Expand Down
195 changes: 195 additions & 0 deletions common/ingame/src/main/kotlin/settingdust/modsets/game/Rules.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
package settingdust.modsets.game

import dev.isxander.yacl3.api.Binding
import dev.isxander.yacl3.api.ConfigCategory
import dev.isxander.yacl3.api.ListOption
import dev.isxander.yacl3.api.Option
import dev.isxander.yacl3.api.OptionDescription
import dev.isxander.yacl3.api.YetAnotherConfigLib
import dev.isxander.yacl3.api.controller.StringControllerBuilder
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.encodeToStream
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.contextual
import net.minecraft.client.gui.screens.Screen
import net.minecraft.network.chat.Component
import settingdust.kinecraft.serialization.ComponentSerializer
import settingdust.kinecraft.serialization.GsonElementSerializer
import settingdust.modsets.ModSets
import settingdust.modsets.PlatformHelper
import settingdust.modsets.config
import kotlin.io.path.createDirectories
import kotlin.io.path.createFile
import kotlin.io.path.div
import kotlin.io.path.inputStream
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.name
import kotlin.io.path.nameWithoutExtension
import kotlin.io.path.outputStream
import kotlin.io.path.writeText

@OptIn(ExperimentalSerializationApi::class)
@Deprecated("Use ModSets.rules instead", ReplaceWith("ModSets.rules"))
object Rules : MutableMap<String, RuleSet> by mutableMapOf() {
private val configDir = PlatformHelper.configDir / "modsets"

val modSets = mutableMapOf<String, ModSet>()
val ModSetsRegisterCallbacks = mutableSetOf<() -> Unit>()

private val definedModSets = mutableMapOf<String, ModSet>()
private val modSetsPath = configDir / "modsets.json"

private val rulesDir = configDir / "rules"

private val json = Json {
encodeDefaults = true
ignoreUnknownKeys = true
isLenient = true
serializersModule = SerializersModule {
contextual(ComponentSerializer)
contextual(GsonElementSerializer)
}
prettyPrint = true
}

fun MutableMap<String, ModSet>.getOrThrow(name: String) =
requireNotNull(get(name)) { "Mod sets $name not exist" }

private val config: YetAnotherConfigLib
get() {
load()
val builder =
YetAnotherConfigLib.createBuilder().title(Component.translatable("modsets.name"))
if (ModSets.config.common.displayModSetsScreen && modSets.isNotEmpty()) {
builder.category(
ConfigCategory.createBuilder()
.apply {
name(Component.translatable("modsets.name"))
tooltip(Component.translatable("modsets.description"))
groups(
modSets.map { (name, modSet) ->
ListOption.createBuilder<String>()
.apply {
name(modSet.text)
modSet.description?.let {
description(OptionDescription.of(it))
}
initial("")
collapsed(true)
controller { StringControllerBuilder.create(it) }
binding(
Binding.generic(
modSet.mods.toMutableList(),
{ modSet.mods.toMutableList() }
) {
modSet.mods.clear()
modSet.mods.addAll(it)
definedModSets[name] = modSet
},
)
}
.build()
},
)
}
.build(),
)
}
if (this@Rules.isNotEmpty()) {
val options = mutableSetOf<Option<Any>>()
builder.categories(
this@Rules.map { (_, ruleSet) ->
val category =
ConfigCategory.createBuilder()
.apply {
name(ruleSet.text)
ruleSet.description?.let { tooltip(it) }
ruleSet.rules.forEach { it.controller.build(this, it) }
}
.build()
// Since the options are instant and may be affected by the others. Update
// the changed options to correct value
val optionsInCategory =
category.groups().flatMap { it.options() as Iterable<Option<Any>> }
options.addAll(optionsInCategory)
for (option in optionsInCategory) {
option.addListener { _, _ ->
var changed = false
for (it in options.filter { it != option && it.changed() }) {
it.requestSet(it.binding().value)
if (!changed && option.changed()) {
ModSets.LOGGER.warn(
"Option ${option.name()} is conflicting with ${it.name()}. Can't change"
)
changed = true
}
}
if (option.changed()) {
ModSets.LOGGER.warn(
"Option ${option.name()} is conflicting with unknown option. Can't change"
)
option.requestSet(option.binding().value)
}
save() // The save won't be called with instant
}
}
category
},
)
} else {
builder.category(
ConfigCategory.createBuilder()
.name(Component.translatable("modsets.no_rules"))
.build(),
)
}
return builder.save(ModSets.rules::save).build()
}

init {
load()
}

private fun load() {
ModSets.config.load()
try {
rulesDir.createDirectories()
} catch (_: Exception) {}

try {
modSetsPath.createFile()
modSetsPath.writeText("{}")
} catch (_: Exception) {}

definedModSets.clear()
modSets.clear()
modSetsPath.inputStream().use { definedModSets.putAll(json.decodeFromStream(it)) }
modSets.putAll(definedModSets)
runBlocking { ModSetsRegisterCallbacks.forEach { it() } }

clear()
rulesDir.listDirectoryEntries("*.json").forEach {
try {
it.inputStream().use { stream ->
this[it.nameWithoutExtension] = json.decodeFromStream(stream)
}
} catch (e: Exception) {
ModSets.LOGGER.error("Failed to load rule ${it.name}", e)
}
}
}

private fun save() {
ModSets.config.save()
modSetsPath.outputStream().use { json.encodeToStream(definedModSets, it) }
}

fun createScreen(parent: Screen) = config.generateScreen(parent)
}

@Suppress("DEPRECATION", "UnusedReceiverParameter")
val ModSets.rules: Rules
get() = Rules
8 changes: 0 additions & 8 deletions config/src/main/kotlin/settingdust/modsets/ModSets.kt

This file was deleted.

29 changes: 16 additions & 13 deletions fabric/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ loom {
mods {
create(archives_name) {
sourceSet("main")
sourceSet("main", project(":config"))
sourceSet("main", project(":ingame"))
sourceSet("main", project(":common:config"))
sourceSet("main", project(":common:ingame"))
dependency(
catalog.kotlinx.serialization.core.get(),
catalog.kotlinx.serialization.json.get(),
Expand All @@ -34,7 +34,7 @@ loom {
}
}

tasks { processResources { from(project(":ingame").sourceSets.main.get().resources) } }
tasks { processResources { from(project(":common:ingame").sourceSets.main.get().resources) } }

repositories {
exclusiveContent {
Expand Down Expand Up @@ -62,27 +62,30 @@ dependencies {
implementation(catalog.kotlinx.coroutines)
implementation(catalog.kotlin.reflect)

implementation(project(path = ":config", configuration = "namedElements")) {
implementation(project(path = ":common:config", configuration = "namedElements")) {
isTransitive = false
}
include(project(":config"))
include(project(":common:config"))

implementation(project(path = ":ingame", configuration = "namedElements")) {
implementation(project(path = ":common:ingame", configuration = "namedElements")) {
isTransitive = false
}
include(project(":ingame"))
include(project(":common:ingame"))

modImplementation(catalog.fabric.loader)
modRuntimeOnly(catalog.fabric.kotlin) { exclude(module = "fabric-loader") }

modRuntimeOnly(catalog.yacl.fabric) { isTransitive = false }
modRuntimeOnly(catalog.modmenu) { exclude(module = "fabric-loader") }

val kinecraft =
"maven.modrinth:kinecraft-serialization:${catalog.kinecraft.serialization.get().version}-fabric"
modRuntimeOnly(kinecraft)
include(kinecraft)
catalog.kinecraft.serialization.get().copy().let {
it.version { require("$requiredVersion-fabric") }
modRuntimeOnly(it)
include(it)
}

implementation(catalog.preloading.tricks)
include(catalog.preloading.tricks)
catalog.preloading.tricks.let {
implementation(it)
include(it)
}
}

0 comments on commit fd64553

Please sign in to comment.