diff --git a/CHANGELOG.md b/CHANGELOG.md index f35a699c2..a3bde3970 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ All notable changes to OneConfig are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Removed +- Removed custom config UI and mod toggle for wWaypoints, as wWaypoints [version] and above now handles this itself + ## [1.10.1] - 2026-12-01 ### Fixed diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java index d084bd73c..8cb6f3904 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java @@ -109,10 +109,6 @@ /*import kotlin.Unit; *///?} -//? if wwaypoints_compat { -import org.polyfrost.oneconfig.internal.compat.WWaypointsCompat; -//?} - public class OneConfig implements ClientModInitializer { public static final OneConfig INSTANCE = new OneConfig(); @@ -398,8 +394,6 @@ private static void registerEventHandlers() { FirmamentHudCompat.register(); //? if > 1.8.9 ArmorHudCompat.register(); - //? if wwaypoints_compat - WWaypointsCompat.register(); ThemeRegistry.INSTANCE.loadFromConfig(); // names Hotwire's types, so it cannot be loaded without Hotwire if (FabricLoader.getInstance().isModLoaded("hotwire")) HotwireLifecycle.register(); diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/toggle/ToggleHooks.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/toggle/ToggleHooks.java index 6b1495ba8..1b3fb5579 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/toggle/ToggleHooks.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/toggle/ToggleHooks.java @@ -82,7 +82,6 @@ public final class ToggleHooks { hook("vignettetweaks", "VignetteAir", "VignetteHealth", "VignetteHunger", "VignetteTotem"); //? if >= 1.21.1 hook("waveycapes", "WaveyCapes"); - hook("wwaypoints", "WWaypoints", "WWaypointsToasts"); hook(YACL, "YaclSave"); hook("yacl-load", "YaclLoad"); hook("zoomify", "Zoomify"); diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/mixin/compat/toggle/Mixin_Toggle_WWaypoints.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/mixin/compat/toggle/Mixin_Toggle_WWaypoints.java deleted file mode 100644 index 1ba33cc36..000000000 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/mixin/compat/toggle/Mixin_Toggle_WWaypoints.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.polyfrost.oneconfig.internal.mixin.compat.toggle; - -import com.llamalad7.mixinextras.injector.ModifyReturnValue; -import org.polyfrost.oneconfig.api.ui.v1.ModToggles; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Pseudo; -import org.spongepowered.asm.mixin.injection.At; - -@Pseudo -@Mixin(targets = "com.wwaypoints.client.ServerFeaturePolicy", remap = false) -public class Mixin_Toggle_WWaypoints { - - @ModifyReturnValue(method = "allows", at = @At("RETURN"), require = 0) - private static boolean oneconfig$disallowWhileOff(boolean original) { - return original && ModToggles.isEnabled("wwaypoints"); - } -} diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/mixin/compat/toggle/Mixin_Toggle_WWaypointsToasts.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/mixin/compat/toggle/Mixin_Toggle_WWaypointsToasts.java deleted file mode 100644 index f41042db9..000000000 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/mixin/compat/toggle/Mixin_Toggle_WWaypointsToasts.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.polyfrost.oneconfig.internal.mixin.compat.toggle; - -import org.polyfrost.oneconfig.api.toggle.v1.ModToggle; -import org.polyfrost.oneconfig.api.ui.v1.ModToggles; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Pseudo; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Pseudo -@Mixin(targets = "com.wwaypoints.client.screen.UiToastRenderer", remap = false) -public class Mixin_Toggle_WWaypointsToasts { - @Unique - private static final ModToggle oneconfig$toggle = ModToggles.handle("wwaypoints"); - - @Inject(method = "render", at = @At("HEAD"), cancellable = true, require = 0) - private static void oneconfig$hideWhileOff(CallbackInfo ci) { - if (!oneconfig$toggle.isEnabled()) ci.cancel(); - } -} diff --git a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/WWaypointsBridge.kt b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/WWaypointsBridge.kt deleted file mode 100644 index 0bb099790..000000000 --- a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/WWaypointsBridge.kt +++ /dev/null @@ -1,361 +0,0 @@ -//? if wwaypoints_compat { -package org.polyfrost.oneconfig.internal.compat - -import com.mojang.blaze3d.platform.InputConstants -import java.lang.reflect.Field -import java.lang.reflect.Method -import java.lang.reflect.Modifier -import java.nio.file.Path -import net.minecraft.client.KeyMapping -import net.minecraft.client.gui.screens.Screen -import org.apache.logging.log4j.LogManager -import org.polyfrost.oneconfig.utils.v1.WrappingUtils - -/** - * reflective access to wWaypoints which is closed-source and not a compile-time dependency so every class - * field and method is looked up by name and cached - * - * any lookup failure leaves [available] false and [WWaypointsCompat] registers nothing - */ -internal object WWaypointsBridge { - - private val LOGGER = LogManager.getLogger("OneConfig/wWaypoints-Compat") - - private const val CLIENT = "com.wwaypoints.WaypointsClient" - private const val CONFIG = "com.wwaypoints.client.ModConfig" - private const val PRESET_STORE = "com.wwaypoints.client.label.preset.LabelPresetStore" - private const val BLOCK_MODEL_HIGHLIGHT = "com.wwaypoints.client.BlockModelHighlightGeometry" - private const val LABEL_RENDERER = "com.wwaypoints.render.WaypointOverlayLabelRenderer" - - private const val SETTINGS_SCREEN = "com.wwaypoints.client.screen.SettingsScreen" - - const val IMPORT_EXPORT_SCREEN = "com.wwaypoints.client.screen.ImportExportScreen" - const val IMPORT_FROM_WORLD_SCREEN = "com.wwaypoints.client.screen.ImportFromWorldScreen" - const val XAERO_IMPORT_SCREEN = "com.wwaypoints.importers.xaero.XaeroImportScreen" - const val PRESET_LIBRARY_SCREEN = "com.wwaypoints.client.screen.PresetLibraryScreen" - - private val classes = HashMap?>() - private val fields = HashMap() - private val methods = HashMap() - - private fun cls(name: String): Class<*>? = classes.getOrPut(name) { - runCatching { Class.forName(name) } - .onFailure { LOGGER.warn("wWaypoints class '{}' not found", name) } - .getOrNull() - } - - private fun method(owner: String, name: String, vararg params: Class<*>): Method? = - methods.getOrPut("$owner#$name/${params.size}") { - runCatching { cls(owner)!!.getMethod(name, *params).apply { isAccessible = true } } - .onFailure { LOGGER.warn("wWaypoints method '{}#{}' not found", owner, name) } - .getOrNull() - } - - private fun configField(name: String): Field? = fields.getOrPut(name) { - runCatching { cls(CONFIG)!!.getField(name).apply { isAccessible = true } } - .onFailure { LOGGER.warn("wWaypoints config field '{}' not found", name) } - .getOrNull() - } - - /** true when every entry point [WWaypointsCompat] depends on resolved successfully */ - val available: Boolean by lazy { - cls(CLIENT) != null && cls(CONFIG) != null && - method(CLIENT, "getConfig") != null && - method(CLIENT, "saveConfig") != null && - config() != null - } - - fun config(): Any? = runCatching { method(CLIENT, "getConfig")?.invoke(null) }.getOrNull() - - fun get(name: String): T? { - val cfg = config() ?: return null - @Suppress("UNCHECKED_CAST") - return runCatching { configField(name)?.get(cfg) as T? }.getOrNull() - } - - fun set(name: String, value: Any?) { - val cfg = config() ?: return - runCatching { configField(name)?.set(cfg, value) } - .onFailure { LOGGER.warn("Failed to write wWaypoints config field '{}'", name, it) } - } - - private val pristineConfig: Any? by lazy { - runCatching { cls(CONFIG)!!.getDeclaredConstructor().apply { isAccessible = true }.newInstance() } - .onFailure { LOGGER.warn("Could not construct a pristine wWaypoints config", it) } - .getOrNull() - } - - fun configDefault(name: String): Any? { - val field = configField(name) ?: return null - if (!WrappingUtils.isSimpleClass(field.type) || Modifier.isStatic(field.modifiers)) return null - return runCatching { field.get(pristineConfig) }.getOrNull() - } - - fun bool(name: String, fallback: Boolean = false): Boolean = get(name) ?: fallback - - fun int(name: String, fallback: Int = 0): Int = get(name)?.toInt() ?: fallback - - fun float(name: String, fallback: Float = 0f): Float = get(name)?.toFloat() ?: fallback - - /** the nested `ModConfig$` enum class or null if it is missing */ - fun enumClass(name: String): Class<*>? = cls("$CONFIG\$$name") - - /** the constant of nested enum [enumName] named [constant] or null */ - fun enumConstant(enumName: String, constant: String): Any? = - enumClass(enumName)?.enumConstants?.firstOrNull { (it as Enum<*>).name == constant } - - private fun typeDefaults(which: String): Any? = get(which) - - fun defaults(name: String): Any? = runCatching { - val defaults = typeDefaults("singleWaypointDefaults") ?: return null - defaults.javaClass.getField(name).apply { isAccessible = true }.get(defaults) - }.getOrNull() - - /** - * writes a field on the single-waypoint defaults and mirrors it into the clump and group defaults like the - * mod's own Defaults page does because 0.7.3 always keeps the three in sync under `UNIFIED` mode - */ - fun setDefaults(name: String, value: Any?) { - runCatching { - val single = typeDefaults("singleWaypointDefaults") ?: return - single.javaClass.getField(name).apply { isAccessible = true }.set(single, value) - set("defaultsMode", enumConstant("DefaultsMode", "UNIFIED")) - val copyFrom = single.javaClass.getMethod("copyFrom", single.javaClass) - listOf("clumpDefaults", "groupDefaults").forEach { other -> - typeDefaults(other)?.let { copyFrom.invoke(it, single) } - } - }.onFailure { LOGGER.warn("Failed to write wWaypoints default '{}'", name, it) } - } - - /** the label presets offered for new waypoints as `id to displayName` */ - fun visiblePresets(): List> = runCatching { - val presets = method(PRESET_STORE, "visiblePresets")?.invoke(null) as? List<*> ?: return emptyList() - val presetClass = cls("com.wwaypoints.client.label.preset.LabelPreset") ?: return emptyList() - val displayName = method(PRESET_STORE, "displayName", presetClass) - val idField = presetClass.getField("id") - presets.mapNotNull { preset -> - preset ?: return@mapNotNull null - val id = idField.get(preset) as? String ?: return@mapNotNull null - if (id.isBlank()) return@mapNotNull null - id to (displayName?.invoke(null, preset) as? String ?: id) - } - }.getOrDefault(emptyList()) - - private const val POLICY = "com.wwaypoints.client.ServerFeaturePolicy" - - /** `WaypointsFeature` bits by constant name, empty before 0.8.0 added server policies */ - private val featureMasks: Map by lazy { - runCatching { - val feature = Class.forName("com.wwaypoints.protocol.WaypointsFeature") - val mask = feature.getMethod("mask") - feature.enumConstants.associate { (it as Enum<*>).name to mask.invoke(it) as Int } - }.getOrDefault(emptyMap()) - } - - /** - * whether the server's policy currently switches off the named `WaypointsFeature`, which switching off - * `ENTIRE_MOD` does to every feature - * - * reads the mask because `allows` also reports false while the mod is switched off from its card - */ - fun disabledByServer(feature: String): Boolean { - val bits = (featureMasks["ENTIRE_MOD"] ?: return false) or (featureMasks[feature] ?: return false) - val mask = runCatching { method(POLICY, "disabledMask")?.invoke(null) as? Int }.getOrNull() ?: return false - return (mask and bits) != 0 - } - - fun addServerPolicyListener(listener: Runnable) { - if (featureMasks.isEmpty()) return - runCatching { method(CLIENT, "addServerPolicyListener", Runnable::class.java)?.invoke(null, listener) } - .onFailure { LOGGER.warn("wWaypoints policy listener registration failed", it) } - } - - fun saveConfig() = invokeClient("saveConfig") - - fun saveWaypoints() = invokeClient("saveWaypoints") - - fun resetConfigToDefaults() = invokeClient("resetConfigToDefaults") - - fun enforceDeathWaypointLimitNow() = invokeClient("enforceDeathWaypointLimitNow") - - fun syncPresetCreateKeybindings() = invokeClient("syncPresetCreateKeybindings") - - fun syncDeathWaypointsHiddenStateAfterToggle(enabled: Boolean) { - runCatching { - method(CLIENT, "syncDeathWaypointsHiddenStateAfterToggle", Boolean::class.javaPrimitiveType!!) - ?.invoke(null, enabled) - }.onFailure { LOGGER.warn("wWaypoints death waypoint sync failed", it) } - } - - fun clearLastAirShapeCache() { - runCatching { method(BLOCK_MODEL_HIGHLIGHT, "clearLastAirShapeCache")?.invoke(null) } - .onFailure { LOGGER.warn("wWaypoints block model cache clear failed", it) } - } - - fun clearSpriteCache() { - runCatching { method(LABEL_RENDERER, "clearSpriteCache")?.invoke(null) } - .onFailure { LOGGER.warn("wWaypoints sprite cache clear failed", it) } - } - - private fun invokeClient(name: String) { - runCatching { method(CLIENT, name)?.invoke(null) } - .onFailure { LOGGER.warn("wWaypoints '{}' failed", name, it) } - } - - fun keyMapping(accessor: String): KeyMapping? = - runCatching { method(CLIENT, accessor)?.invoke(null) as? KeyMapping }.getOrNull() - - /** the mod's dynamic per-preset "create waypoint" mapping or null when it has not been registered yet */ - fun presetCreateKey(presetId: String): KeyMapping? = runCatching { - method(CLIENT, "getPresetCreateWaypointKey", String::class.java)?.invoke(null, presetId) as? KeyMapping - }.getOrNull() - - fun rebindKeyMapping(mapping: KeyMapping, key: InputConstants.Key) { - runCatching { - method(CLIENT, "rebindKeyMapping", KeyMapping::class.java, InputConstants.Key::class.java) - ?.invoke(null, mapping, key) - }.onFailure { LOGGER.warn("wWaypoints rebind failed", it) } - } - - private const val HIDE_CYCLE = "com.wwaypoints.client.HideWaypointCycle" - - private fun cycleConstant(name: String, fallback: Int): Int = - runCatching { cls(HIDE_CYCLE)?.getField(name)?.getInt(null) }.getOrNull() ?: fallback - - fun cycleMaxBlocks(): Int = cycleConstant("MAX_BLOCKS", 100000) - - fun cycleMaxEntries(): Int = cycleConstant("MAX_BLOCKS_IN_CYCLE", 5) - - private fun legacyThreshold(): Int = int("hideWaypointsDistanceThreshold") - - /** runs a cycle through the mod's own normalizer which owns every invariant the editor must respect */ - fun normalizedCycle(raw: IntArray?): IntArray = runCatching { - method(HIDE_CYCLE, "normalize", IntArray::class.java, Int::class.javaPrimitiveType!!) - ?.invoke(null, raw, legacyThreshold()) as? IntArray - }.getOrNull() ?: raw ?: intArrayOf(-1, 0) - - fun nextCycleThreshold(current: IntArray): Int = runCatching { - val next = method(HIDE_CYCLE, "addNextThreshold", IntArray::class.java, Int::class.javaPrimitiveType!!) - ?.invoke(null, current, legacyThreshold()) as? IntArray ?: return@runCatching null - // addNextThreshold returns the whole cycle in its own canonical order so the new entry is found by - // difference rather than by position - val existing = current.toHashSet() - next.firstOrNull { it !in existing } - }.getOrNull() ?: cycleConstant("DEFAULT_WITHIN_BLOCKS", 100) - - /** the unit the first-party editor draws after a distance because `HideWaypointCycle.label` leaves it off */ - const val CYCLE_UNIT = "m" - - fun cycleLabel(value: Int): String { - val label = runCatching { - method(HIDE_CYCLE, "label", Int::class.javaPrimitiveType!!)?.invoke(null, value) as? String - }.getOrNull() ?: value.toString() - return if (value > 0) label + CYCLE_UNIT else label - } - - private const val CONFIG_STORAGE = "com.wwaypoints.client.ConfigStorage" - private const val IMPORT_EXPORT = "com.wwaypoints.client.screen.ImportExportScreen" - private const val TEMPLATE_IO = "com.wwaypoints.client.screen.TemplateImportExportService" - - /** looks up a method the mod does not expose publicly using package-private statics only and never UI state */ - private fun internalMethod(owner: String, name: String, vararg params: Class<*>): Method? = - methods.getOrPut("$owner#$name/${params.size}") { - runCatching { - cls(owner)!!.getDeclaredMethod(name, *params).apply { isAccessible = true } - }.onFailure { LOGGER.warn("wWaypoints method '{}#{}' not found", owner, name) }.getOrNull() - } - - /** the `.wsettings` payload with settings and defaults and pinned icons and label presets */ - fun settingsJson(): String? = runCatching { - method(CONFIG_STORAGE, "toSettingsJson", cls(CONFIG)!!)?.invoke(null, config()) as? String - }.onFailure { LOGGER.warn("Failed to serialize wWaypoints settings", it) }.getOrNull() - - /** applies a `.wsettings` payload and note the mod's parser also replaces the stored label presets */ - fun applySettingsJson(json: String): Boolean = runCatching { - val parsed = method(CONFIG_STORAGE, "fromJson", String::class.java)?.invoke(null, json) ?: return false - method(CLIENT, "applyConfig", cls(CONFIG)!!)?.invoke(null, parsed) - true - }.onFailure { LOGGER.warn("Failed to apply wWaypoints settings", it) }.getOrDefault(false) - - fun currentWorldId(): String? = - runCatching { method(CLIENT, "getCurrentWorldId")?.invoke(null) as? String }.getOrNull() - ?.takeIf { it.isNotBlank() } - - /** - * the current world's waypoints in the mod's own `.wwaypoint` envelope - * - * the per-world object comes from the mod so dimension payloads stay authoritative and only the envelope - * around it is built here because the method that would build it is private - */ - fun exportCurrentWorldJson(exportedAtMillis: Long): String? { - val worldId = currentWorldId() ?: return null - val world = runCatching { - internalMethod(IMPORT_EXPORT, "exportWorld", String::class.java)?.invoke(null, worldId) - }.onFailure { LOGGER.warn("Failed to export wWaypoints world '{}'", worldId, it) }.getOrNull() ?: return null - return """{"format":"wwaypoints","formatVersion":1,"exportedAt":$exportedAtMillis,""" + - """"scope":"CURRENT_WORLD","worlds":[$world]}""" - } - - /** imports a `.wtemplate` file and returns the name the template was stored under */ - fun importTemplateFile(path: Path): String? = runCatching { - internalMethod(TEMPLATE_IO, "importTemplateFile", Path::class.java) - ?.invoke(null, path) as? String - }.onFailure { LOGGER.warn("Failed to import a wWaypoints template", it) }.getOrNull() - - /** shows a message through the mod's own toast so feedback matches its first-party screens */ - fun toast(message: String) { - runCatching { method(CLIENT, "toast", String::class.java)?.invoke(null, message) } - .onFailure { LOGGER.warn("wWaypoints toast failed", it) } - } - - /** the user's label presets as `id to displayName` in store order */ - fun myPresets(): List> = runCatching { - val presets = method(PRESET_STORE, "myPresets")?.invoke(null) as? List<*> ?: return emptyList() - val presetClass = cls("com.wwaypoints.client.label.preset.LabelPreset") ?: return emptyList() - val displayName = method(PRESET_STORE, "displayName", presetClass) - val idField = presetClass.getField("id") - presets.mapNotNull { preset -> - preset ?: return@mapNotNull null - val id = idField.get(preset) as? String ?: return@mapNotNull null - if (id.isBlank()) return@mapNotNull null - id to (displayName?.invoke(null, preset) as? String ?: id) - } - }.getOrDefault(emptyList()) - - /** instantiates one of the mod's own screens returning to [parent] on close */ - fun screen(fqcn: String, parent: Screen?): Screen? = runCatching { - cls(fqcn)?.getConstructor(Screen::class.java)?.newInstance(parent) as? Screen - }.onFailure { LOGGER.warn("Failed to open wWaypoints screen '{}'", fqcn, it) }.getOrNull() - - /** - * the mod's settings screen opened on the named `SettingsScreen.Page` and Data sub-tab where relevant - * - * the page fields are plain assignable fields the mod's own deep-link factories write the same way so if the - * shape ever changes the screen simply opens on its default page - */ - fun settingsScreen(parent: Screen?, page: String, importSubTab: Int = -1): Screen? { - val screen = screen(SETTINGS_SCREEN, parent) ?: return null - runCatching { - val pageClass = cls("$SETTINGS_SCREEN\$Page") ?: return screen - val target = pageClass.enumConstants?.firstOrNull { (it as Enum<*>).name == page } ?: return screen - screen.javaClass.getDeclaredField("page").apply { isAccessible = true }.set(screen, target) - screen.javaClass.getDeclaredField("lastPage").apply { isAccessible = true }.set(screen, target) - if (importSubTab >= 0) { - screen.javaClass.getDeclaredField("importSubTab").apply { isAccessible = true } - .setInt(screen, importSubTab) - } - }.onFailure { LOGGER.warn("Could not target wWaypoints settings page '{}'", page, it) } - return screen - } - - /** the mod's stylist for one of its special waypoint kinds `SUPPLY_DROP` / `AUTO_PICK` / `DEATH` */ - fun specialLabelStylist(kind: String, parent: Screen?): Screen? = runCatching { - val kindClass = cls("com.wwaypoints.client.screen.HopliteAppearanceScreen\$Kind") ?: return null - val constant = kindClass.enumConstants?.firstOrNull { (it as Enum<*>).name == kind } ?: return null - cls(SETTINGS_SCREEN) - ?.getMethod("specialLabelStylist", Screen::class.java, kindClass) - ?.invoke(null, parent, constant) as? Screen - }.onFailure { LOGGER.warn("Failed to open the wWaypoints '{}' stylist", kind, it) }.getOrNull() -} - -//? } diff --git a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/WWaypointsCompat.kt b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/WWaypointsCompat.kt deleted file mode 100644 index 065646f72..000000000 --- a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/WWaypointsCompat.kt +++ /dev/null @@ -1,1182 +0,0 @@ -//? if wwaypoints_compat { -package org.polyfrost.oneconfig.internal.compat - -import com.mojang.blaze3d.platform.InputConstants -import java.nio.file.Files -import java.nio.file.Path -import java.util.function.Consumer -import java.util.function.Function -import java.util.function.Supplier -import net.minecraft.client.KeyMapping -import net.minecraft.client.Minecraft -import net.minecraft.client.gui.screens.Screen -import org.apache.logging.log4j.LogManager -import org.polyfrost.oneconfig.api.config.v1.CompatSnapshots -import org.polyfrost.oneconfig.api.config.v1.Properties -import org.polyfrost.oneconfig.api.config.v1.Property -import org.polyfrost.oneconfig.api.config.v1.Tree -import org.polyfrost.oneconfig.api.config.v1.Visualizer -import org.polyfrost.oneconfig.api.config.v1.dsl.category -import org.polyfrost.oneconfig.api.config.v1.dsl.noCache -import org.polyfrost.oneconfig.api.config.v1.dsl.saveFunction -import org.polyfrost.oneconfig.api.config.v1.dsl.subcategory -import org.polyfrost.oneconfig.api.config.v1.dsl.visualizer -import org.polyfrost.oneconfig.api.platform.v1.ModInfo -import org.polyfrost.oneconfig.api.platform.v1.Platform -import org.polyfrost.oneconfig.api.ui.v1.api.TinyFdApi -import org.polyfrost.oneconfig.api.ui.v1.keybind.KeyModifiers -import org.polyfrost.oneconfig.api.ui.v1.keybind.OneConfigKeybind -import org.polyfrost.oneconfig.api.ui.v1.keybind.internal.MinecraftKeybindCodec -import org.polyfrost.oneconfig.internal.ui.api.HELD_VALUE -import org.polyfrost.oneconfig.internal.ui.api.HeldValue -import org.polyfrost.oneconfig.internal.ui.keybind.MinecraftKeybindRegistrar - -/** - * Renders [wWaypoints](https://modrinth.com/mod/wwaypoints) options as a native OneConfig page instead of the - * Mod Menu Compat placeholder card - * - * The mod is closed-source and not a compile-time dependency so everything goes through [WWaypointsBridge] - * Its own screens keep working because Mod Menu resolves each mod's own factory first and its `K` keybind - * never routes through OneConfig - * - * Settings needing a widget OneConfig does not have yet become link-out buttons onto the first-party screen - */ -object WWaypointsCompat { - - private val LOGGER = LogManager.getLogger("OneConfig/wWaypoints-Compat") - - private const val MOD_ID = "wwaypoints" - - @JvmStatic - fun register() { - // this runs after the entrypoints are decided, so nothing needs retrying - if (!CompatLoader.hasMod(MOD_ID) || ConfigEntrypoints.provides(MOD_ID)) return - // priority 0 so this runs before ModMenuCompat.postLoad (1000) and claims the card first - CompatLoader.requireTranslations(priority = 0, skip = true) { - runCatching { - if (!WWaypointsBridge.available) { - LOGGER.warn("wWaypoints is present but its config could not be resolved; leaving it to Mod Menu compat") - return@requireTranslations - } - val tree = buildTree() - CompatSnapshots.register(tree) - CompatLoader.nativeLoadedConfigs.add(MOD_ID) - }.onFailure { LOGGER.warn("Failed to build the wWaypoints config tree", it) } - } - } - - private fun buildTree(): Tree { - val tree = Tree.tree() - tree.id = MOD_ID - tree.title = "wWaypoints" - // mod writes its config on every row change so OneConfig must never cache values on top of it - tree.noCache = true - tree.saveFunction = Runnable { WWaypointsBridge.saveConfig() } - ModInfo.loadedMods.firstOrNull { it.id == MOD_ID }?.extractIconFile()?.let { - tree.addMetadata("icon_path", it) - } - - buildGeneral(tree) - buildDefaults(tree) - buildIntegrations(tree) - buildControls(tree) - buildData(tree) - buildPresets(tree) - lockWhileDisabledByServer(tree) - return tree - } - - /** The mod closes its own screens while the server switches it off so every row is locked then */ - private fun lockWhileDisabledByServer(tree: Tree) { - val props = tree.map.values.filterIsInstance>() - props.forEach { it.lockedByServer("ENTIRE_MOD") } - WWaypointsBridge.addServerPolicyListener { onClientThread { props.forEach { it.revaluateDisplay() } } } - } - - private fun buildGeneral(tree: Tree) { - tree.put( - switch( - field = "ignoreFov", - name = "Zoom With FOV", - description = "Allows zoom mods to zoom into labels. Uses a fixed FOV baseline.", - tags = listOf("zoom", "fov", "field of view", "optifine", "spyglass"), - ).onChange { enabled -> - // mirrors the first-party row where enabling pins the baseline to the player's current FOV - if (enabled == true) currentFovDegrees()?.let { WWaypointsBridge.set("ignoreFovBaselineDeg", it) } - } - ) - - tree.put( - switch( - field = "deathWaypoints", - name = "Death waypoints", - description = "Create a temporary waypoint at your death location.", - tags = DEATH_TAGS, - ).onChange { WWaypointsBridge.syncDeathWaypointsHiddenStateAfterToggle(it == true) } - ) - tree.put( - linkOut( - id = "death_waypoint_appearance", - name = "Death waypoint appearance", - description = "Style the label and block shown at your death location, and cap how many are kept.", - text = "Configure", - tags = DEATH_TAGS, - ) { WWaypointsBridge.specialLabelStylist("DEATH", currentScreen()) } - ) - - tree.put( - switch( - field = "useBlockModel", - name = "Use Block Model", - description = "When ON, block highlights fit slabs, stairs, buttons, and similar block shapes.", - tags = listOf("block", "model", "shape", "slab", "stairs", "highlight", "hitbox"), - ).onChange { - WWaypointsBridge.clearLastAirShapeCache() - WWaypointsBridge.saveWaypoints() - } - ) - - tree.put( - enumDropdown( - field = "waypointMenuSortOrder", - enumName = "WaypointMenuSortOrder", - fallback = "PROXIMITY", - labels = listOf("Proximity", "Alphabetical", "Custom"), - name = "Sort order", - description = "Applies on new waypoints and when opening the Waypoints menu.", - tags = listOf( - "waypoint list", "list order", "sort waypoints", "sorting", - "alphabetical", "abc", "nearest", "closest", "proximity", "custom", "manual", - ), - ) - ) - - tree.put( - uiScaleDropdown().apply { subcategory = "UI" } - ) - tree.put( - slider( - field = "menuBackgroundDarknessPercent", - name = "Menu background darkness", - description = "How dark the backdrop around menus is.", - min = 0f, - max = 100f, - tags = listOf( - "dark", "darken", "dim", "backdrop", "background", - "brightness", "transparent", "transparency", "opacity", "see through", - ), - ).apply { subcategory = "UI" } - ) - tree.put( - enumDropdown( - field = "uiAnimationMode", - enumName = "UiAnimationMode", - fallback = "ALL", - labels = listOf("All", "Reduced", "None"), - name = "Animations", - description = "All enables full UI motion. Reduced stays non-disruptive and avoids motion that " + - "slows you down. None snaps UI changes.", - tags = listOf( - "less animations", "reduced motion", "no motion", "disable animations", - "instant", "snap", "snappy", "motion", - ), - ).apply { subcategory = "UI" } - ) - } - - private fun uiScaleDropdown(): Property<*> { - // mod stores a float and normalizes it on read while OneConfig's dropdown writes back the selected - // index so translate between the two here rather than exposing the raw float - val prop = Properties.functional( - Supplier { uiScaleIndex(WWaypointsBridge.float("waypointMenuGuiScale", 2f)) }, - Consumer { index -> WWaypointsBridge.set("waypointMenuGuiScale", UI_SCALES.getOrElse(index) { 2f }) }, - "wwaypoints.waypointMenuGuiScale", - "UI Scale", - "Menu size. The middle option adapts for lower resolutions.", - Int::class.java, - ) - prop.visualizer = Visualizer.DropdownVisualizer::class.java - prop.addMetadata("options", listOf("Small", "Medium", "Large")) - prop.category = "General" - prop.addMetadata( - "searchTags", - listOf("big", "bigger", "large", "small", "smaller", "tiny", "medium", "menu size", "ui size", "gui scale", "text size"), - ) - return prop - } - - private val UI_SCALES = floatArrayOf(1f, 2f, 3f) - - /** Mirrors `UiScale.normalizeMenuReferenceScale` mapped onto the dropdown's option indices */ - private fun uiScaleIndex(scale: Float): Int = when { - !scale.isFinite() -> 1 - scale <= 1.5f -> 0 - scale < 2.75f -> 1 - else -> 2 - } - - private fun currentFovDegrees(): Float? = runCatching { - (Minecraft.getInstance().options.fov().get() as? Number)?.toFloat() - }.getOrNull() - - /** - * The mod's Defaults page and the Label section of its composer - * - * 0.7.3 always keeps the single/clump/group defaults identical (`UNIFIED` mode) so these edit the - * single-waypoint set and mirror it like the first-party page does - */ - private fun buildDefaults(tree: Tree) { - defaultLabelPreset()?.let { tree.put(it.defaults("Label")) } - tree.put( - floatSlider( - field = "labelEyeOffset", - name = "Label height", - description = "How far above a waypoint its label floats, in blocks.", - min = 1f, - max = 3f, - step = 0.1f, - tags = listOf("above waypoint", "above head", "vertical", "height", "raise", "lower", "move label"), - ).defaults("Label") - ) - tree.put(labelFadeRange().defaults("Label")) - tree.put( - switch( - field = "labelStylistAlwaysCenterHorizontally", - name = "Always Center X", - description = "Keeps label layers horizontally centred as you edit them.", - tags = listOf("center", "centre", "align", "horizontal", "layout"), - ).defaults("Label") - ) - tree.put( - switch( - field = "labelStylistCenterWhenDone", - name = "Center When Done", - description = "Re-centres the label composition once you finish editing it.", - tags = listOf("center", "centre", "align", "layout", "finish"), - ).defaults("Label") - ) - - if (WWaypointsBridge.enumClass("DefaultsMode") == null) return - tree.put( - defaultsSwitch( - field = "blockThroughWalls", - name = "Block through walls", - description = "Only affects block rendering.", - tags = listOf("through walls", "wall", "xray", "visible behind blocks", "occluded", "block render"), - ).defaults("Block") - ) - tree.put( - inheritablePercent( - field = "outlineOpacityPercent", - globalField = "outlineOpacityPercent", - name = "Outline opacity", - description = "How solid a waypoint block's outline is. Inherits the global outline opacity when unset.", - tags = listOf("outline", "transparent", "transparency", "opacity", "alpha", "border", "see through"), - ).defaults("Block") - ) - tree.put( - inheritablePercent( - field = "fillOpacityPercent", - globalField = "fillOpacityPercent", - name = "Fill opacity", - description = "How solid a waypoint block's fill is. Inherits the global fill opacity when unset.", - tags = listOf("fill", "transparent", "transparency", "opacity", "alpha", "inside", "see through"), - ).defaults("Block") - ) - tree.put( - inheritableThickness().defaults("Block") - ) - } - - /** - * The preset new waypoints get plus the mod's synthetic "Label Off" choice which hides the label instead of - * picking a preset - * - * Built from the presets that exist at startup like the keybind rows - */ - private fun defaultLabelPreset(): Property? { - val presets = WWaypointsBridge.visiblePresets() - if (presets.isEmpty() || WWaypointsBridge.enumClass("DefaultsMode") == null) return null - val values = presets.map { it.first } + LABEL_OFF - val labels = presets.map { it.second } + "Label Off" - - val prop = Properties.functional( - Supplier { - if (WWaypointsBridge.defaults("hiddenLabel") == true) LABEL_OFF - else (WWaypointsBridge.defaults("defaultLabelPresetId") as? String)?.takeIf { it in values } - ?: values.first() - }, - Consumer { selected -> - if (selected == LABEL_OFF) { - WWaypointsBridge.setDefaults("hiddenLabel", true) - } else { - WWaypointsBridge.setDefaults("defaultLabelPresetId", selected) - WWaypointsBridge.setDefaults("hiddenLabel", false) - } - }, - "wwaypoints.defaults.defaultLabelPresetId", - "Default Label Preset", - "Preset applied to newly created items.", - String::class.java, - ) - prop.visualizer = Visualizer.DropdownVisualizer::class.java - prop.addMetadata("options", labels) - prop.addMetadata("optionValues", values) - prop.addMetadata( - "searchTags", - listOf("default preset", "new waypoint", "label style", "appearance", "label off", "hidden", "default label"), - ) - return prop - } - - private const val LABEL_OFF = "oneconfig:label_off" - - /** - * `outlineOpacityPercent`/`fillOpacityPercent` on the defaults are `int`s where any negative value means - * inherit so `-1` is the sentinel and the global field of the same name supplies the inherited value - */ - private fun inheritablePercent( - field: String, - globalField: String, - name: String, - description: String, - tags: List, - ): Property { - val prop = Properties.functional( - Supplier { (WWaypointsBridge.defaults(field) as? Number)?.toInt() ?: -1 }, - Consumer { WWaypointsBridge.setDefaults(field, if (it < 0) -1 else it.coerceAtMost(100)) }, - "wwaypoints.defaults.$field", - name, - description, - Int::class.java, - ) - prop.visualizer = Visualizer.InheritableSliderVisualizer::class.java - prop.addMetadata("min", 0f) - prop.addMetadata("max", 100f) - prop.addMetadata("step", 1f) - prop.addMetadata("inheritSentinel", -1) - prop.addMetadata("inheritedValue", Supplier { WWaypointsBridge.int(globalField) }) - prop.addMetadata("searchTags", tags) - return prop - } - - /** - * `outlineThickness` on the defaults is a boxed `Float` where `null` means inherit so this property is - * nullable and carries no explicit sentinel because writing null hands the value back to the global - */ - @Suppress("UNCHECKED_CAST") - private fun inheritableThickness(): Property { - val prop = Properties.functional( - Supplier { (WWaypointsBridge.defaults("outlineThickness") as? Number)?.toFloat() }, - Consumer { WWaypointsBridge.setDefaults("outlineThickness", it?.coerceIn(0f, 10f)) }, - "wwaypoints.defaults.outlineThickness", - "Outline thickness", - "How thick a waypoint block's outline is. Inherits the global outline thickness when unset.", - Float::class.javaObjectType as Class, - ) - prop.visualizer = Visualizer.InheritableSliderVisualizer::class.java - prop.addMetadata("min", 0f) - prop.addMetadata("max", 10f) - prop.addMetadata("step", 0.5f) - prop.addMetadata("inheritedValue", Supplier { WWaypointsBridge.float("outlineThickness", 2f) }) - prop.addMetadata("searchTags", listOf("outline", "width", "border", "thickness", "thick", "thin", "block outline")) - // compat snapshots cannot record a null so a snapshotted value would resurrect itself on the next - // profile apply and undo inherit - // the opacity rows are unaffected because their -1 sentinel snapshots fine - prop.addMetadata(CompatSnapshots.NO_SNAPSHOT_META, true) - return prop - } - - private fun defaultsSwitch(field: String, name: String, description: String, tags: List): Property { - val prop = Properties.functional( - Supplier { WWaypointsBridge.defaults(field) as? Boolean ?: false }, - Consumer { WWaypointsBridge.setDefaults(field, it) }, - "wwaypoints.defaults.$field", - name, - description, - Boolean::class.java, - ) - prop.visualizer = Visualizer.SwitchVisualizer::class.java - prop.addMetadata("searchTags", tags) - return prop - } - - /** - * The two `labelFade*Blocks` fields as a single start/end pair - * - * They are nullable on disk and the mod reads a missing end of the range as `0` so that is what an unset - * field surfaces as here - */ - private fun labelFadeRange(): Property { - val prop = Properties.functional( - Supplier { - floatArrayOf( - WWaypointsBridge.get("labelFadeStartBlocks")?.toFloat() ?: 0f, - WWaypointsBridge.get("labelFadeEndBlocks")?.toFloat() ?: 0f, - ) - }, - Consumer { range -> - WWaypointsBridge.set("labelFadeStartBlocks", range.getOrElse(0) { 0f }) - WWaypointsBridge.set("labelFadeEndBlocks", range.getOrElse(1) { 0f }) - }, - "wwaypoints.labelFadeRange", - "Fade Range (Blocks)", - "Fade labels out as you get close. Set where the fade starts and where it finishes.", - FloatArray::class.java, - ) - prop.visualizer = Visualizer.RangeSliderVisualizer::class.java - prop.addMetadata("min", 0f) - prop.addMetadata("max", 10f) - prop.addMetadata("step", 0.1f) - prop.addMetadata("searchTags", listOf("fade", "close", "near", "disappear", "distance", "hide near", "range", "visibility")) - return prop - } - - private fun buildIntegrations(tree: Tree) { - val hopliteEnabled = switch( - field = "hopliteEnabled", - name = "Enable Hoplite features", - description = "Master switch for Hoplite-related waypoints and tagging.", - tags = HOPLITE_TAGS, - ) - hopliteEnabled.category = "Integrations" - hopliteEnabled.subcategory = "Hoplite" - tree.put(hopliteEnabled) - - tree.put( - switch( - field = "hopliteAutoSupplyDropWaypoints", - name = "Auto supply drop waypoints", - description = "Automatically creates supply drop waypoints.", - tags = HOPLITE_TAGS + listOf("supply drop", "crate", "airdrop", "loot"), - ).integrations("Hoplite").requires(hopliteEnabled) - ) - tree.put( - linkOut( - id = "hoplite_supply_drop_appearance", - name = "Supply drop appearance", - description = "Style the label and block used for automatic supply drop waypoints.", - text = "Configure", - tags = HOPLITE_TAGS + listOf("supply drop", "crate", "airdrop"), - ) { WWaypointsBridge.specialLabelStylist("SUPPLY_DROP", currentScreen()) } - .integrations("Hoplite").requires(hopliteEnabled) - ) - - tree.put( - switch( - field = "hopliteAutoPickCreatesWaypoint", - name = "Auto pick waypoint", - description = "Creates a waypoint when you auto-pick an item.", - tags = HOPLITE_TAGS + listOf("auto pick", "autopick", "picked item"), - ).integrations("Hoplite").requires(hopliteEnabled) - ) - tree.put( - linkOut( - id = "hoplite_auto_pick_appearance", - name = "Auto pick appearance", - description = "Style the label and block used for auto-pick waypoints.", - text = "Configure", - tags = HOPLITE_TAGS + listOf("auto pick", "autopick"), - ) { WWaypointsBridge.specialLabelStylist("AUTO_PICK", currentScreen()) } - .integrations("Hoplite").requires(hopliteEnabled) - ) - - tree.put( - switch( - field = "signGuiPopup", - name = "Sign GUI popup", - description = "When OFF, placing signs will not open the sign editor.", - tags = SIGN_TAGS, - ).integrations("Extras").lockedByServer("SIGN_MODIFICATIONS") - ) - tree.put( - switch( - field = "showHiddenPotionEffectsOnHud", - name = "Show hidden potion effects (HUD)", - description = "When ON, effects with hideParticles=true still show on the HUD.", - tags = listOf("hidden potion effects", "hud", "status effects", "particles", "beacon"), - ).integrations("Extras") - ) - - buildToggleSneak(tree) - } - - /** - * Native reimplementation of the mod's `ToggleSneakConfigScreen` which is a plain popup of scalar rows - * - * The two `Boolean` fields are tri-state on disk and the mod reads them with `Boolean.TRUE.equals` after - * load so `null` is surfaced as off and only concrete values are ever written back - */ - private fun buildToggleSneak(tree: Tree) { - tree.put( - switch( - field = "toggleSneakStaySneakedInContainers", - name = "Stay Sneaked in Containers", - description = "Keeps Toggle Sneak active while inventory and container screens are open.", - tags = SNEAK_TAGS + listOf("container", "inventory", "chest"), - ).integrations("Toggle Sneak").lockedByServer("SNEAK_MODIFICATIONS", shownOff = true) - ) - tree.put( - switch( - field = "toggleSneakBetterInteractions", - name = "Better Sneak Interactions", - description = "Lets container clicks work with items in hand and waterlogs slabs while toggle-sneaking.", - tags = SNEAK_TAGS + listOf("interactions", "waterlog", "slab"), - ).integrations("Toggle Sneak").lockedByServer("SNEAK_MODIFICATIONS", shownOff = true) - ) - tree.put( - switch( - field = "sneakKeybindOverrides", - name = "Sneak Keybind Overrides", - description = "While Toggle Sneak is enabled, tapping Sneak will cancel Toggle Sneak when you release it.", - tags = SNEAK_TAGS + listOf("override", "cancel", "release", "tap"), - ).integrations("Toggle Sneak").lockedByServer("SNEAK_MODIFICATIONS", shownOff = true) - ) - tree.put( - enumDropdown( - field = "toggleSneakIndicatorMode", - enumName = "ToggleSneakIndicatorMode", - fallback = "OFF", - labels = listOf("Off", "When Crawling", "Always"), - name = "Toggle Sneak Indicator", - description = "Show a persistent \"Toggle Sneak Enabled\" indicator above the hotbar.", - tags = SNEAK_TAGS + listOf("indicator", "crawl", "crawling", "hotbar"), - ).onChange { mode -> - // mod keeps this legacy flag in step with the mode because the crawl renderer still reads it - WWaypointsBridge.set("crawlToggleSneakIndicator", (mode as? Enum<*>)?.name != "OFF") - }.integrations("Toggle Sneak") - ) - } - - private fun buildControls(tree: Tree) { - WWaypointsBridge.syncPresetCreateKeybindings() - - for ((presetId, presetName) in WWaypointsBridge.myPresets()) { - val mapping = WWaypointsBridge.presetCreateKey(presetId) ?: continue - tree.put( - keybind( - id = "preset_create.$presetId", - mapping = mapping, - name = "$presetName Waypoint", - description = "Creates a waypoint using the $presetName preset.", - subcategory = "Create wWaypoint", - tags = listOf("create waypoint", "new waypoint", "preset", presetName), - ) - ) - } - - tree.put( - keybindFor( - accessor = "getOpenWaypointMenuKey", - id = "open_menu", - name = "Open waypoint menu", - description = "Opens the waypoint list/menu.", - subcategory = "Menus & Utility", - tags = listOf("waypoint menu", "waypoint list", "open waypoints", "waypoint screen"), - ) - ) - tree.put( - keybindFor( - accessor = "getOpenWaypointSettingsKey", - id = "open_settings", - name = "Open settings", - description = "Opens wWaypoints settings.", - subcategory = "Menus & Utility", - tags = listOf("settings", "options", "config", "configure"), - ) - ) - tree.put( - keybindFor( - accessor = "getClearUnlockedKey", - id = "clear_unlocked", - name = "Clear unlocked", - description = "Prompts to clear unlocked waypoints.", - subcategory = "Menus & Utility", - tags = listOf("delete unlocked", "remove unlocked", "clear waypoints", "purge"), - ) - ) - - tree.put( - keybindFor( - accessor = "getHideWaypointsKey", - id = "hide_waypoints", - name = "Hide waypoints", - description = "Cycles through waypoint visibility modes.", - subcategory = "Hide Waypoints", - tags = HIDE_TAGS, - ) - ) - tree.put(hideWaypointCycle()) - - tree.put( - keybindFor( - accessor = "getToggleSneakKey", - id = "toggle_sneak", - name = "Toggle Sneak", - description = "Toggles sneak on or off.", - subcategory = "Extras", - tags = SNEAK_TAGS, - ) - ) - tree.put( - keybindFor( - accessor = "getSignGuiPopupToggleKey", - id = "sign_gui_popup_toggle", - name = "Sign GUI popup", - description = "Toggles the Sign GUI popup feature on or off.", - subcategory = "Extras", - tags = SIGN_TAGS, - ).lockedByServer("SIGN_MODIFICATIONS") - ) - } - - /** - * The visibility modes the hide-waypoints keybind steps through - * - * Every edit is round-tripped through the mod's own `HideWaypointCycle.normalize` which owns the rules - * (fixed leading "Show All" / no duplicates / clamped distances / length between two and five) - */ - private fun hideWaypointCycle(): Property { - val prop = Properties.functional( - Supplier { WWaypointsBridge.normalizedCycle(WWaypointsBridge.get("hideWaypointCycleThresholds")) }, - Consumer { WWaypointsBridge.set("hideWaypointCycleThresholds", WWaypointsBridge.normalizedCycle(it)) }, - "wwaypoints.hideWaypointCycleThresholds", - "Cycle Options", - "Press the keybind to cycle through these options from left to right.", - IntArray::class.java, - ) - prop.visualizer = Visualizer.NumberChainVisualizer::class.java - prop.addMetadata("min", 0f) - prop.addMetadata("max", WWaypointsBridge.cycleMaxBlocks().toFloat()) - prop.addMetadata("maxEntries", WWaypointsBridge.cycleMaxEntries()) - prop.addMetadata("unit", WWaypointsBridge.CYCLE_UNIT) - // index 0 is always "Show All" and the mod refuses to move edit or drop it - prop.addMetadata("lockedLeading", 1) - prop.addMetadata("entryLabel", Function { WWaypointsBridge.cycleLabel(it.toInt()) }) - prop.addMetadata("nextValue", Function, Number> { current -> - WWaypointsBridge.nextCycleThreshold(current.map { it.toInt() }.toIntArray()) - }) - prop.category = "Controls" - prop.subcategory = "Hide Waypoints" - prop.addMetadata("searchTags", HIDE_TAGS) - return prop - } - - private fun buildData(tree: Tree) { - tree.put( - linkOut( - id = "import_export", - name = "Import / Export wWaypoints", - // importing needs the mod's merge/override decision flow and exporting every world needs its - // private on-disk layout walk so both stay on the first-party screen - description = "Import wWaypoints data, export every world, or use the clipboard.", - text = "Open", - tags = TRANSFER_TAGS, - ) { WWaypointsBridge.screen(WWaypointsBridge.IMPORT_EXPORT_SCREEN, currentScreen()) } - .data("Waypoints") - ) - tree.put( - linkOut( - id = "import_from_world", - name = "Import From Another World", - description = "Import waypoints from a different world/server into the current one.", - text = "Open", - tags = TRANSFER_TAGS + listOf("world", "server", "realm"), - ) { WWaypointsBridge.screen(WWaypointsBridge.IMPORT_FROM_WORLD_SCREEN, currentScreen()) } - .data("Waypoints") - ) - tree.put( - linkOut( - id = "import_xaero", - name = "Import from Xaero's Minimap", - description = "Imports Xaero minimap waypoints (xaero/minimap or mods/XaeroWaypoints).", - text = "Open", - tags = TRANSFER_TAGS + listOf("xaero", "minimap", "convert", "old waypoints"), - ) { WWaypointsBridge.screen(WWaypointsBridge.XAERO_IMPORT_SCREEN, currentScreen()) } - .data("Waypoints") - ) - - tree.put( - action( - id = "export_world", - name = "Export this world", - description = "Saves the current world's waypoints to a .wwaypoint file.", - text = "Save", - tags = TRANSFER_TAGS + listOf("wwaypoint", "world", "backup"), - ) { exportCurrentWorld() } - .data("Waypoints") - ) - - tree.put( - action( - id = "export_settings", - name = "Export settings", - description = "Saves settings, defaults, pinned icons, and Waypoint Presets to a .wsettings file.", - text = "Save", - tags = TRANSFER_TAGS + listOf("wsettings", "backup", "settings"), - ) { exportSettings() } - .data("Settings") - ) - tree.put( - action( - id = "import_settings", - name = "Import settings", - description = "Loads settings, defaults, pinned icons, and Waypoint Presets from a .wsettings file.", - text = "Open", - tags = TRANSFER_TAGS + listOf("wsettings", "restore", "settings"), - ) { importSettings() } - .data("Settings") - ) - tree.put( - action( - id = "reset_settings", - name = "Reset All Settings", - description = "Resets all wWaypoints settings to defaults.", - text = "Reset All", - tags = listOf("reset", "defaults", "restore defaults", "start over"), - confirmText = "Confirm reset", - ) { resetAllSettings() } - .data("Settings") - ) - tree.put( - linkOut( - id = "factory_reset", - name = "Factory Reset wWaypoints", - description = "Deletes all wWaypoints save data, settings, presets, templates, custom icons, and backups.", - text = "Open", - tags = listOf("wipe", "delete everything", "delete all", "start over", "uninstall", "clean"), - ) { WWaypointsBridge.settingsScreen(currentScreen(), page = "IMPORT", importSubTab = 1) } - .data("Settings") - ) - } - - /** - * The mod builds this envelope in a private method so the row is limited to the current world - * - * The all-worlds variant would mean duplicating its on-disk layout walk which breaks silently on updates - */ - private fun exportCurrentWorld() { - val json = WWaypointsBridge.exportCurrentWorldJson(System.currentTimeMillis()) - if (json == null) { - WWaypointsBridge.toast("Join a world before exporting waypoints.") - return - } - val suggested = "${WWaypointsBridge.currentWorldId() ?: "wwaypoints"}.wwaypoint" - saveFileInBackground("Export wWaypoints", suggested, WWAYPOINT_FILTER, "wWaypoints data") { path -> - Files.writeString(path, json) - WWaypointsBridge.toast("Exported waypoints to ${path.fileName}.") - } - } - - private fun exportSettings() { - val json = WWaypointsBridge.settingsJson() - if (json == null) { - WWaypointsBridge.toast("Could not read wWaypoints settings.") - return - } - saveFileInBackground("Export settings", "wwaypoints.wsettings", WSETTINGS_FILTER, "wWaypoints settings") { path -> - Files.writeString(path, json) - WWaypointsBridge.toast("Exported settings to ${path.fileName}.") - } - } - - private fun importSettings() { - openFileInBackground("Import settings", WSETTINGS_FILTER, "wWaypoints settings") { path -> - val json = Files.readString(path) - onClientThread { - if (WWaypointsBridge.applySettingsJson(json)) { - WWaypointsBridge.saveConfig() - WWaypointsBridge.toast("Imported settings from ${path.fileName}.") - } else { - WWaypointsBridge.toast("That file is not a wWaypoints settings export.") - } - } - } - } - - private fun resetAllSettings() = onClientThread { - WWaypointsBridge.resetConfigToDefaults() - WWaypointsBridge.saveConfig() - WWaypointsBridge.toast("wWaypoints settings reset to defaults.") - } - - private fun importTemplate() { - openFileInBackground("Import template", WTEMPLATE_FILTER, "wWaypoints template") { path -> - onClientThread { - val name = WWaypointsBridge.importTemplateFile(path) - if (name != null) WWaypointsBridge.toast("Imported template \"$name\".") - else WWaypointsBridge.toast("That file is not a wWaypoints template.") - } - } - } - - private val WWAYPOINT_FILTER = arrayOf("*.wwaypoint") - private val WSETTINGS_FILTER = arrayOf("*.wsettings") - private val WTEMPLATE_FILTER = arrayOf("*.wtemplate") - - /** - * Button handlers run on the render thread where a native dialog would freeze the game so every dialog is - * opened from a short-lived worker and the result marshalled back with [onClientThread] - */ - private fun inBackground(block: () -> Unit) { - Thread({ - runCatching(block).onFailure { LOGGER.warn("wWaypoints file action failed", it) } - }, "oneconfig-wwaypoints-dialog").apply { isDaemon = true }.start() - } - - private fun onClientThread(block: () -> Unit) { - Minecraft.getInstance().execute { runCatching(block).onFailure { LOGGER.warn("wWaypoints action failed", it) } } - } - - private fun saveFileInBackground( - title: String, - suggestedName: String, - filters: Array, - filterName: String, - write: (Path) -> Unit, - ) = inBackground { - val chosen = TinyFdApi.getInstance().openSaveSelector(title, suggestedName, filters, filterName) ?: return@inBackground - val target = if (chosen.fileName.toString().contains('.')) chosen else chosen.resolveSibling("${chosen.fileName}${filters[0].removePrefix("*")}") - write(target) - } - - private fun openFileInBackground( - title: String, - filters: Array, - filterName: String, - read: (Path) -> Unit, - ) = inBackground { - val chosen = TinyFdApi.getInstance().openFileSelector(title, null, filters, filterName) ?: return@inBackground - read(chosen) - } - - private fun buildPresets(tree: Tree) { - tree.put( - linkOut( - id = "preset_library", - name = "Manage Presets", - description = "Create, rename, reorder, and style the label presets new waypoints use.", - text = "Open", - tags = listOf("preset", "presets", "library", "label", "stylist", "composer", "appearance"), - ) { WWaypointsBridge.screen(WWaypointsBridge.PRESET_LIBRARY_SCREEN, currentScreen()) } - .apply { category = "Presets"; subcategory = "Presets" } - ) - tree.put( - linkOut( - id = "templates", - name = "Manage Templates", - description = "Apply, rename, reorder, and delete saved waypoint layout templates.", - text = "Open", - tags = listOf("template", "templates", "layout", "group", "structure"), - ) { WWaypointsBridge.settingsScreen(currentScreen(), page = "TEMPLATES") } - .apply { category = "Presets"; subcategory = "Templates" } - ) - tree.put( - action( - id = "import_template", - name = "Import Template", - description = "Adds a waypoint layout template from a .wtemplate file.", - text = "Open", - tags = TRANSFER_TAGS + listOf("template", "templates", "layout", "structure"), - ) { importTemplate() } - .apply { category = "Presets"; subcategory = "Templates" } - ) - } - - private fun switch(field: String, name: String, description: String, tags: List): Property { - val prop = Properties.functional( - Supplier { WWaypointsBridge.bool(field) }, - Consumer { WWaypointsBridge.set(field, it) }, - "wwaypoints.$field", - name, - description, - Boolean::class.java, - ) - prop.visualizer = Visualizer.SwitchVisualizer::class.java - prop.category = "General" - prop.addMetadata("searchTags", tags) - (WWaypointsBridge.configDefault(field) as? Boolean)?.let { prop.addMetadata("default", it) } - return prop - } - - private fun slider( - field: String, - name: String, - description: String, - min: Float, - max: Float, - tags: List, - ): Property { - val prop = Properties.functional( - Supplier { WWaypointsBridge.int(field) }, - Consumer { WWaypointsBridge.set(field, it.coerceIn(min.toInt(), max.toInt())) }, - "wwaypoints.$field", - name, - description, - Int::class.java, - ) - prop.visualizer = Visualizer.SliderVisualizer::class.java - prop.addMetadata("min", min) - prop.addMetadata("max", max) - prop.addMetadata("step", 1f) - prop.category = "General" - prop.addMetadata("searchTags", tags) - (WWaypointsBridge.configDefault(field) as? Number)?.let { prop.addMetadata("default", it.toInt()) } - return prop - } - - private fun floatSlider( - field: String, - name: String, - description: String, - min: Float, - max: Float, - step: Float, - tags: List, - ): Property { - val prop = Properties.functional( - Supplier { WWaypointsBridge.float(field) }, - Consumer { WWaypointsBridge.set(field, it.coerceIn(min, max)) }, - "wwaypoints.$field", - name, - description, - Float::class.java, - ) - prop.visualizer = Visualizer.SliderVisualizer::class.java - prop.addMetadata("min", min) - prop.addMetadata("max", max) - prop.addMetadata("step", step) - prop.category = "General" - prop.addMetadata("searchTags", tags) - (WWaypointsBridge.configDefault(field) as? Number)?.let { prop.addMetadata("default", it.toFloat()) } - return prop - } - - /** - * A dropdown over one of the mod's nested config enums - * - * [fallback] is the constant the mod substitutes when the stored value is `null` and [labels] must be in - * the enum's declaration order - */ - private fun enumDropdown( - field: String, - enumName: String, - fallback: String, - labels: List, - name: String, - description: String, - tags: List, - ): Property { - val enumClass = WWaypointsBridge.enumClass(enumName) - ?: error("wWaypoints enum ModConfig.$enumName is missing") - val fallbackConstant = WWaypointsBridge.enumConstant(enumName, fallback) - ?: error("wWaypoints enum constant ModConfig.$enumName.$fallback is missing") - @Suppress("UNCHECKED_CAST") - val prop = Properties.functional( - Supplier { WWaypointsBridge.get(field) ?: fallbackConstant }, - Consumer { WWaypointsBridge.set(field, it) }, - "wwaypoints.$field", - name, - description, - enumClass as Class, - ) - prop.visualizer = Visualizer.DropdownVisualizer::class.java - prop.addMetadata("options", labels) - prop.category = "General" - prop.addMetadata("searchTags", tags) - prop.addMetadata("default", WWaypointsBridge.configDefault(field)?.takeIf(enumClass::isInstance) ?: fallbackConstant) - return prop - } - - private fun linkOut( - id: String, - name: String, - description: String, - text: String, - tags: List, - screen: () -> Screen?, - ): Property = action(id, name, description, text, tags) { - screen()?.let { Platform.screen().display(it) } - } - - /** A button row that runs [run] rather than handing off to one of the mod's own screens */ - private fun action( - id: String, - name: String, - description: String, - text: String, - tags: List, - confirmText: String? = null, - run: () -> Unit, - ): Property { - val prop = Properties.dummy("wwaypoints.$id", name, description) - prop.visualizer = Visualizer.ButtonVisualizer::class.java - prop.addMetadata("text", text) - if (confirmText != null) prop.addMetadata("confirmText", confirmText) - prop.addMetadata("runnable", Runnable { runCatching(run).onFailure { LOGGER.warn("wWaypoints action '{}' failed", id, it) } }) - prop.category = "General" - prop.addMetadata("searchTags", tags) - return prop - } - - private fun keybindFor( - accessor: String, - id: String, - name: String, - description: String, - subcategory: String, - tags: List, - ): Property<*> { - val mapping = WWaypointsBridge.keyMapping(accessor) - if (mapping == null) { - return unavailableKeybind(id, name, description, subcategory, tags) - } - return keybind(id, mapping, name, description, subcategory, tags) - } - - /** - * Bridges one of the mod's vanilla [KeyMapping]s onto OneConfig's keybind row - * - * The value never lives in OneConfig - * - * Reads convert the mapping's current key and writes go through the mod's own rebind entry point so its - * conflict handling and `options.txt` persistence still run - */ - private fun keybind( - id: String, - mapping: KeyMapping, - name: String, - description: String, - subcategory: String, - tags: List, - ): Property { - val prop = Properties.functional( - Supplier { mapping.toOneConfigKeybind() }, - Consumer { WWaypointsBridge.rebindKeyMapping(mapping, it.toInputKey()) }, - "wwaypoints.key.$id", - name, - description, - OneConfigKeybind::class.java, - ) - prop.visualizer = Visualizer.KeybindVisualizer::class.java - prop.category = "Controls" - prop.subcategory = subcategory - prop.addMetadata("searchTags", tags) - // mapping is already a real vanilla keybind so it must not be mirrored back into the Controls menu - // and Minecraft keybinds are profile-managed by MinecraftKeybindProfiles rather than compat snapshots - prop.addMetadata(MinecraftKeybindRegistrar.NO_MIRROR_METADATA, true) - prop.addMetadata(CompatSnapshots.NO_SNAPSHOT_META, true) - return prop - } - - /** Shown when the mod has not registered a mapping yet because it only picks up new preset binds on restart */ - private fun unavailableKeybind( - id: String, - name: String, - description: String, - subcategory: String, - tags: List, - ): Property { - val prop = Properties.dummy("wwaypoints.key.$id", name, description) - prop.visualizer = Visualizer.InfoVisualizer::class.java - prop.addMetadata("type", "warning") - prop.category = "Controls" - prop.subcategory = subcategory - prop.addMetadata("searchTags", tags) - prop.addMetadata(CompatSnapshots.NO_SNAPSHOT_META, true) - return prop - } - - private fun KeyMapping.toOneConfigKeybind(): OneConfigKeybind { - val key = runCatching { InputConstants.getKey(saveString()) }.getOrDefault(InputConstants.UNKNOWN) - return when (key.type) { - //~ if !sdl 'Type.KEYBOARD' -> 'Type.KEYSYM' - InputConstants.Type.KEYBOARD if key.value > 0 -> - OneConfigKeybind(intArrayOf(key.value), null, KeyModifiers.NONE, 0L) { true } - //~ if !sdl 'key.value > 0' -> 'key.value >= 0' - InputConstants.Type.MOUSE if key.value > 0 -> - OneConfigKeybind(null, intArrayOf(key.value), KeyModifiers.NONE, 0L) { true } - else -> OneConfigKeybind(null, null, KeyModifiers.NONE, 0L) { true } - } - } - - /** wWaypoints mappings are single-key so only the primary input of a combo survives the round trip */ - private fun OneConfigKeybind?.toInputKey(): InputConstants.Key { - if (this == null || !isBound) return InputConstants.UNKNOWN - //~ if !sdl 'it > 0' -> 'it >= 0' - mouseBtns?.firstOrNull { it > 0 }?.let { return MinecraftKeybindCodec.mouse(it) } - keyCodes?.firstOrNull { it > 0 }?.let { return MinecraftKeybindCodec.keysym(it) } - return InputConstants.UNKNOWN - } - - private fun currentScreen(): Screen? = runCatching { Platform.screen().current() }.getOrNull() - - private fun Property.onChange(action: (T?) -> Unit): Property = apply { - addCallback { value -> - runCatching { action(value) }.onFailure { LOGGER.warn("wWaypoints change hook failed for '{}'", id, it) } - false - } - } - - private fun Property.integrations(subcategory: String): Property = apply { - category = "Integrations" - this.subcategory = subcategory - } - - private fun Property.data(subcategory: String): Property = apply { - category = "Data" - this.subcategory = subcategory - } - - private fun Property.defaults(subcategory: String): Property = apply { - category = "Defaults" - this.subcategory = subcategory - } - - /** - * Greys the row out while the server's policy switches off the named `WaypointsFeature` - * - * [shownOff] also shows the switch as off meanwhile like the mod's own screen does, without touching the - * stored value - */ - private fun Property.lockedByServer(feature: String, shownOff: Boolean = false): Property = apply { - addDisplayCondition(Supplier { - val locked = WWaypointsBridge.disabledByServer(feature) - // kept in step here because display listeners are only told after every condition was evaluated - if (shownOff) if (locked) addMetadata(HELD_VALUE, HeldValue(false)) else removeMetadata(HELD_VALUE) - if (locked) Property.Display.DISABLED else Property.Display.SHOWN - }) - } - - /** Greys the row out rather than hiding it while [condition] is off matching the first-party screen */ - private fun Property.requires(condition: Property): Property = - apply { addDisplayCondition(condition, false) } - - // search vocabulary mirroring the mod's own SettingsSearchVocabulary - private val DEATH_TAGS = listOf( - "die", "died", "dead", "killed", "grave", "corpse", "death marker", - "last death", "recover items", "respawn", - ) - - private val HOPLITE_TAGS = listOf("hoplite", "uhc", "event", "server", "integration") - - private val SNEAK_TAGS = listOf( - "shift", "crouch", "crouching", "sneak", "sneaking", "toggle sneak", "hold sneak", - ) - - private val SIGN_TAGS = listOf( - "sign", "signs", "sign popup", "sign editor", "edit sign", "placing signs", "pop up", - ) - - private val HIDE_TAGS = listOf( - "hide", "show", "visibility", "visible", "invisible", "waypoint visibility", - "visibility mode", "cycle", "labels", "blocks", - ) - - private val TRANSFER_TAGS = listOf( - "import", "export", "backup", "restore", "share", "send", "receive", - "copy", "paste", "clipboard", "file", "transfer", "migrate", - ) -} - -//? } diff --git a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/toggle/ModGates.kt b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/toggle/ModGates.kt index 7d3847f6b..6e72e0e0a 100644 --- a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/toggle/ModGates.kt +++ b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/toggle/ModGates.kt @@ -171,7 +171,6 @@ internal object ModGates { } }), Gate("tooltipscroll", onToggle = { callStatic("com.provismet.tooltipscroll.ScrollTracker", "reset") }), - Gate("wwaypoints"), Gate("appleskin"), Gate("detailabreconst"), Gate("status-effect-bars"), diff --git a/minecraft/stonecutter.gradle.kts b/minecraft/stonecutter.gradle.kts index f25a9fdc2..7d9586f6f 100644 --- a/minecraft/stonecutter.gradle.kts +++ b/minecraft/stonecutter.gradle.kts @@ -48,7 +48,6 @@ stonecutter { this["tr7zw_compat"] = true this["ukulib_compat"] = current.project.endsWith("-fabric") this["axolotlclient_config_compat"] = true - this["wwaypoints_compat"] = current.project.endsWith("-fabric") this["cinnabar"] = catalogue.has("cinnabar") && rootProject.hasProperty("minecraft.vulkan") this["vulkanmod"] = current.project.endsWith("-fabric") && catalogue.has("vulkanmod") }