worldbox-observer-mod/IdleSpectator/ModSettings.cs
2026-07-14 15:13:49 -05:00

100 lines
2.8 KiB
C#

using System.IO;
using NeoModLoader.api;
using NeoModLoader.constants;
using NeoModLoader.services;
namespace IdleSpectator;
/// <summary>
/// NML ModConfig accessors for Idle Spectator.
/// </summary>
public static class ModSettings
{
public const string GroupId = "Spectator";
public const string EnabledId = "enabled";
public const string ShowWatchReasonsId = "show_watch_reasons";
public const string DebugStateProbeId = "debug_state_probe";
private static ModConfig _config;
public static bool Enabled => GetBool(EnabledId, defaultValue: true);
public static bool ShowWatchReasons => GetBool(ShowWatchReasonsId, defaultValue: true);
public static bool DebugStateProbe => GetBool(DebugStateProbeId, defaultValue: true);
public static ModConfig Load(ModDeclare declare)
{
string persistentPath = Path.Combine(Paths.ModsConfigPath, declare.UID + ".config");
ModConfig persistent = new ModConfig(persistentPath, pIsPersistent: true);
string defaultsPath = Path.Combine(declare.FolderPath, Paths.ModDefaultConfigFileName);
if (File.Exists(defaultsPath))
{
ModConfig defaults = new ModConfig(defaultsPath);
persistent.MergeWith(defaults);
}
_config = persistent;
return _config;
}
/// <summary>NML config callback: IdleSpectator.ModSettings:OnEnabledChanged</summary>
public static void OnEnabledChanged(bool enabled)
{
if (!enabled && SpectatorMode.Active)
{
SpectatorMode.SetActive(false);
LogService.LogInfo("[IdleSpectator] Disabled via settings");
}
}
public static bool TrySetBool(string id, bool value)
{
if (_config == null || string.IsNullOrEmpty(id))
{
return false;
}
try
{
ModConfigItem item = _config[GroupId][id];
item.SetValue(value);
// Ensure settings callbacks apply even if NML does not fire them from SetValue.
if (id == EnabledId)
{
OnEnabledChanged(value);
}
return true;
}
catch (System.Exception ex)
{
LogService.LogInfo($"[IdleSpectator] TrySetBool failed for {id}: {ex.Message}");
return false;
}
}
private static bool GetBool(string id, bool defaultValue)
{
if (_config == null)
{
return defaultValue;
}
try
{
ModConfigItem item = _config[GroupId][id];
object value = item.GetValue();
if (value is bool b)
{
return b;
}
}
catch
{
// Fall through to default.
}
return defaultValue;
}
}