diff --git a/src/main/java/dynamic_fps/impl/DynamicFPSMod.java b/src/main/java/dynamic_fps/impl/DynamicFPSMod.java index b3f7fd5b..03bc38a8 100644 --- a/src/main/java/dynamic_fps/impl/DynamicFPSMod.java +++ b/src/main/java/dynamic_fps/impl/DynamicFPSMod.java @@ -62,8 +62,6 @@ public class DynamicFPSMod implements ClientModInitializer { @Override public void onInitializeClient() { - modConfig.save(); // Force create file on disk - toggleForcedKeyBinding.register(); toggleDisabledKeyBinding.register(); diff --git a/src/main/java/dynamic_fps/impl/config/DynamicFPSConfig.java b/src/main/java/dynamic_fps/impl/config/DynamicFPSConfig.java index 747f5bff..b256cf95 100644 --- a/src/main/java/dynamic_fps/impl/config/DynamicFPSConfig.java +++ b/src/main/java/dynamic_fps/impl/config/DynamicFPSConfig.java @@ -5,6 +5,7 @@ import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.util.EnumMap; import java.util.Map; @@ -21,7 +22,9 @@ public final class DynamicFPSConfig { private Map configs; - private static final Path PATH = FabricLoader.getInstance().getConfigDir().resolve(DynamicFPSMod.MOD_ID + ".json"); + private static final Path CONFIGS = FabricLoader.getInstance().getConfigDir(); + private static final Path CONFIG_FILE = CONFIGS.resolve(DynamicFPSMod.MOD_ID + ".json"); + private static final Codec> STATES_CODEC = Codec.unboundedMap(PowerState.CODEC, Config.CODEC); private static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( @@ -54,9 +57,11 @@ public static DynamicFPSConfig load() { String data; try { - data = Files.readString(PATH); + data = Files.readString(CONFIG_FILE); } catch (NoSuchFileException e) { - return new DynamicFPSConfig(new EnumMap<>(PowerState.class)); + var config = new DynamicFPSConfig(new EnumMap<>(PowerState.class)); + config.save(); + return config; } catch (IOException e) { throw new RuntimeException("Failed to load Dynamic FPS config.", e); } @@ -72,10 +77,14 @@ public void save() { var root = data.getOrThrow(false, RuntimeException::new); try { - Files.writeString(PATH, root.toString(), StandardCharsets.UTF_8); + var temp = Files.createTempFile(CONFIGS, "dynamic_fps", ".json"); + Files.writeString(temp, root.toString(), StandardCharsets.UTF_8); + + Files.deleteIfExists(CONFIG_FILE); + Files.move(temp, CONFIG_FILE, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { - // Cloth Config's automatic saving does not support catching exceptions - throw new RuntimeException("Failed to save Dynamic FPS config.", e); + // Cloth Config's built-in saving does not support catching exceptions :( + throw new RuntimeException("Failed to save or modify Dynamic FPS config!", e); } }