This repository has been archived by the owner on Jul 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnsavedEntry.cs
52 lines (43 loc) · 2.16 KB
/
UnsavedEntry.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using BepInEx.Configuration;
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace KiraiMod.Core.UI
{
public abstract class UnsavedEntry : ConfigEntryBase
{
protected UnsavedEntry(ConfigFile file, ConfigDefinition definition, Type type, object value, ConfigDescription description)
: base(file, definition, type, value, description)
{
((Dictionary<ConfigDefinition, ConfigEntryBase>)Hooks.Entries.GetValue(file))[definition] = this;
file.SettingChanged += (object sender, SettingChangedEventArgs args) =>
{
if (args.ChangedSetting == this)
SettingChanged?.Invoke(sender, args);
};
}
public event EventHandler SettingChanged;
public static class Hooks
{
static Hooks() => Harmony.CreateAndPatchAll(typeof(Hooks));
public static FieldInfo Entries = typeof(ConfigFile).GetField("<Entries>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance);
[HarmonyPrefix, HarmonyPatch(typeof(ConfigFile), nameof(ConfigFile.Save), MethodType.Normal)]
public static void PreSave(ConfigFile __instance, ref (KeyValuePair<ConfigDefinition, ConfigEntryBase>[], Dictionary<ConfigDefinition, ConfigEntryBase>) __state)
{
var entries = (Dictionary<ConfigDefinition, ConfigEntryBase>)Entries.GetValue(__instance);
var removal = entries.Where(x => x.Value.GetType().GetGenericTypeDefinition() == typeof(MemoryEntry<>)).ToArray();
foreach (var entry in removal)
entries.Remove(entry.Key);
__state = (removal, entries);
}
[HarmonyPostfix, HarmonyPatch(typeof(ConfigFile), nameof(ConfigFile.Save), MethodType.Normal)]
public static void PostSave((KeyValuePair<ConfigDefinition, ConfigEntryBase>[], Dictionary<ConfigDefinition, ConfigEntryBase>) __state)
{
foreach (var entry in __state.Item1)
__state.Item2.Add(entry.Key, entry.Value);
}
}
}
}