81 lines
2.3 KiB
C#
81 lines
2.3 KiB
C#
using System.IO;
|
|
using Raylib_cs;
|
|
using Tomlyn;
|
|
|
|
namespace SzGui;
|
|
|
|
public static class ApplicationSettings
|
|
{
|
|
private static Dictionary<string, object> _settings = new();
|
|
private static readonly string _filePath = "settings.toml";
|
|
|
|
public static Dictionary<string, object> GetAllSettings() => _settings;
|
|
|
|
public static void CreateInitialSettings()
|
|
{
|
|
CreateSetting("ShowStartup", false);
|
|
CreateSetting("BackgroundColor", Color.DarkGray);
|
|
SaveSettings();
|
|
}
|
|
|
|
public static T GetSettingValue<T>(string settingName, T defaultValue = default!)
|
|
{
|
|
if (_settings.TryGetValue(settingName, out var value))
|
|
{
|
|
try
|
|
{
|
|
if (typeof(T) == typeof(float) && value is double d)
|
|
return (T)(object)(float)d;
|
|
|
|
return (T)Convert.ChangeType(value, typeof(T));
|
|
}
|
|
catch { return defaultValue; }
|
|
}
|
|
return defaultValue;
|
|
}
|
|
|
|
public static bool SetSettingValue(string settingName, object value)
|
|
{
|
|
if (!_settings.ContainsKey(settingName)) return false;
|
|
_settings[settingName] = value;
|
|
return true;
|
|
}
|
|
|
|
public static bool CreateSetting(string name, object value)
|
|
{
|
|
return _settings.TryAdd(name, value);
|
|
}
|
|
|
|
public static void SaveSettings()
|
|
{
|
|
try
|
|
{
|
|
var saveDict = new Dictionary<string, object>();
|
|
|
|
foreach(var kvp in _settings)
|
|
{
|
|
if (kvp.Value is Color c)
|
|
saveDict[kvp.Key] = new int[] { c.R, c.G, c.B };
|
|
else
|
|
saveDict[kvp.Key] = kvp.Value;
|
|
}
|
|
|
|
var tomlString = Toml.FromModel(saveDict);
|
|
File.WriteAllText(_filePath, tomlString);
|
|
}
|
|
catch (Exception ex) { Console.WriteLine($"Save Error: {ex.Message}"); }
|
|
}
|
|
|
|
public static void LoadSettings()
|
|
{
|
|
if (!File.Exists(_filePath)) { SaveSettings(); return; }
|
|
|
|
try
|
|
{
|
|
var tomlString = File.ReadAllText(_filePath);
|
|
var loaded = Toml.ToModel<Dictionary<string, object>>(tomlString);
|
|
if (loaded != null) _settings = loaded;
|
|
}
|
|
catch (Exception ex) { Console.WriteLine($"Load Error: {ex.Message}"); }
|
|
}
|
|
} |