From 302712f0dc34ba561143526aaf86883da0d223e0 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 20 Nov 2026 05:54:22 +0100 Subject: [PATCH 01/12] feat(config): rebind configs and trees put back after a profile switch --- .../api/config/v1/CompatSnapshots.java | 12 + .../api/config/v1/ConfigManager.java | 71 +++++ .../api/config/v1/DetachedRebindTest.java | 278 ++++++++++++++++++ 3 files changed, 361 insertions(+) create mode 100644 modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java diff --git a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/CompatSnapshots.java b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/CompatSnapshots.java index 84948f828..3f9d39681 100644 --- a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/CompatSnapshots.java +++ b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/CompatSnapshots.java @@ -337,6 +337,18 @@ private void applyProfile0(Tree tree, String profile) { if (changed[0] && ownerStillThere) runSave(tree); } + // for a tree that missed the switch to the active profile, which a new profile would have reset + void applyOrReset(Tree tree) { + String profile = ConfigManager.activeProfile(); + if (store.load(profile).containsKey(tree.getID())) { + applyProfile(tree, profile); + return; + } + restoreDefaults(tree); + captureAll(tree, profile); + flushSnapshotThenBaseline(store, profile, baselineStore, BASELINE_BUCKET); + } + public static void capture(Tree tree) { if (tree == null || !Boolean.TRUE.equals(tree.getMetadata(TAG))) return; INSTANCE.captureAll(tree, ConfigManager.activeProfile()); diff --git a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java index 8f8ad94b3..8c76af5ba 100644 --- a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java +++ b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java @@ -84,6 +84,8 @@ public final class ConfigManager { private static boolean isFirstRun = false; private static final Queue pendingInitialization = new ArrayDeque<>(); private static final Map initializedConfigs = new LinkedHashMap<>(); + // backends a profile switch closed, kept as whatever took a tree out of one before the switch puts it back there + private static final List retired = new ArrayList<>(); private static final ReentrantLock PROFILE_LIFECYCLE_LOCK = new ReentrantLock(); private static final long PROFILE_OPERATION_BUDGET_NANOS = TimeUnit.SECONDS.toNanos(30L); private static final long MINIMUM_WAIT_NANOS = TimeUnit.MILLISECONDS.toNanos(500L); @@ -261,6 +263,15 @@ static boolean didInitializationFail(Config config) { return failedInitialization.contains(config.id); } + /** + * Makes configs created from now on wait for the next {@link #initialize()} again, for mods that start after + * the game did + */ + @ApiStatus.Internal + public static void reopenInitialization() { + initialized = false; + } + @ApiStatus.Internal public static void submitForInitialization(Config config) { // never initialize synchronously here because this runs from the Config base constructor @@ -472,6 +483,11 @@ private static void openProfile(String profile, boolean restoreDefaults) { externalTrees.add(t); } active.close(); + // emptied so that a tree put back later stands out, see rebindDetached() + for (Tree t : new ArrayList<>(active.trees())) { + if (t.getID() != null) active.unregister(t.getID()); + } + retired.add(active); } internal().get("profiles.json").getProp("activeProfile").setAs(profile); internal().save("profiles.json"); @@ -507,6 +523,61 @@ private static void openProfile(String profile, boolean restoreDefaults) { } } + /** + * Binds what is registered but not on the active profile to it: configs whose tree is not in the active backend, + * and trees put back into a backend that a profile switch has closed. Hotwire returns a mod's objects to where it + * took them from when the mod went off, which is no longer where they belong if the profile changed since. + *
+ * Each is loaded from the active profile, or reset to its defaults when the profile has nothing stored for it + */ + @ApiStatus.Internal + public static synchronized void rebindDetached() { + ConfigManager mgr = activeLocked(); + boolean wasRebinding = REBINDING_PROFILES.get(); + REBINDING_PROFILES.set(Boolean.TRUE); + try { + for (Config config : new ArrayList<>(initializedConfigs.values())) { + if (mgr.tracks(config.tree)) continue; + try { + config.rebindToActiveProfile(!Files.exists(mgr.getFolder().resolve(config.id))); + } catch (Throwable t) { + LOGGER.error("Failed to rebind config {} onto the active profile", config.id, t); + } + } + for (ConfigManager closed : retired) { + for (Tree tree : new ArrayList<>(closed.trees())) { + closed.unregister(tree.getID()); + try { + mgr.adopt(tree); + } catch (Throwable t) { + LOGGER.error("Failed to rebind tree {} onto the active profile", tree.getID(), t); + } + } + } + } finally { + if (wasRebinding) REBINDING_PROFILES.set(Boolean.TRUE); + else REBINDING_PROFILES.remove(); + } + } + + private boolean tracks(@Nullable Tree tree) { + return tree != null && tree.getID() != null && backend.exists(tree.getID()) && backend.get(tree.getID()) == tree; + } + + private void adopt(Tree tree) { + String id = tree.getID(); + // configs build their tree anew and HUDs are loaded from their files, so only what nothing else brings back + if (initializedConfigs.containsKey(id) || Boolean.TRUE.equals(tree.getMetadata(PROFILE_LOCAL_METADATA))) return; + // left alone if something registered it anew in the meantime, as registering over that would clear the tree + if (backend.exists(id) && !Boolean.TRUE.equals(backend.get(id).getMetadata(Backend.UI_PLACEHOLDER_METADATA))) return; + boolean snapshot = Boolean.TRUE.equals(tree.getMetadata(CompatSnapshots.SNAPSHOT_METADATA)); + if (!snapshot && !Boolean.TRUE.equals(tree.getMetadata(Backend.UI_ONLY_METADATA)) && !Files.exists(getFolder().resolve(id))) { + Config.restoreCapturedDefaults(tree); + } + register(tree); + if (snapshot) CompatSnapshots.INSTANCE.applyOrReset(tree); + } + public static synchronized String activeProfile() { activeLocked(); String profile = internal().get("profiles.json").getProp("activeProfile").getAs(); diff --git a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java new file mode 100644 index 000000000..4cfc4c289 --- /dev/null +++ b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java @@ -0,0 +1,278 @@ +/* + * This file is part of OneConfig. + * OneConfig - Next Generation Config Library for Minecraft: Java Edition + * Copyright (C) 2021~2024 Polyfrost. + * + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * OneConfig is licensed under the terms of version 3 of the GNU Lesser + * General Public License as published by the Free Software Foundation, AND + * under the Additional Terms Applicable to OneConfig, as published by Polyfrost, + * either version 1.0 of the Additional Terms, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License. If not, see . You should + * have also received a copy of the Additional Terms Applicable + * to OneConfig, as published by Polyfrost. If not, see + * + */ + +package org.polyfrost.oneconfig.api.config.v1; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.polyfrost.oneconfig.api.config.v1.annotations.Switch; +import org.polyfrost.oneconfig.api.config.v1.backend.Backend; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * What {@link ConfigManager#rebindDetached()} has to repair after Hotwire turned a mod off and on again: Hotwire takes + * the mod's config and trees out of OneConfig's maps and later puts the same objects back into the same maps + */ +class DetachedRebindTest { + private static final String PROFILE_A = "oc_detached_profile_a"; + private static final String PROFILE_B = "oc_detached_profile_b"; + private static final String CONFIG = "detached_rebind_test.json"; + private static final String COMPAT = "detached_rebind_compat"; + + @BeforeEach + void setUp() throws Exception { + ConfigManager.active(); + ConfigManager.openProfile(""); + cleanup(); + } + + @AfterEach + void tearDown() throws Exception { + ConfigManager.openProfile(""); + cleanup(); + } + + @Test + void configPutBackAfterASwitchGetsTheNewProfilesValues() throws Exception { + DetachedConfig config = configWith(true); + ConfigManager.createProfile(PROFILE_A); + assertFalse(config.enabled, "the new profile starts from the defaults"); + ConfigManager.openProfile(""); + Off off = turnOff(config); + + ConfigManager.openProfile(PROFILE_A); + off.turnOn(); + ConfigManager.rebindDetached(); + + assertFalse(config.enabled); + assertSame(config.getTree(), ConfigManager.active().get(CONFIG)); + config.enabled = true; + config.save(); + ConfigManager.openProfile(""); + assertTrue(config.enabled, "the profile it went off in keeps its own value"); + ConfigManager.openProfile(PROFILE_A); + assertTrue(config.enabled, "what it saved after coming back went to the profile it came back in"); + } + + @Test + void configPutBackAfterSwitchingAwayAndBackKeepsItsValues() throws Exception { + DetachedConfig config = configWith(true); + ConfigManager.createProfile(PROFILE_A); + ConfigManager.openProfile(""); + Off off = turnOff(config); + + ConfigManager.openProfile(PROFILE_A); + ConfigManager.openProfile(""); + off.turnOn(); + ConfigManager.rebindDetached(); + + assertTrue(config.enabled); + assertSame(config.getTree(), ConfigManager.active().get(CONFIG), "the same profile name is still a new backend"); + } + + @Test + void configPutBackOnAProfileWithoutItsFileGetsItsDefaults() throws Exception { + DetachedConfig config = configWith(true); + Off off = turnOff(config); + + ConfigManager.createProfile(PROFILE_A); + assertFalse(Files.exists(ConfigManager.profileDir(PROFILE_A).resolve(CONFIG))); + off.turnOn(); + ConfigManager.rebindDetached(); + + assertFalse(config.enabled); + assertTrue(Files.exists(ConfigManager.profileDir(PROFILE_A).resolve(CONFIG))); + ConfigManager.openProfile(""); + assertTrue(config.enabled, "the profile it went off in keeps its own value"); + } + + @Test + void configPutBackAfterItsProfileWasRenamedKeepsItsValues() throws Exception { + ConfigManager.createProfile(PROFILE_A); + DetachedConfig config = configWith(true); + Off off = turnOff(config); + + ConfigManager.renameProfile(PROFILE_A, PROFILE_B); + off.turnOn(); + ConfigManager.rebindDetached(); + + assertTrue(config.enabled); + assertSame(config.getTree(), ConfigManager.active().get(CONFIG)); + } + + // Hotwire 0.9.5.1 also resets Config.tree of a mod it turned off, even when the profile never changed + @Test + void configWhoseTreeWasForgottenSurvivesTheNextProfileSwitch() throws Exception { + DetachedConfig config = configWith(true); + Off off = turnOff(config); + config.tree = null; + off.turnOn(); + ConfigManager.rebindDetached(); + + assertSame(config.getTree(), ConfigManager.active().get(CONFIG)); + ConfigManager.createProfile(PROFILE_A); + ConfigManager.openProfile(""); + assertTrue(config.enabled, "its value on the profile it went off in was overwritten"); + } + + @Test + void compatTreePutBackAfterASwitchGetsTheNewProfilesValues() throws Exception { + Property value = Properties.simple("value", "Value", "", 1); + Tree tree = CompatSnapshots.register(Tree.tree(COMPAT).put(value)); + value.setAs(5); + ConfigManager.createProfile(PROFILE_A); + value.setAs(9); + ConfigManager.openProfile(""); + assertEquals(5, value.get()); + Off off = turnOff(tree); + + ConfigManager.openProfile(PROFILE_A); + off.turnOn(); + ConfigManager.rebindDetached(); + + assertEquals(9, value.get()); + assertSame(tree, ConfigManager.active().get(COMPAT)); + ConfigManager.openProfile(""); + assertEquals(5, value.get(), "the profile it went off in keeps its own value"); + } + + @Test + void compatTreePutBackOnAProfileMadeMeanwhileGetsItsDefaults() throws Exception { + Property value = Properties.simple("value", "Value", "", 1); + Tree tree = CompatSnapshots.register(Tree.tree(COMPAT).put(value)); + value.setAs(5); + Off off = turnOff(tree); + + ConfigManager.createProfile(PROFILE_A); + off.turnOn(); + ConfigManager.rebindDetached(); + + assertEquals(1, value.get()); + ConfigManager.openProfile(""); + assertEquals(5, value.get(), "the profile it went off in keeps its own value"); + } + + private static DetachedConfig configWith(boolean enabled) { + DetachedConfig config = new DetachedConfig(); + config.initialize(false); + config.enabled = enabled; + config.save(); + return config; + } + + /** Takes a config out the way Hotwire does at a mod's off, after everything was saved as OneConfig's listener does */ + private static Off turnOff(Config config) throws Exception { + ConfigManager.active().saveAll(); + ConfigManager manager = ConfigManager.active(); + Tree tree = config.tree; + configs().remove(config.id); + manager.unregister(config.id); + return () -> { + configs().put(config.id, config); + trees(manager).put(tree.getID(), tree); + }; + } + + private static Off turnOff(Tree compat) throws Exception { + ConfigManager.active().saveAll(); + CompatSnapshots.INSTANCE.onProfileSaving(ConfigManager.activeProfile()); + ConfigManager manager = ConfigManager.active(); + manager.unregister(compat.getID()); + known().remove(compat.getID()); + return () -> { + known().put(compat.getID(), compat); + trees(manager).put(compat.getID(), compat); + }; + } + + private interface Off { + void turnOn() throws Exception; + } + + @SuppressWarnings("unchecked") + private static Map configs() throws Exception { + return (Map) read(ConfigManager.class, null, "initializedConfigs"); + } + + @SuppressWarnings("unchecked") + private static Map known() throws Exception { + return (Map) read(CompatSnapshots.class, CompatSnapshots.INSTANCE, "known"); + } + + @SuppressWarnings("unchecked") + private static Map trees(ConfigManager manager) throws Exception { + return (Map) read(Backend.class, manager.backend, "trees"); + } + + private static Object read(Class type, Object target, String name) throws Exception { + Field field = type.getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } + + private static void cleanup() throws Exception { + configs().remove(CONFIG); + ConfigManager.active().delete(CONFIG); + ConfigManager.active().unregister(COMPAT); + CompatSnapshots.untrack(COMPAT); + Files.deleteIfExists(ConfigManager.profileDir("").resolve(CONFIG)); + deletePath(ConfigManager.PROFILES_DIR.resolve(PROFILE_A)); + deletePath(ConfigManager.PROFILES_DIR.resolve(PROFILE_B)); + } + + private static void deletePath(Path path) throws IOException { + if (!Files.exists(path)) return; + try (Stream stream = Files.walk(path)) { + for (Path entry : stream.sorted(Comparator.reverseOrder()).toList()) { + Files.deleteIfExists(entry); + } + } + } + + private static final class DetachedConfig extends Config { + @Switch(title = "Enabled") + boolean enabled = false; + + private DetachedConfig() { + super(CONFIG, "Detached Rebind Test", Category.OTHER); + addCallback("enabled", () -> { + }); + } + } +} From 5acdc2dc0b7e223ae15ea1418f8eca3ad9140978 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 20 Nov 2026 05:58:24 +0100 Subject: [PATCH 02/12] feat(hud): leave HUDs of providers taken out alone and reload for ones put back --- .../oneconfig/api/hud/v1/HudManager.kt | 21 ++++ .../api/hud/v1/HudProfileIsolationTest.java | 104 ++++++++++++++++++ 2 files changed, 125 insertions(+) diff --git a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt index 9d9f48fc7..a45145691 100644 --- a/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt +++ b/modules/hud/src/main/kotlin/org/polyfrost/oneconfig/api/hud/v1/HudManager.kt @@ -68,6 +68,9 @@ public object HudManager { private val hudProviders = HashMap, Hud>() private val unsupportedHuds: MutableSet = ConcurrentHashMap.newKeySet() + // classes registered and not unregistered here, which still names a provider that Hotwire took out of hudProviders + private val registeredHuds: MutableSet = ConcurrentHashMap.newKeySet() + private var loadedProviders: Set> = emptySet() private val pendingUnsupported: MutableSet> = ConcurrentHashMap.newKeySet() private val hudIcons = HashMap() private val registrationListeners = CopyOnWriteArrayList() @@ -386,6 +389,7 @@ public object HudManager { @JvmStatic public fun register(hud: Hud) { unsupportedHuds.remove(hud::class.java.name) + registeredHuds.add(hud::class.java.name) HudStyles.captureBuiltIn(hud) hudProviders[hud::class.java] = hud revision++ @@ -531,6 +535,7 @@ public object HudManager { public fun providers(): Collection = hudProviders.values public fun unregister(hud: T, removeActiveInstances: Boolean = false, delete: Boolean = false): ArrayList? { + registeredHuds.remove(hud::class.java.name) if (hudProviders.remove(hud::class.java) != null) { revision++ notifyRegistrationChanged() @@ -1577,6 +1582,19 @@ public object HudManager { profileReloadDispatcher = dispatcher } + /** + * Reloads the active profile's HUDs if providers are registered that its last load did not see, which is how + * Hotwire leaves the ones of a mod it turned back on after the profile changed + * + * The instances put back with them belong to the profile the mod went off in and are dropped without being saved + */ + @ApiStatus.Internal + public fun reloadForNewProviders() { + if (!init || loadedProviders.containsAll(hudProviders.keys)) return + pendingProfileReload.set(ProfileReload(ConfigManager.activeProfile(), saveCurrent = true)) + applyPendingProfileReload() + } + private fun teardownForProfile(profile: String) { val kept = ArrayList(activeInstances.size) for (hud in ArrayList(activeInstances)) { @@ -1749,6 +1767,8 @@ public object HudManager { ?: throw IllegalArgumentException("hud tree ${data.id} is missing class name") if (clsName.endsWith(".OneConfigHudCompat")) return@forEach if (clsName in unsupportedHuds) return@forEach + // its mod is off, so its class must not be instantiated and its file stays as it is + if (clsName in registeredHuds && hudProviders.keys.none { it.name == clsName }) return@forEach val cls = Class.forName(clsName, true, loader) as? Class ?: throw IllegalArgumentException("$clsName is not a subclass of Hud") providerClass = cls @@ -1841,6 +1861,7 @@ public object HudManager { } if (registryChanged) saveRegistry() + loadedProviders = HashSet(hudProviders.keys) try { HudGroups.applyDefaults() diff --git a/modules/hud/src/test/java/org/polyfrost/oneconfig/api/hud/v1/HudProfileIsolationTest.java b/modules/hud/src/test/java/org/polyfrost/oneconfig/api/hud/v1/HudProfileIsolationTest.java index 9aaaaf8a3..6c2cd50fa 100644 --- a/modules/hud/src/test/java/org/polyfrost/oneconfig/api/hud/v1/HudProfileIsolationTest.java +++ b/modules/hud/src/test/java/org/polyfrost/oneconfig/api/hud/v1/HudProfileIsolationTest.java @@ -42,6 +42,8 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; +import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; @@ -314,6 +316,79 @@ void lateRegistrationDoesNotDiscardUnsavedHudChanges() throws Exception { } } + @Test + void profileLoadDoesNotRunAHudWhoseProviderWasTakenOut() throws Exception { + SwitchedHud provider = new SwitchedHud(); + HudManager.register(provider); + Runnable putBack = () -> { + }; + try { + launch(); + assertEquals(1, HudManager.INSTANCE.getHudsOfType(SwitchedHud.class).size()); + ConfigManager.active().saveAll(); + putBack = takeOut(provider); + int made = SwitchedHud.made; + + ConfigManager.createProfile(PROFILE); + ConfigManager.openProfile(""); + + assertEquals(made, SwitchedHud.made, "a HUD of a mod that is off must not be made from its file"); + assertTrue(HudManager.INSTANCE.getHudsOfType(SwitchedHud.class).isEmpty()); + } finally { + putBack.run(); + HudManager.INSTANCE.unregister(provider, true, true); + } + } + + @Test + void providerPutBackAfterAProfileSwitchGetsThatProfilesHud() throws Exception { + SwitchedHud provider = new SwitchedHud(); + HudManager.register(provider); + try { + launch(); + switched().setHidden(true); + ConfigManager.active().saveAll(); + ConfigManager.createProfile(PROFILE); + assertFalse(switched().getHidden()); + ConfigManager.openProfile(""); + assertTrue(switched().getHidden()); + Runnable putBack = takeOut(provider); + + ConfigManager.openProfile(PROFILE); + putBack.run(); + HudManager.INSTANCE.reloadForNewProviders(); + + assertEquals(1, HudManager.INSTANCE.getHudsOfType(SwitchedHud.class).size()); + assertFalse(switched().getHidden(), "it must get this profile's settings, not the ones it went off with"); + Object tree = switched().getTree(); + assertTrue(ConfigManager.active().trees().stream().anyMatch(t -> t == tree), + "the HUD that came back must be bound to the profile that is open now"); + ConfigManager.openProfile(""); + assertTrue(switched().getHidden(), "the profile it went off in must keep its settings"); + } finally { + HudManager.INSTANCE.unregister(provider, true, true); + } + } + + /** Takes a provider and its HUDs out of the manager's collections the way Hotwire does when their mod goes off */ + @SuppressWarnings("unchecked") + private static Runnable takeOut(Hud provider) throws Exception { + Field f = HudManager.class.getDeclaredField("hudProviders"); + f.setAccessible(true); + Map, Hud> providers = (Map, Hud>) f.get(HudManager.INSTANCE); + List instances = new ArrayList<>(HudManager.INSTANCE.getHudsOfType(provider.getClass())); + providers.remove(provider.getClass()); + HudManager.INSTANCE.getActiveInstances().removeAll(instances); + return () -> { + HudManager.INSTANCE.getActiveInstances().addAll(instances); + providers.put(provider.getClass(), provider); + }; + } + + private static Hud switched() { + return HudManager.INSTANCE.getHudsOfType(SwitchedHud.class).get(0); + } + private static Hud hud() { return HudManager.INSTANCE.getHudsOfType(ProfileTestHud.class).get(0); } @@ -607,6 +682,35 @@ public String getText() { } } + static class SwitchedHud extends TextHud { + static int made = 0; + + SwitchedHud() { + super("test-switched", "Test Switched HUD", Hud.Category.getINFO(), "", ""); + made++; + } + + @Override + public Pair defaultPosition() { + return new Pair<>(10f, 10f); + } + + @Override + public boolean showByDefault() { + return true; + } + + @Override + public boolean multipleInstancesAllowed() { + return false; + } + + @Override + public String getText() { + return "switched"; + } + } + static class FailingSetupHud extends TextHud { FailingSetupHud() { super("test-failing-setup", "Failing Setup HUD", Hud.Category.getINFO(), "", ""); From 9d1f0e9e3944ac262cda823f5158b82c0459255e Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 20 Nov 2026 06:40:02 +0100 Subject: [PATCH 03/12] test(config): check a config with a reset tree is bound to the tree put back --- .../oneconfig/api/config/v1/DetachedRebindTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java index 4cfc4c289..fa276344c 100644 --- a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java +++ b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java @@ -136,19 +136,19 @@ void configPutBackAfterItsProfileWasRenamedKeepsItsValues() throws Exception { assertSame(config.getTree(), ConfigManager.active().get(CONFIG)); } - // Hotwire 0.9.5.1 also resets Config.tree of a mod it turned off, even when the profile never changed + // Hotwire 0.9.5.1 also resets Config.tree of a mod it turned off, without which Config.save() does nothing @Test - void configWhoseTreeWasForgottenSurvivesTheNextProfileSwitch() throws Exception { + void configWhoseTreeWasResetIsBoundToTheTreePutBack() throws Exception { DetachedConfig config = configWith(true); + Tree tree = config.getTree(); Off off = turnOff(config); config.tree = null; off.turnOn(); ConfigManager.rebindDetached(); - assertSame(config.getTree(), ConfigManager.active().get(CONFIG)); - ConfigManager.createProfile(PROFILE_A); - ConfigManager.openProfile(""); - assertTrue(config.enabled, "its value on the profile it went off in was overwritten"); + assertSame(tree, config.getTree()); + assertSame(tree, ConfigManager.active().get(CONFIG)); + assertTrue(config.enabled); } @Test From d4d6c1834d5fd4e00c9b610ebab0ae59ddc9b985 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 20 Nov 2026 06:40:02 +0100 Subject: [PATCH 04/12] feat(compat): refresh what is built from the mod list and run config entrypoints of mods started late --- .../internal/CompatibilityPlatformImpl.java | 8 ++- .../internal/compat/ConfigEntrypoints.java | 57 ++++++++++++++++++- .../oneconfig/internal/compat/CompatLoader.kt | 29 ++++++++-- .../oneconfig/api/platform/v1/ModInfo.kt | 8 +++ 4 files changed, 92 insertions(+), 10 deletions(-) diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/api/platform/v1/internal/CompatibilityPlatformImpl.java b/minecraft/src/main/java/org/polyfrost/oneconfig/api/platform/v1/internal/CompatibilityPlatformImpl.java index aef0c1be2..4465edb1b 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/api/platform/v1/internal/CompatibilityPlatformImpl.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/api/platform/v1/internal/CompatibilityPlatformImpl.java @@ -1,6 +1,8 @@ package org.polyfrost.oneconfig.api.platform.v1.internal; import com.google.common.collect.Iterables; +import java.util.Collections; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import net.fabricmc.loader.api.FabricLoader; @@ -41,13 +43,17 @@ public void displayChatMessage(Component text) { *///?} } + // by its own id, the mod each copy stands in for that Hotwire runs in place of a mod it could not update in place + public static volatile Map liveCopies = Collections.emptyMap(); + @Override public Set getMods() { return FabricLoader.getInstance().getAllMods().stream() .map(mod -> { var metadata = mod.getMetadata(); return new ModInfo( - metadata.getId(), + // so the copy's settings, snapshots and cards stay those of the mod it stands in for + liveCopies.getOrDefault(metadata.getId(), metadata.getId()), metadata.getName(), metadata.getVersion().getFriendlyString(), Iterables.getFirst(mod.getRootPaths(), null), diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java index bc6c4008b..3c55a27ef 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java @@ -49,6 +49,7 @@ import org.polyfrost.oneconfig.api.config.v1.ConfigEntrypoint; import org.polyfrost.oneconfig.api.config.v1.ConfigManager; import org.polyfrost.oneconfig.api.config.v1.Tree; +import org.polyfrost.oneconfig.api.platform.v1.internal.CompatibilityPlatformImpl; import org.polyfrost.oneconfig.api.platform.v1.ModInfo; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; @@ -76,6 +77,7 @@ private record Skipped(String modId, Runnable extraction) { // keyed so a hook that fires more than once before the mod is decided is only retried once private static final Map> skippedExtractions = new HashMap<>(); private static final AtomicBoolean registered = new AtomicBoolean(); + private static final AtomicBoolean listening = new AtomicBoolean(); private static final Map treeOwners = new ConcurrentHashMap<>(); // configs claimed only because they existed before the entrypoint ran, which do not count when it threw private static final Set earlierConfigs = ConcurrentHashMap.newKeySet(); @@ -152,8 +154,7 @@ public static List ownedTrees(String modId) { public static void registerAll() { if (!registered.compareAndSet(false, true)) return; if (providers().isEmpty()) return; - ConfigManager.addTreeRegistrationListener(ConfigEntrypoints::onTreeRegistered); - ConfigManager.addConfigSubmissionListener(ConfigEntrypoints::onConfigSubmitted); + listen(); claimEarlierConfigs(); // a mod may name more than one entrypoint, which only decide together whether its original is extracted Map> byMod = new LinkedHashMap<>(); @@ -161,6 +162,55 @@ public static void registerAll() { byMod.forEach((modId, entrypoints) -> undecided.put(modId, register(modId, entrypoints))); } + private static void listen() { + if (!listening.compareAndSet(false, true)) return; + ConfigManager.addTreeRegistrationListener(ConfigEntrypoints::onTreeRegistered); + ConfigManager.addConfigSubmissionListener(ConfigEntrypoints::onConfigSubmitted); + } + + /** + * Runs the entrypoints of mods that Hotwire started after the game did, to be decided by the next + * {@link #finishRegistration()} like those of {@link #registerAll()}. A mod that was already decided is left + * alone, as it only gained other entrypoints, unless it is a copy, which starts over what it stands in for. + */ + public static void registerStarted(Collection modIds) { + // registerAll has not run yet and will find them itself + if (!registered.get()) return; + Set started = new HashSet<>(); + for (String id : modIds) { + String original = CompatibilityPlatformImpl.liveCopies.get(id); + if (original != null) forgetDecision(original); + started.add(original == null ? id : original); + } + Map> byMod = new LinkedHashMap<>(); + for (Provider provider : providers()) { + if (started.contains(provider.modId) && !isDecided(provider.modId)) byMod.computeIfAbsent(provider.modId, k -> new ArrayList<>()).add(provider); + } + if (byMod.isEmpty()) return; + listen(); + claimEarlierConfigs(); + byMod.forEach((modId, entrypoints) -> { + // as CompatLoader did for the providers it saw when it initialized + CompatLoader.INSTANCE.getNativeLoadedConfigs().add(modId); + undecided.put(modId, register(modId, entrypoints)); + }); + } + + private static synchronized void forgetDecision(String modId) { + succeeded.remove(modId); + failed.remove(modId); + } + + /** + * Looks the entrypoints up again at their next use, for when the mods that provide them changed + */ + static void forgetProviders() { + synchronized (DISCOVERY_LOCK) { + providers = null; + } + defaultOpeners.clear(); + } + /** * Decides for each mod that ran an entrypoint whether to keep its configs or extract its original. Called after * {@link ConfigManager#initialize()}, as a config only counts once its tree was built and registered. @@ -497,8 +547,9 @@ private static List providers() { List found = new ArrayList<>(); try { for (EntrypointContainer container : FabricLoader.getInstance().getEntrypointContainers(ConfigEntrypoint.ENTRYPOINT, ConfigEntrypoint.class)) { + String id = container.getProvider().getMetadata().getId(); found.add(new Provider( - container.getProvider().getMetadata().getId(), + CompatibilityPlatformImpl.liveCopies.getOrDefault(id, id), container.getDefinition(), container::getEntrypoint )); diff --git a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/CompatLoader.kt b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/CompatLoader.kt index 8dd0bca51..126ead2a6 100644 --- a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/CompatLoader.kt +++ b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/compat/CompatLoader.kt @@ -25,7 +25,8 @@ object CompatLoader { var queuedCompatsRan = false private set - private val pathFactory: MutableMap String> = mutableMapOf() + @Volatile + private var pathFactory: Map String> = emptyMap() // concurrent as compat hooks may fire on other threads while ConfigEntrypoints un-marks a failed mod val nativeLoadedConfigs: MutableSet = ConcurrentHashMap.newKeySet() @@ -174,14 +175,30 @@ object CompatLoader { private var entrypointsDecided = false init { + indexMods() + + // filtered so a mod whose entrypoint already failed is never marked again + nativeLoadedConfigs.addAll(ConfigEntrypoints.providerModIds().filter(ConfigEntrypoints::provides)) + } + + /** + * Reads the loader's mod list again into everything built from it, for when mods changed while the game runs + */ + fun refreshMods() { + ModInfo.forgetLoadedMods() + indexMods() + ConfigEntrypoints.forgetProviders() + } + + private fun indexMods() { + val paths = HashMap String>() ModInfo.loadedMods.forEach { mod -> mod.file?.let { - pathFactory[mod] = it.toUri().toString()::plus + paths[mod] = it.toUri().toString()::plus } } - - // filtered so a mod whose entrypoint already failed is never marked again - nativeLoadedConfigs.addAll(ConfigEntrypoints.providerModIds().filter(ConfigEntrypoints::provides)) + pathFactory = paths + ownerByClassName.clear() } /** @@ -230,4 +247,4 @@ object CompatLoader { } if (!queued) init() } -} \ No newline at end of file +} diff --git a/modules/utils/src/main/kotlin/org/polyfrost/oneconfig/api/platform/v1/ModInfo.kt b/modules/utils/src/main/kotlin/org/polyfrost/oneconfig/api/platform/v1/ModInfo.kt index b9969af65..3f42b3424 100644 --- a/modules/utils/src/main/kotlin/org/polyfrost/oneconfig/api/platform/v1/ModInfo.kt +++ b/modules/utils/src/main/kotlin/org/polyfrost/oneconfig/api/platform/v1/ModInfo.kt @@ -1,5 +1,6 @@ package org.polyfrost.oneconfig.api.platform.v1 +import org.jetbrains.annotations.ApiStatus import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption @@ -50,6 +51,13 @@ public data class ModInfo @JvmOverloads constructor( @get:JvmStatic public val loadedMods: Set get() = cached ?: Platform.compatibility().mods.also { if (it.isNotEmpty()) cached = it } + + /** Makes the next read of [loadedMods] ask the loader again, for when mods changed while the game runs */ + @ApiStatus.Internal + @JvmStatic + public fun forgetLoadedMods() { + cached = null + } } } From 5e6ae7f39a414071fe796cf447ea6f7d8ea54a6d Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 20 Nov 2026 06:40:03 +0100 Subject: [PATCH 05/12] feat(compat): take part in Hotwire's mod lifecycle Needs Hotwire 0.9.2 or newer, which is compiled against and not bundled. --- CHANGELOG.md | 6 + .../src/main/kotlin/OneConfigSetupPlugin.kt | 7 + .../oneconfig/internal/OneConfig.java | 4 + .../internal/compat/HotwireLifecycle.java | 128 ++++++++++++++++++ minecraft/src/main/resources/fabric.mod.json | 1 + 5 files changed, 146 insertions(+) create mode 100644 minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 20230e8fb..5b4947a08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ 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] + +### Added +- Mods that [Hotwire](https://modrinth.com/mod/irenehotwire) turns off, turns on, adds or updates while the game runs keep their settings, mod cards and HUDs, including when a profile was switched to, created or renamed while they were off +- API: `oneconfig:config` entrypoints of mods that Hotwire adds or updates while the game runs are run as the mod starts + ## [1.9.1] - 2026-11-22 ### Added diff --git a/buildSrc/src/main/kotlin/OneConfigSetupPlugin.kt b/buildSrc/src/main/kotlin/OneConfigSetupPlugin.kt index ad504fa02..6c62bf4dc 100644 --- a/buildSrc/src/main/kotlin/OneConfigSetupPlugin.kt +++ b/buildSrc/src/main/kotlin/OneConfigSetupPlugin.kt @@ -270,6 +270,13 @@ class OneConfigSetupPlugin : Plugin { } } + // Hotwire's API has no Minecraft types, so one of its builds serves every version. Its published jar keeps + // the API in a jar nested inside, which is the part to compile against + val hotwire = configurations.detachedConfiguration( + dependencies.create("maven.modrinth:irenehotwire:0.9.5.1-beta+mc26.1-26.3") + ).apply { isTransitive = false } + "compileOnly"(zipTree(hotwire.elements.map { it.single() }).matching { include("META-INF/jars/hotwire-core.jar") }) + "annotationProcessor"(versionedCatalog["mixin.squared"]) if (enableMoulRelocatorKsp) { 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 9a027c00e..c68437c3c 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/OneConfig.java @@ -29,6 +29,7 @@ import com.mojang.brigadier.Command; import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; @@ -56,6 +57,7 @@ import org.polyfrost.oneconfig.api.platform.v1.Platform; import org.polyfrost.oneconfig.internal.compat.CompatLoader; import org.polyfrost.oneconfig.internal.compat.ConfigEntrypoints; +import org.polyfrost.oneconfig.internal.compat.HotwireLifecycle; import org.polyfrost.oneconfig.internal.compat.KaleidoCompat; import org.polyfrost.oneconfig.internal.compat.toggle.ModGates; import org.polyfrost.oneconfig.internal.ui.api.ConfigRegistry; @@ -343,6 +345,8 @@ private static void registerEventHandlers() { //? 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(); }); EventManager.register(WorldEvent.Load.class, e -> { showFirstLaunchNotification(); diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java new file mode 100644 index 000000000..8fff8c8c8 --- /dev/null +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java @@ -0,0 +1,128 @@ +/* + * This file is part of OneConfig. + * OneConfig - Next Generation Config Library for Minecraft: Java Edition + * Copyright (C) 2021~2024 Polyfrost. + * + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * OneConfig is licensed under the terms of version 3 of the GNU Lesser + * General Public License as published by the Free Software Foundation, AND + * under the Additional Terms Applicable to OneConfig, as published by Polyfrost, + * either version 1.0 of the Additional Terms, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License. If not, see . You should + * have also received a copy of the Additional Terms Applicable + * to OneConfig, as published by Polyfrost. If not, see + * + */ + +package org.polyfrost.oneconfig.internal.compat; + +import dev.moon.hotwire.api.HotwireApi; +import dev.moon.hotwire.api.ModLifecycleListener; +import dev.moon.hotwire.api.ModState; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.polyfrost.oneconfig.api.config.v1.CompatSnapshots; +import org.polyfrost.oneconfig.api.config.v1.ConfigManager; +import org.polyfrost.oneconfig.api.hud.v1.HudManager; +import org.polyfrost.oneconfig.api.platform.v1.internal.CompatibilityPlatformImpl; +import org.polyfrost.oneconfig.internal.ui.api.ConfigRegistry; +import org.polyfrost.oneconfig.internal.ui.api.ConfigSource; + +/** + * OneConfig's part in Hotwire turning mods off and on, adding and updating them while the game runs. Hotwire takes a + * mod's objects out of OneConfig's collections and puts the same ones back itself, so what is left is what needs to + * know about profiles and about when new configs are initialized. Every call comes on the game thread. + *
+ * This is the only class that names Hotwire's types, so it must only be loaded when Hotwire is installed. + */ +public final class HotwireLifecycle implements ModLifecycleListener { + private static final Logger LOGGER = LogManager.getLogger("OneConfig/Hotwire"); + + private HotwireLifecycle() { + } + + public static void register() { + HotwireApi.getInstance().addLifecycleListener(new HotwireLifecycle()); + } + + // the whole profile rather than what these mods own, which Hotwire decides in ways OneConfig cannot mirror + @Override + public void prepareOff(List ids) { + try { + ConfigManager.active().saveAll(); + CompatSnapshots.INSTANCE.onProfileSaving(ConfigManager.activeProfile()); + } catch (Throwable t) { + LOGGER.error("Failed to save the settings of {} before Hotwire turns them off", ids, t); + } + } + + // by what is out of place rather than by which mods came back, as their objects only are if the profile changed + @Override + public void finishOn(List ids) { + try { + refreshMods(); + ConfigManager.rebindDetached(); + HudManager.INSTANCE.reloadForNewProviders(); + ConfigRegistry.INSTANCE.loadFrom(ConfigManager.active(), ConfigSource.OC); + } catch (Throwable t) { + LOGGER.error("Failed to bind {} to the active profile after Hotwire turned them on", ids, t); + } + } + + @Override + public void prepareStart(List ids) { + ConfigManager.reopenInitialization(); + } + + @Override + public void finishStart(List ids, boolean ok) { + try { + if (ok) { + refreshMods(); + ConfigEntrypoints.registerStarted(ids); + } else { + ConfigManager.pendingConfigs().forEach(ConfigManager::cancelInitialization); + } + } catch (Throwable t) { + LOGGER.error("Failed to set up the configs of {}, which Hotwire started", ids, t); + } finally { + // also what closes the window prepareStart opened + try { + ConfigManager.initialize(); + } finally { + if (ok) ConfigEntrypoints.finishRegistration(); + } + } + } + + @Override + public void finishUpdate(List ids) { + try { + refreshMods(); + } catch (Throwable t) { + LOGGER.error("Failed to read the mods again after Hotwire updated {}", ids, t); + } + } + + private static void refreshMods() { + Map copies = new HashMap<>(); + for (ModState mod : HotwireApi.getInstance().getMods()) { + if (mod.copyOf() != null) copies.put(mod.id(), mod.copyOf()); + } + CompatibilityPlatformImpl.liveCopies = copies; + CompatLoader.INSTANCE.refreshMods(); + } +} diff --git a/minecraft/src/main/resources/fabric.mod.json b/minecraft/src/main/resources/fabric.mod.json index 21c4ec041..192379b64 100644 --- a/minecraft/src/main/resources/fabric.mod.json +++ b/minecraft/src/main/resources/fabric.mod.json @@ -50,6 +50,7 @@ "chattweaks": "<1.2.3", "crashpatch": "<2.3.0", "evergreenhud": "<3.10.0", + "hotwire": "<0.9.2-beta", "hybedwars": "<1.2.1", "legacyskyblock": "<2.10.1", "noteable": "<3.1.0", From 368f9444a97604288fa75ac13ba41826984a9345 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 20 Nov 2026 06:40:03 +0100 Subject: [PATCH 06/12] test(compat): check the names Hotwire reads by reflection still exist --- .../internal/compat/HotwireContractTest.java | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 minecraft/src/test/java/org/polyfrost/oneconfig/internal/compat/HotwireContractTest.java diff --git a/minecraft/src/test/java/org/polyfrost/oneconfig/internal/compat/HotwireContractTest.java b/minecraft/src/test/java/org/polyfrost/oneconfig/internal/compat/HotwireContractTest.java new file mode 100644 index 000000000..35d0d46e1 --- /dev/null +++ b/minecraft/src/test/java/org/polyfrost/oneconfig/internal/compat/HotwireContractTest.java @@ -0,0 +1,120 @@ +/* + * This file is part of OneConfig. + * OneConfig - Next Generation Config Library for Minecraft: Java Edition + * Copyright (C) 2021~2024 Polyfrost. + * + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * OneConfig is licensed under the terms of version 3 of the GNU Lesser + * General Public License as published by the Free Software Foundation, AND + * under the Additional Terms Applicable to OneConfig, as published by Polyfrost, + * either version 1.0 of the Additional Terms, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License. If not, see . You should + * have also received a copy of the Additional Terms Applicable + * to OneConfig, as published by Polyfrost. If not, see + * + */ + +package org.polyfrost.oneconfig.internal.compat; + +import java.lang.reflect.Method; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Released builds of Hotwire reach these names by reflection to take a mod's objects out of OneConfig and put them + * back, and stop doing so without a word when one is missing. Renaming one needs a Hotwire that knows the new name. + */ +class HotwireContractTest { + private static final String CONFIG = "org.polyfrost.oneconfig.api.config.v1."; + private static final String HUD = "org.polyfrost.oneconfig.api.hud.v1."; + private static final String UI = "org.polyfrost.oneconfig.internal.ui."; + + @Test + void configManager() throws Exception { + Class manager = type(CONFIG + "ConfigManager"); + Class tree = type(CONFIG + "Tree"); + manager.getMethod("active"); + manager.getMethod("trees"); + manager.getMethod("save", tree); + manager.getMethod("initialize"); + fields(manager, "initialized", "pendingInitialization", "initializedConfigs"); + tree.getMethod("getID"); + fields(tree, "theMap"); + fields(type(CONFIG + "Property$Field"), "owner"); + fields(type(CONFIG + "Config"), "tree", "id"); + type(CONFIG + "Node").getMethod("getMetadata", String.class); + } + + @Test + void hudManager() throws Exception { + Class manager = type(HUD + "HudManager"); + manager.getField("INSTANCE"); + fields(manager, "activeInstances", "hudProviders"); + manager.getMethod("invalidate"); + manager.getMethod("getRevision"); + manager.getDeclaredMethod("setRevision", int.class); + manager.getDeclaredMethod("notifyRegistrationChanged"); + methods(manager, "getInstancesRevision"); + Class hud = type(HUD + "Hud"); + hud.getMethod("getRuntimeOrNull"); + methods(hud, "set_runtime$hud", "setLastDraw$hud"); + type(HUD + "OneConfigHudCompat").getMethod("getWrapper").getReturnType().getMethod("getModId"); + } + + @Test + void hudEditor() throws Exception { + Class editor = type(UI + "compose.impls.HudEditorUIScreen"); + fields(editor, "instance"); + editor.getSuperclass().getDeclaredMethod("disposeScene"); + } + + @Test + void modCards() throws Exception { + Class registry = type(UI + "api.ConfigRegistry"); + Class card = type(UI + "api.ConfigData"); + registry.getField("INSTANCE"); + registry.getMethod("getConfigs"); + registry.getMethod("findTree", String.class); + registry.getMethod("register", card); + registry.getMethod("unregister", String.class); + card.getMethod("getId"); + type("org.polyfrost.oneconfig.api.ui.v1.OneConfigUI").getMethod("createScreen", Object.class); + } + + @Test + void events() throws Exception { + Class manager = type("org.polyfrost.oneconfig.api.event.v1.EventManager"); + Class handler = type("org.polyfrost.oneconfig.api.event.v1.invoke.EventHandler"); + fields(manager, "handlers"); + manager.getMethod("register", handler); + manager.getMethod("unregister", handler); + } + + // not initialized, as most of these need a running game for that + private static Class type(String name) throws ClassNotFoundException { + return Class.forName(name, false, HotwireContractTest.class.getClassLoader()); + } + + private static void fields(Class type, String... names) { + for (String name : names) assertDoesNotThrow(() -> type.getDeclaredField(name), type.getName() + "." + name); + } + + private static void methods(Class type, String... names) { + for (String name : names) { + assertTrue(Arrays.stream(type.getMethods()).map(Method::getName).anyMatch(name::equals), type.getName() + "." + name); + } + } +} From 6645c8023d71b207cc5091155c05d2dbfb8ded07 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 22 Nov 2026 01:12:02 +0100 Subject: [PATCH 07/12] fix(config): bind a config to its tree put back on the same profile Registering the tree again merged it into itself for a KtConfig, which builds its tree once, and that cleared the tree and its file. --- .../api/config/v1/ConfigManager.java | 6 ++++ .../api/config/v1/DetachedRebindTest.java | 21 +++++++++++++ .../api/config/v1/DetachedKtConfig.kt | 31 +++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 modules/config-impl/src/test/kotlin/org/polyfrost/oneconfig/api/config/v1/DetachedKtConfig.kt diff --git a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java index 8c76af5ba..49f426b75 100644 --- a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java +++ b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java @@ -538,6 +538,12 @@ public static synchronized void rebindDetached() { try { for (Config config : new ArrayList<>(initializedConfigs.values())) { if (mgr.tracks(config.tree)) continue; + // Hotwire also resets the field of a config it took out, and on the same profile puts its tree back here, + // where registering it again would merge it into itself, which clears it + if (config.tree == null && mgr.backend.exists(config.id)) { + config.tree = mgr.backend.get(config.id); + continue; + } try { config.rebindToActiveProfile(!Files.exists(mgr.getFolder().resolve(config.id))); } catch (Throwable t) { diff --git a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java index fa276344c..32fc3edce 100644 --- a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java +++ b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java @@ -42,6 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -151,6 +152,26 @@ void configWhoseTreeWasResetIsBoundToTheTreePutBack() throws Exception { assertTrue(config.enabled); } + // a KtConfig builds its tree once, so binding it again by registering that tree over itself would clear it + @Test + void ktConfigWhoseTreeWasResetKeepsItsValues() throws Exception { + DetachedKtConfig config = new DetachedKtConfig(CONFIG); + config.initialize(false); + config.setEnabled(true); + config.save(); + Tree tree = config.getTree(); + Off off = turnOff(config); + config.tree = null; + off.turnOn(); + ConfigManager.rebindDetached(); + + assertSame(tree, config.getTree()); + assertNotNull(tree.getProp("enabled"), "the tree kept its options"); + ConfigManager.createProfile(PROFILE_A); + ConfigManager.openProfile(""); + assertEquals(true, ConfigManager.active().get(CONFIG).getProp("enabled").get(), "and so did its file"); + } + @Test void compatTreePutBackAfterASwitchGetsTheNewProfilesValues() throws Exception { Property value = Properties.simple("value", "Value", "", 1); diff --git a/modules/config-impl/src/test/kotlin/org/polyfrost/oneconfig/api/config/v1/DetachedKtConfig.kt b/modules/config-impl/src/test/kotlin/org/polyfrost/oneconfig/api/config/v1/DetachedKtConfig.kt new file mode 100644 index 000000000..37ef01654 --- /dev/null +++ b/modules/config-impl/src/test/kotlin/org/polyfrost/oneconfig/api/config/v1/DetachedKtConfig.kt @@ -0,0 +1,31 @@ +/* + * This file is part of OneConfig. + * OneConfig - Next Generation Config Library for Minecraft: Java Edition + * Copyright (C) 2021~2024 Polyfrost. + * + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * OneConfig is licensed under the terms of version 3 of the GNU Lesser + * General Public License as published by the Free Software Foundation, AND + * under the Additional Terms Applicable to OneConfig, as published by Polyfrost, + * either version 1.0 of the Additional Terms, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License. If not, see . You should + * have also received a copy of the Additional Terms Applicable + * to OneConfig, as published by Polyfrost. If not, see + * + */ + +package org.polyfrost.oneconfig.api.config.v1 + +class DetachedKtConfig(id: String) : KtConfig(id, "Detached Rebind Test", Category.OTHER) { + var enabled by switch(false, "Enabled") +} From 228ceaf867f0162b7aa2c700dc88876872fc0ed6 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 22 Nov 2026 01:12:02 +0100 Subject: [PATCH 08/12] fix(compat): read the mods before a live start and only decide what it started Compat told whose config an initializer built from a mod list that did not have the new mod yet. A start also failed the config entrypoints of mods whose own start was yet to come in the same update. --- .../internal/compat/ConfigEntrypoints.java | 23 +++++++++++++++---- .../internal/compat/HotwireLifecycle.java | 9 ++++++-- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java index 3c55a27ef..6763f7b90 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/ConfigEntrypoints.java @@ -170,8 +170,11 @@ private static void listen() { /** * Runs the entrypoints of mods that Hotwire started after the game did, to be decided by the next - * {@link #finishRegistration()} like those of {@link #registerAll()}. A mod that was already decided is left - * alone, as it only gained other entrypoints, unless it is a copy, which starts over what it stands in for. + * {@link #finishStarted()}. A mod that was already decided is left alone, as it only gained other entrypoints, + * unless it is a copy, which starts over what it stands in for. + *
+ * shortcut: a second config entrypoint that an update adds to a decided mod only runs at the next launch, track + * which definitions ran if a mod ever does that */ public static void registerStarted(Collection modIds) { // registerAll has not run yet and will find them itself @@ -215,8 +218,20 @@ static void forgetProviders() { * Decides for each mod that ran an entrypoint whether to keep its configs or extract its original. Called after * {@link ConfigManager#initialize()}, as a config only counts once its tree was built and registered. */ - // compat waits for this, so it always ends by releasing it even if deciding a mod threw public static void finishRegistration() { + finishRegistration(true); + } + + /** + * As {@link #finishRegistration()} for {@link #registerStarted}, where a provider that has not run is left alone, + * as it may be of a mod that Hotwire is yet to start + */ + public static void finishStarted() { + finishRegistration(false); + } + + // compat waits for this, so it always ends by releasing it even if deciding a mod threw + private static void finishRegistration(boolean all) { try { Map pending = new LinkedHashMap<>(undecided); undecided.clear(); @@ -235,7 +250,7 @@ public static void finishRegistration() { }); // providers registerAll never reached, such as when it threw partway, would otherwise stay skipped forever for (String modId : providerIds()) { - if (pending.containsKey(modId) || isDecided(modId)) continue; + if (!all || pending.containsKey(modId) || isDecided(modId)) continue; LOGGER.warn("The OneConfig config entrypoint of {} never ran, extracting its original config instead", modId); try { fallBackToOriginal(modId); diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java index 8fff8c8c8..547342500 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java @@ -82,8 +82,14 @@ public void finishOn(List ids) { } } + // the mods are in the loader's list by now, which compat goes by to tell whose config an initializer builds @Override public void prepareStart(List ids) { + try { + refreshMods(); + } catch (Throwable t) { + LOGGER.error("Failed to read the mods again before Hotwire starts {}", ids, t); + } ConfigManager.reopenInitialization(); } @@ -91,7 +97,6 @@ public void prepareStart(List ids) { public void finishStart(List ids, boolean ok) { try { if (ok) { - refreshMods(); ConfigEntrypoints.registerStarted(ids); } else { ConfigManager.pendingConfigs().forEach(ConfigManager::cancelInitialization); @@ -103,7 +108,7 @@ public void finishStart(List ids, boolean ok) { try { ConfigManager.initialize(); } finally { - if (ok) ConfigEntrypoints.finishRegistration(); + if (ok) ConfigEntrypoints.finishStarted(); } } } From 70513dee55e6a3503e13250861e51105093e7c97 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 22 Nov 2026 01:12:02 +0100 Subject: [PATCH 09/12] fix(keybind): apply the profile's controls to keys of mods Hotwire turned on Their key mappings are out of the game while the mod is off, so a profile switch in that time left them with the keys of the profile they went off in, which the next save of the options then stored for the new profile. --- .../oneconfig/internal/compat/HotwireLifecycle.java | 3 +++ .../internal/ui/keybind/MinecraftKeybindProfiles.kt | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java index 547342500..014a4db4a 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java @@ -40,6 +40,7 @@ import org.polyfrost.oneconfig.api.platform.v1.internal.CompatibilityPlatformImpl; import org.polyfrost.oneconfig.internal.ui.api.ConfigRegistry; import org.polyfrost.oneconfig.internal.ui.api.ConfigSource; +import org.polyfrost.oneconfig.internal.ui.keybind.MinecraftKeybindProfiles; /** * OneConfig's part in Hotwire turning mods off and on, adding and updating them while the game runs. Hotwire takes a @@ -76,6 +77,7 @@ public void finishOn(List ids) { refreshMods(); ConfigManager.rebindDetached(); HudManager.INSTANCE.reloadForNewProviders(); + MinecraftKeybindProfiles.reapply(); ConfigRegistry.INSTANCE.loadFrom(ConfigManager.active(), ConfigSource.OC); } catch (Throwable t) { LOGGER.error("Failed to bind {} to the active profile after Hotwire turned them on", ids, t); @@ -98,6 +100,7 @@ public void finishStart(List ids, boolean ok) { try { if (ok) { ConfigEntrypoints.registerStarted(ids); + MinecraftKeybindProfiles.reapply(); } else { ConfigManager.pendingConfigs().forEach(ConfigManager::cancelInitialization); } diff --git a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt index 0acd3ba4a..dfbbfcf05 100644 --- a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt +++ b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt @@ -116,6 +116,16 @@ object MinecraftKeybindProfiles : ConfigManager.ProfileChangeListener { } } + /** + * Applies the active profile's controls again, to key mappings that were not there when they last were, such as + * those of a mod that Hotwire turned on after the profile changed + */ + @JvmStatic + fun reapply() { + val owner = modeTransitions.liveOwner() ?: return + if (owner.separateControls) apply(owner.profile) + } + @JvmStatic fun onOptionsSaved() { if (!initialized) return From 0e193b767c7a4ad3d849858d6bad8260f619497b Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 22 Nov 2026 01:29:18 +0100 Subject: [PATCH 10/12] Revert "fix(keybind): apply the profile's controls to keys of mods Hotwire turned on" Hotwire leaves the key mappings of an off mod in the options, so a profile switch already reaches them. This reverts commit 9070f0dde50cf7b858b4b8a886600beef09527ff. --- .../oneconfig/internal/compat/HotwireLifecycle.java | 3 --- .../internal/ui/keybind/MinecraftKeybindProfiles.kt | 10 ---------- 2 files changed, 13 deletions(-) diff --git a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java index 014a4db4a..547342500 100644 --- a/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java +++ b/minecraft/src/main/java/org/polyfrost/oneconfig/internal/compat/HotwireLifecycle.java @@ -40,7 +40,6 @@ import org.polyfrost.oneconfig.api.platform.v1.internal.CompatibilityPlatformImpl; import org.polyfrost.oneconfig.internal.ui.api.ConfigRegistry; import org.polyfrost.oneconfig.internal.ui.api.ConfigSource; -import org.polyfrost.oneconfig.internal.ui.keybind.MinecraftKeybindProfiles; /** * OneConfig's part in Hotwire turning mods off and on, adding and updating them while the game runs. Hotwire takes a @@ -77,7 +76,6 @@ public void finishOn(List ids) { refreshMods(); ConfigManager.rebindDetached(); HudManager.INSTANCE.reloadForNewProviders(); - MinecraftKeybindProfiles.reapply(); ConfigRegistry.INSTANCE.loadFrom(ConfigManager.active(), ConfigSource.OC); } catch (Throwable t) { LOGGER.error("Failed to bind {} to the active profile after Hotwire turned them on", ids, t); @@ -100,7 +98,6 @@ public void finishStart(List ids, boolean ok) { try { if (ok) { ConfigEntrypoints.registerStarted(ids); - MinecraftKeybindProfiles.reapply(); } else { ConfigManager.pendingConfigs().forEach(ConfigManager::cancelInitialization); } diff --git a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt index dfbbfcf05..0acd3ba4a 100644 --- a/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt +++ b/minecraft/src/main/kotlin/org/polyfrost/oneconfig/internal/ui/keybind/MinecraftKeybindProfiles.kt @@ -116,16 +116,6 @@ object MinecraftKeybindProfiles : ConfigManager.ProfileChangeListener { } } - /** - * Applies the active profile's controls again, to key mappings that were not there when they last were, such as - * those of a mod that Hotwire turned on after the profile changed - */ - @JvmStatic - fun reapply() { - val owner = modeTransitions.liveOwner() ?: return - if (owner.separateControls) apply(owner.profile) - } - @JvmStatic fun onOptionsSaved() { if (!initialized) return From 8eb36dff307a6de09ecaddeebee5778071039a0d Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 22 Nov 2026 01:30:57 +0100 Subject: [PATCH 11/12] fix(config): give a config its tree back before rebinding it On a profile without its file, restoring the defaults of a config whose tree field was reset registered its tree, and the rebind then merged a KtConfig's tree into itself. --- .../oneconfig/api/config/v1/ConfigManager.java | 18 ++++++++++++------ .../api/config/v1/DetachedRebindTest.java | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java index 49f426b75..64e86c4aa 100644 --- a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java +++ b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java @@ -537,13 +537,10 @@ public static synchronized void rebindDetached() { REBINDING_PROFILES.set(Boolean.TRUE); try { for (Config config : new ArrayList<>(initializedConfigs.values())) { + // Hotwire also resets the field of a config it took out. Without its tree a config would be registered + // twice, and one that builds its tree only once would merge it into itself, which clears it + if (config.tree == null) config.tree = mgr.findPutBack(config.id); if (mgr.tracks(config.tree)) continue; - // Hotwire also resets the field of a config it took out, and on the same profile puts its tree back here, - // where registering it again would merge it into itself, which clears it - if (config.tree == null && mgr.backend.exists(config.id)) { - config.tree = mgr.backend.get(config.id); - continue; - } try { config.rebindToActiveProfile(!Files.exists(mgr.getFolder().resolve(config.id))); } catch (Throwable t) { @@ -566,6 +563,15 @@ public static synchronized void rebindDetached() { } } + // the tree under this id in this backend, or else in one that a profile switch closed + private @Nullable Tree findPutBack(String id) { + if (backend.exists(id)) return backend.get(id); + for (ConfigManager closed : retired) { + if (closed.backend.exists(id)) return closed.backend.get(id); + } + return null; + } + private boolean tracks(@Nullable Tree tree) { return tree != null && tree.getID() != null && backend.exists(tree.getID()) && backend.get(tree.getID()) == tree; } diff --git a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java index 32fc3edce..ae7bf5075 100644 --- a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java +++ b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java @@ -172,6 +172,24 @@ void ktConfigWhoseTreeWasResetKeepsItsValues() throws Exception { assertEquals(true, ConfigManager.active().get(CONFIG).getProp("enabled").get(), "and so did its file"); } + @Test + void ktConfigWhoseTreeWasResetGetsItsDefaultsOnAProfileWithoutItsFile() throws Exception { + DetachedKtConfig config = new DetachedKtConfig(CONFIG); + config.initialize(false); + config.setEnabled(true); + config.save(); + Off off = turnOff(config); + config.tree = null; + ConfigManager.createProfile(PROFILE_A); + off.turnOn(); + ConfigManager.rebindDetached(); + + assertNotNull(config.getTree().getProp("enabled"), "the tree kept its options"); + assertEquals(false, config.getTree().getProp("enabled").get()); + ConfigManager.openProfile(""); + assertEquals(true, config.getTree().getProp("enabled").get(), "the profile it went off in keeps its own value"); + } + @Test void compatTreePutBackAfterASwitchGetsTheNewProfilesValues() throws Exception { Property value = Properties.simple("value", "Value", "", 1); From b99ef85d3744c5557ffffb8ee158bb4430685859 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 22 Nov 2026 01:55:17 +0100 Subject: [PATCH 12/12] fix(config): find a config's tree under the id it is stored by A config whose id has spaces or the like has a tree with another spelling of it, so its tree was not found and it was reset to its defaults. --- .../api/config/v1/ConfigManager.java | 18 ++++++++---- .../api/config/v1/DetachedRebindTest.java | 28 ++++++++++++++++--- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java index 64e86c4aa..e4ba653ad 100644 --- a/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java +++ b/modules/config-impl/src/main/java/org/polyfrost/oneconfig/api/config/v1/ConfigManager.java @@ -541,8 +541,9 @@ public static synchronized void rebindDetached() { // twice, and one that builds its tree only once would merge it into itself, which clears it if (config.tree == null) config.tree = mgr.findPutBack(config.id); if (mgr.tracks(config.tree)) continue; + String file = config.tree == null ? config.id : config.tree.getID(); try { - config.rebindToActiveProfile(!Files.exists(mgr.getFolder().resolve(config.id))); + config.rebindToActiveProfile(!Files.exists(mgr.getFolder().resolve(file))); } catch (Throwable t) { LOGGER.error("Failed to rebind config {} onto the active profile", config.id, t); } @@ -563,11 +564,16 @@ public static synchronized void rebindDetached() { } } - // the tree under this id in this backend, or else in one that a profile switch closed - private @Nullable Tree findPutBack(String id) { - if (backend.exists(id)) return backend.get(id); - for (ConfigManager closed : retired) { - if (closed.backend.exists(id)) return closed.backend.get(id); + // the tree of the config with this id in this backend, or else in one that a profile switch closed + private @Nullable Tree findPutBack(String configId) { + // a KtConfig's tree goes by the id as it is, any other by how Node.setID spells it + Tree spelled = Tree.tree(); + spelled.setID(configId); + for (String id : new String[]{configId, spelled.getID()}) { + if (backend.exists(id)) return backend.get(id); + for (ConfigManager closed : retired) { + if (closed.backend.exists(id)) return closed.backend.get(id); + } } return null; } diff --git a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java index ae7bf5075..65bca135d 100644 --- a/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java +++ b/modules/config-impl/src/test/java/org/polyfrost/oneconfig/api/config/v1/DetachedRebindTest.java @@ -54,6 +54,7 @@ class DetachedRebindTest { private static final String PROFILE_A = "oc_detached_profile_a"; private static final String PROFILE_B = "oc_detached_profile_b"; private static final String CONFIG = "detached_rebind_test.json"; + private static final String SPACED_CONFIG = "detached rebind test.json"; private static final String COMPAT = "detached_rebind_compat"; @BeforeEach @@ -152,6 +153,24 @@ void configWhoseTreeWasResetIsBoundToTheTreePutBack() throws Exception { assertTrue(config.enabled); } + // a tree's id is its config's with what does not belong in a file name replaced, which is what both are stored under + @Test + void configWhoseTreeGoesByAnotherSpellingOfItsIdKeepsItsValues() throws Exception { + DetachedConfig config = new DetachedConfig(SPACED_CONFIG); + config.initialize(false); + config.enabled = true; + config.save(); + Tree tree = config.getTree(); + assertEquals(CONFIG, tree.getID()); + Off off = turnOff(config); + config.tree = null; + off.turnOn(); + ConfigManager.rebindDetached(); + + assertSame(tree, config.getTree()); + assertTrue(config.enabled); + } + // a KtConfig builds its tree once, so binding it again by registering that tree over itself would clear it @Test void ktConfigWhoseTreeWasResetKeepsItsValues() throws Exception { @@ -228,7 +247,7 @@ void compatTreePutBackOnAProfileMadeMeanwhileGetsItsDefaults() throws Exception } private static DetachedConfig configWith(boolean enabled) { - DetachedConfig config = new DetachedConfig(); + DetachedConfig config = new DetachedConfig(CONFIG); config.initialize(false); config.enabled = enabled; config.save(); @@ -241,7 +260,7 @@ private static Off turnOff(Config config) throws Exception { ConfigManager manager = ConfigManager.active(); Tree tree = config.tree; configs().remove(config.id); - manager.unregister(config.id); + manager.unregister(tree.getID()); return () -> { configs().put(config.id, config); trees(manager).put(tree.getID(), tree); @@ -287,6 +306,7 @@ private static Object read(Class type, Object target, String name) throws Exc private static void cleanup() throws Exception { configs().remove(CONFIG); + configs().remove(SPACED_CONFIG); ConfigManager.active().delete(CONFIG); ConfigManager.active().unregister(COMPAT); CompatSnapshots.untrack(COMPAT); @@ -308,8 +328,8 @@ private static final class DetachedConfig extends Config { @Switch(title = "Enabled") boolean enabled = false; - private DetachedConfig() { - super(CONFIG, "Detached Rebind Test", Category.OTHER); + private DetachedConfig(String id) { + super(id, "Detached Rebind Test", Category.OTHER); addCallback("enabled", () -> { }); }