|
| 1 | +package org.embeddedt.modernfix.forge.config; |
| 2 | + |
| 3 | +import net.minecraftforge.fml.ModContainer; |
| 4 | +import net.minecraftforge.fml.ModList; |
| 5 | +import net.minecraftforge.fml.common.ObfuscationReflectionHelper; |
| 6 | +import net.minecraftforge.fml.config.ModConfig; |
| 7 | +import org.embeddedt.modernfix.ModernFix; |
| 8 | + |
| 9 | +import java.util.Optional; |
| 10 | +import java.util.function.Consumer; |
| 11 | + |
| 12 | +public class ConfigFixer { |
| 13 | + /** |
| 14 | + * To prevent mods from crashing if their ModConfigEvent is invoked by Night Config's watch thread and Forge |
| 15 | + * at the same time, wrap their config handler so that it only executes the event in serial for that mod. |
| 16 | + * |
| 17 | + * Should have no noticeable performance impact as config handlers are virtually instant. |
| 18 | + */ |
| 19 | + public static void replaceConfigHandlers() { |
| 20 | + ModList.get().forEachModContainer((id, container) -> { |
| 21 | + try { |
| 22 | + Optional<Consumer<ModConfig.ModConfigEvent>> configOpt = ObfuscationReflectionHelper.getPrivateValue(ModContainer.class, container, "configHandler"); |
| 23 | + if(configOpt.isPresent()) { |
| 24 | + ObfuscationReflectionHelper.setPrivateValue(ModContainer.class, container, Optional.of(new LockingConfigHandler(id, configOpt.get())), "configHandler"); |
| 25 | + } |
| 26 | + } catch(RuntimeException e) { |
| 27 | + ModernFix.LOGGER.error("Error replacing config handler", e); |
| 28 | + } |
| 29 | + }); |
| 30 | + } |
| 31 | + |
| 32 | + private static class LockingConfigHandler implements Consumer<ModConfig.ModConfigEvent> { |
| 33 | + private final Consumer<ModConfig.ModConfigEvent> actualHandler; |
| 34 | + private final String modId; |
| 35 | + |
| 36 | + LockingConfigHandler(String id, Consumer<ModConfig.ModConfigEvent> actualHandler) { |
| 37 | + this.modId = id; |
| 38 | + this.actualHandler = actualHandler; |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public void accept(ModConfig.ModConfigEvent modConfigEvent) { |
| 43 | + synchronized (this) { |
| 44 | + this.actualHandler.accept(modConfigEvent); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + public String toString() { |
| 50 | + return "LockingConfigHandler{id=" + modId + "}"; |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments