UnityExplorer/src/Config/InternalConfigHandler.cs

80 lines
2.2 KiB
C#
Raw Normal View History

2022-01-19 17:34:53 +11:00
using System;
2021-04-16 17:49:19 +10:00
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityExplorer.UI;
2022-01-19 17:34:53 +11:00
using Tomlet;
using Tomlet.Models;
2021-04-16 17:49:19 +10:00
namespace UnityExplorer.Config
2021-04-16 17:49:19 +10:00
{
public class InternalConfigHandler : ConfigHandler
{
2022-01-19 17:34:53 +11:00
internal static string CONFIG_PATH;
2021-04-16 17:49:19 +10:00
public override void Init()
{
CONFIG_PATH = Path.Combine(ExplorerCore.ExplorerFolder, "data.cfg");
2021-04-16 17:49:19 +10:00
}
public override void LoadConfig()
{
if (!TryLoadConfig())
SaveConfig();
}
public override void RegisterConfigElement<T>(ConfigElement<T> element)
{
// Not necessary
}
public override void SetConfigValue<T>(ConfigElement<T> element, T value)
{
// Not necessary
2021-04-16 17:49:19 +10:00
}
2022-01-19 17:34:53 +11:00
// Not necessary, just return the value.
public override T GetConfigValue<T>(ConfigElement<T> element) => element.Value;
2021-04-16 17:49:19 +10:00
2022-01-19 17:34:53 +11:00
// Always just auto-save.
public override void OnAnyConfigChanged() => SaveConfig();
2021-04-16 17:49:19 +10:00
public bool TryLoadConfig()
{
try
{
2022-01-19 17:34:53 +11:00
if (!File.Exists(CONFIG_PATH))
2021-04-16 17:49:19 +10:00
return false;
2022-01-19 17:34:53 +11:00
TomlDocument document = TomlParser.ParseFile(CONFIG_PATH);
foreach (var key in document.Keys)
2021-04-16 17:49:19 +10:00
{
2022-01-19 17:34:53 +11:00
var panelKey = (UIManager.Panels)Enum.Parse(typeof(UIManager.Panels), key);
ConfigManager.GetPanelSaveData(panelKey).Value = document.GetString(key);
2021-04-16 17:49:19 +10:00
}
return true;
}
catch (Exception ex)
2021-04-16 17:49:19 +10:00
{
ExplorerCore.LogWarning("Error loading internal data: " + ex.ToString());
2021-04-16 17:49:19 +10:00
return false;
}
}
public override void SaveConfig()
{
if (UIManager.Initializing)
return;
2022-01-19 17:34:53 +11:00
var tomlDocument = TomlDocument.CreateEmpty();
2021-04-16 17:49:19 +10:00
foreach (var entry in ConfigManager.InternalConfigs)
2022-01-19 17:34:53 +11:00
tomlDocument.Put(entry.Key, entry.Value.BoxedValue as string, false);
2021-04-16 17:49:19 +10:00
2022-01-19 17:34:53 +11:00
File.WriteAllText(CONFIG_PATH, tomlDocument.SerializedValue);
}
2021-04-16 17:49:19 +10:00
}
}