Decompiled source of POG Fonts v1.2.0

POGFonts.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using POGMods.Config;
using POGMods.Fonts;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(FontsMod), "POG Fonts", "1.2.0", "largo", "https://github.com/largoz/POGFonts")]
[assembly: MelonOptionalDependencies(new string[] { "POGConfig" })]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("POGFonts")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a9227a5e04b972a16c492a29a2e3a2bcab450186")]
[assembly: AssemblyProduct("POGFonts")]
[assembly: AssemblyTitle("POGFonts")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace POGMods.Fonts;

internal static class ConfigPage
{
	private const string PageName = "POG Fonts";

	private const string TagOriginal = "Original";

	private const string TagMods = "Font mods";

	private const string TagGame = "Game fonts";

	[MethodImpl(MethodImplOptions.NoInlining)]
	public static void Register(List<FontSlot> slots, Func<FontSlot, string> selected, Action<FontSlot, string> select)
	{
		try
		{
			RegisterWithLists(slots, selected, select);
		}
		catch (Exception ex) when (ex is TypeLoadException || ex is MissingMethodException)
		{
			RegisterWithSliders(slots, selected, select);
		}
	}

	private static ModInfo Info()
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Expected O, but got Unknown
		return new ModInfo("1.2.0", "Font manager: pick the font for each kind of text in the game. A chosen font draws the letters it has; the rest stay as in the original. A font file put into UserData/POGFonts/<game font name>/ shows up here after a restart.", "largo");
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static void RegisterWithLists(List<FontSlot> slots, Func<FontSlot, string> selected, Action<FontSlot, string> select)
	{
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		List<ConfigEntry> list = new List<ConfigEntry>();
		foreach (FontSlot slot in slots)
		{
			FontSlot s = slot;
			List<Option> list2 = s.Options.Select((FontOption o) => ToOption(s, o)).ToList();
			ChoiceRow val = new ChoiceRow(s.Label, (Func<string>)(() => selected(s)), (Action<string>)delegate(string v)
			{
				select(s, v);
			}, (IEnumerable<Option>)list2).Filters(new string[3] { "Original", "Font mods", "Game fonts" });
			string text = GameFonts.Use(s.Target);
			if (text != null)
			{
				val.Description(text);
			}
			list.Add((ConfigEntry)(object)val);
		}
		POGConfig.Register("POG Fonts", list, Info());
	}

	private static Option ToOption(FontSlot slot, FontOption o)
	{
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Expected O, but got Unknown
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Expected O, but got Unknown
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Expected O, but got Unknown
		string text = GameFonts.Display(slot.Target);
		if (o.Kind == OptionKind.Replace && o.Choice != null)
		{
			return new Option(o.Name, o.Choice.Name, "Draws this text; letters it lacks stay as in the original", new string[1] { "Font mods" });
		}
		if (o.Kind != OptionKind.Replace)
		{
			string text2 = ((slot.AddOns.Count > 0) ? (", with letters from " + string.Join(", ", slot.AddOns.Select((FontChoice c) => c.Name))) : ", unchanged");
			return new Option(o.Name, text + " (original)", "The game's own font for this text" + text2, new string[1] { "Original" });
		}
		return new Option(o.Name, GameFonts.Display(o.GameFont) + " (game font)", "The game's " + GameFonts.Display(o.GameFont) + "; letters it lacks stay as in the original", new string[1] { "Game fonts" });
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static void RegisterWithSliders(List<FontSlot> slots, Func<FontSlot, string> selected, Action<FontSlot, string> select)
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected O, but got Unknown
		List<ConfigEntry> list = new List<ConfigEntry>();
		foreach (FontSlot slot in slots)
		{
			FontSlot s = slot;
			string[] options = s.OptionNames();
			list.Add((ConfigEntry)new OptionsSliderEntry(s.Label, (Func<int>)(() => Math.Max(0, Array.IndexOf(options, selected(s)))), (Action<int>)delegate(int i)
			{
				select(s, options[Math.Clamp(i, 0, options.Length - 1)]);
			}, options, (string)null));
		}
		POGConfig.Register("POG Fonts", list, Info());
	}
}
internal sealed class FallbackPatcher
{
	public const string OwnSuffix = " (POG Fonts)";

	private const string ReplaceSample = "AaGgZz09";

	private readonly Instance _log;

	private readonly Dictionary<string, TMP_FontAsset> _assets = new Dictionary<string, TMP_FontAsset>();

	private readonly HashSet<string> _failedFiles = new HashSet<string>();

	private readonly Dictionary<string, TMP_FontAsset> _originalCopies = new Dictionary<string, TMP_FontAsset>();

	private readonly Dictionary<string, TargetState> _states = new Dictionary<string, TargetState>();

	public Action<string> GameFontSeen;

	private const float LogSettleSeconds = 1f;

	private readonly Dictionary<string, (string text, float at)> _pendingLog = new Dictionary<string, (string, float)>();

	public void FlushLog()
	{
		if (_pendingLog.Count == 0)
		{
			return;
		}
		foreach (string item in _pendingLog.Keys.ToList())
		{
			var (text, num) = _pendingLog[item];
			if (!(Time.unscaledTime - num < 1f))
			{
				_log.Msg(text);
				_pendingLog.Remove(item);
			}
		}
	}

	public FallbackPatcher(Instance log)
	{
		_log = log;
	}

	public bool Apply(List<FontSlot> slots, Func<FontSlot, string> selected)
	{
		Il2CppArrayBase<TMP_FontAsset> val = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
		Dictionary<string, TMP_FontAsset> dictionary = new Dictionary<string, TMP_FontAsset>();
		foreach (TMP_FontAsset item in val)
		{
			if (!((Object)(object)item == (Object)null))
			{
				string name = ((Object)item).name;
				if (!name.EndsWith(" (POG Fonts)") && !dictionary.ContainsKey(name))
				{
					dictionary[name] = item;
				}
			}
		}
		foreach (string key in dictionary.Keys)
		{
			GameFontSeen?.Invoke(key);
		}
		bool result = false;
		bool flag = false;
		List<(FontSlot, FontOption, TMP_FontAsset, TMP_FontAsset, List<TMP_FontAsset>)> list = new List<(FontSlot, FontOption, TMP_FontAsset, TMP_FontAsset, List<TMP_FontAsset>)>();
		foreach (FontSlot slot2 in slots)
		{
			FontOption fontOption = slot2.Find(selected(slot2)) ?? FontOption.VanillaOption;
			if (!dictionary.TryGetValue(slot2.Target, out var value))
			{
				if (fontOption.Kind != OptionKind.Vanilla)
				{
					result = true;
					WarnMissing(slot2, slot2.Target);
				}
				continue;
			}
			List<TMP_FontAsset> list2 = new List<TMP_FontAsset>();
			foreach (FontChoice addOn in slot2.AddOns)
			{
				TMP_FontAsset val2 = AssetFor(addOn, value);
				if ((Object)(object)val2 != (Object)null)
				{
					list2.Add(val2);
				}
			}
			List<TMP_FontAsset> list3 = new List<TMP_FontAsset>(list2);
			bool flag2 = false;
			TMP_FontAsset val3 = null;
			if (fontOption.Kind == OptionKind.Replace)
			{
				TMP_FontAsset value2;
				if (fontOption.Choice != null)
				{
					val3 = AssetFor(fontOption.Choice, value);
				}
				else if (dictionary.TryGetValue(fontOption.GameFont, out value2))
				{
					val3 = OwnLettersOf(value2, value);
				}
				else
				{
					result = true;
					WarnMissing(slot2, fontOption.GameFont);
				}
				if ((Object)(object)val3 != (Object)null)
				{
					list3.Clear();
					list3.Add(val3);
					TMP_FontAsset val4 = OriginalCopy(value);
					if ((Object)(object)val4 != (Object)null)
					{
						list3.Add(val4);
					}
					list3.AddRange(list2);
					flag2 = true;
				}
			}
			TargetState state = StateFor(value);
			bool num = SetOwnLetters(value, state, !flag2);
			bool flag3 = SetFallbacks(value, state, list3);
			if (num || flag3)
			{
				flag = true;
				string text = (flag2 ? ("drawn in " + fontOption.Name.Substring(9)) : ((list2.Count > 0) ? ("original, with letters from " + string.Join(", ", slot2.AddOns.Select((FontChoice c) => c.Name))) : "original"));
				_pendingLog[((Object)value).name] = (((Object)value).name + ": " + text, Time.unscaledTime);
				list.Add((slot2, flag2 ? fontOption : FontOption.VanillaOption, value, val3, list2));
			}
		}
		if (flag)
		{
			ForgetRememberedLetters((IEnumerable<TMP_FontAsset>)val);
			foreach (var (slot, option, target, chosen, addOns) in list)
			{
				SelfCheck(slot, option, target, chosen, addOns);
			}
			RefreshTexts();
		}
		return result;
	}

	private void WarnMissing(FontSlot slot, string name)
	{
		if (!slot.WarnedMissing && !(Time.unscaledTime < 120f))
		{
			slot.WarnedMissing = true;
			_log.Msg(slot.Label + ": waiting for the game font \"" + name + "\" to load (some load only in levels)");
		}
	}

	private TargetState StateFor(TMP_FontAsset target)
	{
		if (_states.TryGetValue(((Object)target).name, out var value) && value.Instance == ((Il2CppObjectBase)target).Pointer)
		{
			return value;
		}
		value = new TargetState
		{
			Instance = ((Il2CppObjectBase)target).Pointer,
			OriginalFallbacks = new List<TMP_FontAsset>()
		};
		List<TMP_FontAsset> fallbackFontAssetTable = target.fallbackFontAssetTable;
		if (fallbackFontAssetTable != null)
		{
			for (int i = 0; i < fallbackFontAssetTable.Count; i++)
			{
				value.OriginalFallbacks.Add(fallbackFontAssetTable[i]);
			}
		}
		_states[((Object)target).name] = value;
		return value;
	}

	private static bool SetOwnLetters(TMP_FontAsset target, TargetState state, bool on)
	{
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		List<TMP_Character> characterTable = target.characterTable;
		if (on)
		{
			if (state.OwnCharacters == null)
			{
				return false;
			}
			characterTable.Clear();
			foreach (TMP_Character ownCharacter in state.OwnCharacters)
			{
				characterTable.Add(ownCharacter);
			}
			target.atlasPopulationMode = state.OwnMode;
			state.OwnCharacters = null;
		}
		else
		{
			if (state.OwnCharacters != null)
			{
				return false;
			}
			state.OwnCharacters = new List<TMP_Character>();
			for (int i = 0; i < characterTable.Count; i++)
			{
				state.OwnCharacters.Add(characterTable[i]);
			}
			state.OwnMode = target.atlasPopulationMode;
			characterTable.Clear();
			target.atlasPopulationMode = (AtlasPopulationMode)0;
		}
		target.ReadFontAssetDefinition();
		return true;
	}

	private static bool SetFallbacks(TMP_FontAsset target, TargetState state, List<TMP_FontAsset> head)
	{
		List<TMP_FontAsset> list = new List<TMP_FontAsset>(head);
		foreach (TMP_FontAsset f in state.OriginalFallbacks)
		{
			if (!list.Any((TMP_FontAsset d) => (Object)(object)d == (Object)(object)f))
			{
				list.Add(f);
			}
		}
		List<TMP_FontAsset> val = target.fallbackFontAssetTable;
		if (val == null)
		{
			if (list.Count == 0)
			{
				return false;
			}
			val = (target.fallbackFontAssetTable = new List<TMP_FontAsset>());
		}
		bool flag = val.Count == list.Count;
		int num = 0;
		while (flag && num < list.Count)
		{
			flag = (Object)(object)val[num] == (Object)(object)list[num];
			num++;
		}
		if (flag)
		{
			return false;
		}
		val.Clear();
		foreach (TMP_FontAsset item in list)
		{
			val.Add(item);
		}
		return true;
	}

	private TMP_FontAsset AssetFor(FontChoice choice, TMP_FontAsset target)
	{
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		string key = choice.Name + "|" + ((Object)target).name;
		if (_assets.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
		{
			return value;
		}
		if (_failedFiles.Contains(choice.FontFile))
		{
			return null;
		}
		int num = Mathf.RoundToInt(((TMP_Asset)target).faceInfo.pointSize);
		TMP_FontAsset val = null;
		try
		{
			val = TMP_FontAsset.CreateFontAsset(choice.FontFile, 0, num, target.atlasPadding, target.atlasRenderMode, target.atlasWidth, target.atlasHeight);
		}
		catch (Exception ex)
		{
			_log.Error(choice.Name + ": " + ex.Message);
		}
		if ((Object)(object)val == (Object)null)
		{
			_failedFiles.Add(choice.FontFile);
			_log.Error(choice.Name + ": TextMeshPro could not load " + choice.FontFile + ". Is it a valid TTF/OTF font?");
			return null;
		}
		Keep(val, choice.Name + " (POG Fonts)");
		MelonDebug.Msg($"[POG Fonts] {choice.Name}: loaded for {((Object)target).name} (sampling {num}, padding {target.atlasPadding}, {target.atlasRenderMode}, atlas {target.atlasWidth}x{target.atlasHeight})");
		_assets[key] = val;
		return val;
	}

	private TMP_FontAsset OwnLettersOf(TMP_FontAsset game, TMP_FontAsset target)
	{
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		string key = "game:" + ((Object)game).name + "|" + ((Object)target).name;
		if (_assets.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
		{
			return value;
		}
		TMP_FontAsset val = null;
		Font sourceFontFile = game.sourceFontFile;
		string value2;
		try
		{
			if ((Object)(object)sourceFontFile != (Object)null)
			{
				val = TMP_FontAsset.CreateFontAsset(sourceFontFile, Mathf.RoundToInt(((TMP_Asset)target).faceInfo.pointSize), target.atlasPadding, target.atlasRenderMode, target.atlasWidth, target.atlasHeight, (AtlasPopulationMode)1, true);
				value2 = "from its font file";
			}
			else
			{
				val = Object.Instantiate<TMP_FontAsset>(game);
				val.fallbackFontAssetTable = new List<TMP_FontAsset>();
				if (_states.TryGetValue(((Object)game).name, out var value3) && value3.Instance == ((Il2CppObjectBase)game).Pointer && value3.OwnCharacters != null)
				{
					List<TMP_Character> characterTable = val.characterTable;
					characterTable.Clear();
					foreach (TMP_Character ownCharacter in value3.OwnCharacters)
					{
						characterTable.Add(ownCharacter);
					}
				}
				val.ReadFontAssetDefinition();
				value2 = "as a clone of its fixed atlas";
			}
		}
		catch (Exception ex)
		{
			_log.Warning($"{((Object)game).name}: could not copy its letters for {((Object)target).name} ({ex.Message})");
			return null;
		}
		if ((Object)(object)val == (Object)null)
		{
			return null;
		}
		Keep(val, GameFonts.Display(((Object)game).name) + " for " + GameFonts.Display(((Object)target).name) + " (POG Fonts)");
		MelonDebug.Msg($"[POG Fonts] {((Object)game).name}: letters copied for {((Object)target).name} {value2}");
		_assets[key] = val;
		return val;
	}

	private TMP_FontAsset OriginalCopy(TMP_FontAsset target)
	{
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		if (_originalCopies.TryGetValue(((Object)target).name, out var value))
		{
			return value;
		}
		TMP_FontAsset val = null;
		Font sourceFontFile = target.sourceFontFile;
		if ((Object)(object)sourceFontFile != (Object)null)
		{
			try
			{
				val = TMP_FontAsset.CreateFontAsset(sourceFontFile, Mathf.RoundToInt(((TMP_Asset)target).faceInfo.pointSize), target.atlasPadding, target.atlasRenderMode, target.atlasWidth, target.atlasHeight, (AtlasPopulationMode)1, true);
			}
			catch (Exception ex)
			{
				_log.Warning(((Object)target).name + ": no copy of its own font (" + ex.Message + ")");
			}
		}
		if ((Object)(object)val != (Object)null)
		{
			Keep(val, GameFonts.Display(((Object)target).name) + " original (POG Fonts)");
		}
		_originalCopies[((Object)target).name] = val;
		return val;
	}

	private static void Keep(TMP_FontAsset asset, string name)
	{
		((Object)asset).name = name;
		((Object)asset).hideFlags = (HideFlags)32;
		if ((Object)(object)((TMP_Asset)asset).material != (Object)null)
		{
			((Object)((TMP_Asset)asset).material).hideFlags = (HideFlags)32;
		}
		Il2CppReferenceArray<Texture2D> atlasTextures = asset.atlasTextures;
		if (atlasTextures == null)
		{
			return;
		}
		foreach (Texture2D item in (Il2CppArrayBase<Texture2D>)(object)atlasTextures)
		{
			if ((Object)(object)item != (Object)null)
			{
				((Object)item).hideFlags = (HideFlags)32;
			}
		}
	}

	private void ForgetRememberedLetters(IEnumerable<TMP_FontAsset> loaded)
	{
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		foreach (TMP_FontAsset item in loaded)
		{
			if (!((Object)(object)item == (Object)null))
			{
				int num4 = CountRemembered(item);
				if (num4 != 0)
				{
					item.ReadFontAssetDefinition();
					num++;
					num2 += num4;
					num3 += CountRemembered(item);
				}
			}
		}
		if (num3 > 0)
		{
			_log.Warning($"forgot {num2} letters remembered from fallbacks in {num} fonts, but {num3} are still remembered");
		}
		else if (num > 0)
		{
			MelonDebug.Msg($"[POG Fonts] forgot {num2} letters remembered from fallbacks in {num} fonts");
		}
	}

	private static int CountRemembered(TMP_FontAsset font)
	{
		Dictionary<uint, TMP_Character> characterLookupTable = font.characterLookupTable;
		if (characterLookupTable == null)
		{
			return 0;
		}
		int num = 0;
		Enumerator<uint, TMP_Character> enumerator = characterLookupTable.Values.GetEnumerator();
		while (enumerator.MoveNext())
		{
			TMP_Character current = enumerator.Current;
			if (current != null && (Object)(object)((TMP_TextElement)current).textAsset != (Object)null && (Object)(object)((TMP_TextElement)current).textAsset != (Object)(object)font)
			{
				num++;
			}
		}
		return num;
	}

	private void SelfCheck(FontSlot slot, FontOption option, TMP_FontAsset target, TMP_FontAsset chosen, List<TMP_FontAsset> addOns)
	{
		_originalCopies.TryGetValue(((Object)target).name, out var original);
		string letters = string.Concat(slot.AddOns.Select((FontChoice c) => c.Sample ?? ""));
		StringBuilder bad = new StringBuilder();
		if (option.Kind == OptionKind.Replace)
		{
			Check("AaGgZz09", (TMP_Asset a) => (Object)(object)a != (Object)null && (Object)(object)a == (Object)(object)chosen);
			Check(letters, (TMP_Asset a) => (Object)(object)a != (Object)null && ((Object)(object)a == (Object)(object)chosen || (Object)(object)a == (Object)(object)original || IsAddOn(a)));
		}
		else
		{
			Check("AaGgZz09", (TMP_Asset a) => (Object)(object)a != (Object)null && (Object)(object)a == (Object)(object)target);
			Check(letters, IsAddOn);
		}
		if (bad.Length == 0)
		{
			MelonDebug.Msg($"[POG Fonts] {((Object)target).name}: check OK ({option.Name})");
		}
		else
		{
			_log.Warning($"{((Object)target).name}: check failed for {option.Name}: {bad.ToString().Trim()}");
		}
		void Check(string text, Func<TMP_Asset, bool> ok)
		{
			bool flag = default(bool);
			foreach (char c in text)
			{
				TMP_Character characterFromFontAsset = TMP_FontAssetUtilities.GetCharacterFromFontAsset((uint)c, target, true, (FontStyles)0, (FontWeight)400, ref flag);
				TMP_Asset val = ((characterFromFontAsset != null) ? ((TMP_TextElement)characterFromFontAsset).textAsset : null);
				if (!ok(val))
				{
					bad.Append(c).Append('→').Append(((Object)(object)val != (Object)null) ? ((Object)val).name : "none")
						.Append(' ');
				}
			}
		}
		bool IsAddOn(TMP_Asset a)
		{
			if ((Object)(object)a != (Object)null)
			{
				return addOns.Any((TMP_FontAsset x) => (Object)(object)x == (Object)(object)a);
			}
			return false;
		}
	}

	private void RefreshTexts()
	{
		int num = 0;
		foreach (TMP_Text item in Resources.FindObjectsOfTypeAll<TMP_Text>())
		{
			if (!((Object)(object)item == (Object)null) && ((Behaviour)item).isActiveAndEnabled)
			{
				try
				{
					item.ForceMeshUpdate(false, true);
					num++;
				}
				catch
				{
				}
			}
		}
		if (num > 0)
		{
			MelonDebug.Msg($"[POG Fonts] refreshed {num} text objects");
		}
	}
}
internal static class FontCatalog
{
	public const string DescriptorName = "pogfont.json";

	public const int DescriptorFormat = 1;

	private static readonly string[] FontExtensions = new string[2] { ".ttf", ".otf" };

	public static List<FontChoice> Build(string modsFolder, string userFolder, Action<string> info, Action<string> warn)
	{
		List<FontChoice> choices = new List<FontChoice>();
		List<string> list = Find(modsFolder, "pogfont.json", warn).Concat(Find(userFolder, "pogfont.json", warn)).ToList();
		foreach (string item in list)
		{
			FontChoice fontChoice = ReadDescriptor(item, warn);
			if (fontChoice != null)
			{
				Add(fontChoice, item);
			}
		}
		if (Directory.Exists(userFolder))
		{
			HashSet<string> hashSet = new HashSet<string>(list.Select(Path.GetDirectoryName), StringComparer.OrdinalIgnoreCase);
			foreach (string item2 in Directory.GetDirectories(userFolder).OrderBy<string, string>((string d) => d, StringComparer.OrdinalIgnoreCase))
			{
				if (hashSet.Contains(item2))
				{
					continue;
				}
				foreach (string item3 in (from f in Directory.GetFiles(item2)
					where FontExtensions.Contains(Path.GetExtension(f).ToLowerInvariant())
					select f).OrderBy<string, string>((string f) => f, StringComparer.OrdinalIgnoreCase))
				{
					Add(new FontChoice
					{
						Name = Path.GetFileNameWithoutExtension(item3),
						FontFile = item3,
						Target = Path.GetFileName(item2)
					}, item3);
				}
			}
		}
		return choices;
		void Add(FontChoice choice, string source)
		{
			if (choices.Exists((FontChoice c) => c.Name == choice.Name))
			{
				warn($"skipped {source}: a font named \"{choice.Name}\" is already installed");
			}
			else
			{
				choices.Add(choice);
				info($"font \"{choice.Name}\" (made for {choice.Target}) from {source}");
			}
		}
	}

	private static IEnumerable<string> Find(string folder, string fileName, Action<string> warn)
	{
		if (!Directory.Exists(folder))
		{
			return Array.Empty<string>();
		}
		try
		{
			EnumerationOptions enumerationOptions = new EnumerationOptions
			{
				RecurseSubdirectories = true,
				IgnoreInaccessible = true,
				MatchCasing = MatchCasing.CaseInsensitive
			};
			return Directory.EnumerateFiles(folder, fileName, enumerationOptions).OrderBy<string, string>((string p) => p, StringComparer.OrdinalIgnoreCase).ToList();
		}
		catch (Exception ex)
		{
			warn("could not search " + folder + ": " + ex.Message);
			return Array.Empty<string>();
		}
	}

	private static FontChoice ReadDescriptor(string path, Action<string> warn)
	{
		try
		{
			using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(path), new JsonDocumentOptions
			{
				AllowTrailingCommas = true,
				CommentHandling = JsonCommentHandling.Skip
			});
			JsonElement root = jsonDocument.RootElement;
			JsonElement value;
			int value2;
			int num = ((!root.TryGetProperty("format", out value) || !value.TryGetInt32(out value2)) ? 1 : value2);
			if (num > 1)
			{
				warn($"skipped {path}: written for a newer POG Fonts (format {num}); update POG Fonts");
				return null;
			}
			string text = Str("name");
			string text2 = Str("font");
			string text3 = Str("target");
			if (string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(text2) || string.IsNullOrWhiteSpace(text3))
			{
				warn("skipped " + path + ": \"name\", \"font\" and \"target\" are required");
				return null;
			}
			string fullPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), text2));
			if (!File.Exists(fullPath))
			{
				warn($"skipped {path}: font file {fullPath} not found");
				return null;
			}
			return new FontChoice
			{
				Name = text,
				FontFile = fullPath,
				Target = text3,
				Sample = Str("sample")
			};
			string Str(string key)
			{
				if (!root.TryGetProperty(key, out var value3) || value3.ValueKind != JsonValueKind.String)
				{
					return null;
				}
				return value3.GetString();
			}
		}
		catch (Exception ex)
		{
			warn("skipped " + path + ": " + ex.Message);
			return null;
		}
	}
}
internal sealed class FontChoice
{
	public string Name;

	public string FontFile;

	public string Target;

	public string Sample;
}
internal enum OptionKind
{
	Vanilla,
	Replace
}
internal sealed class FontOption
{
	public OptionKind Kind;

	public string Name;

	public FontChoice Choice;

	public string GameFont;

	public static readonly FontOption VanillaOption = new FontOption
	{
		Kind = OptionKind.Vanilla,
		Name = "Vanilla"
	};
}
internal sealed class FontSlot
{
	public const string Vanilla = "Vanilla";

	public string Target;

	public readonly List<FontChoice> AddOns = new List<FontChoice>();

	public string Label;

	public string DefaultName;

	public readonly List<FontOption> Options = new List<FontOption>();

	public bool WarnedMissing;

	public string[] OptionNames()
	{
		return Options.ConvertAll((FontOption o) => o.Name).ToArray();
	}

	public FontOption Find(string name)
	{
		return Options.Find((FontOption o) => o.Name == name);
	}

	public bool Has(string name)
	{
		return Find(name) != null;
	}
}
internal sealed class TargetState
{
	public IntPtr Instance;

	public List<TMP_FontAsset> OriginalFallbacks;

	public List<TMP_Character> OwnCharacters;

	public AtlasPopulationMode OwnMode;
}
internal sealed class FontSettings
{
	public const string Category = "POG_Fonts";

	private const string AddPrefix = "Add: ";

	private readonly MelonPreferences_Category _category;

	private readonly Dictionary<string, MelonPreferences_Entry<string>> _entries = new Dictionary<string, MelonPreferences_Entry<string>>();

	public bool CapturingDefaults;

	public event Action Changed;

	public FontSettings()
	{
		_category = MelonPreferences.CreateCategory("POG_Fonts", "POG Fonts");
	}

	private static string Key(FontSlot slot)
	{
		return Regex.Replace(slot.Target, "[^A-Za-z0-9_]", "_");
	}

	public void Bind(FontSlot slot, Action<string> warn)
	{
		string text = Key(slot);
		if (!_entries.TryGetValue(text, out var value))
		{
			value = _category.GetEntry<string>(text) ?? _category.CreateEntry<string>(text, slot.DefaultName, slot.Label, (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonEventBase<LemonAction<string, string>>)(object)value.OnEntryValueChanged).Subscribe((LemonAction<string, string>)delegate
			{
				this.Changed?.Invoke();
			}, 0, false);
			_entries[text] = value;
		}
		((MelonPreferences_Entry)value).Description = "Font for the game font \"" + slot.Target + "\". One of: " + string.Join(", ", slot.OptionNames());
		string v = value.Value ?? "";
		bool flag = slot.AddOns.Exists((FontChoice c) => v == c.Name || v == "Add: " + c.Name || v == "Replace: " + c.Name);
		if (!slot.Has(v) && flag)
		{
			value.Value = "Vanilla";
			_category.SaveToFile(false);
		}
		else if (!slot.Has(value.Value))
		{
			warn($"{slot.Label}: saved choice \"{value.Value}\" is not installed, using {slot.DefaultName}");
		}
	}

	public string Selected(FontSlot slot)
	{
		if (CapturingDefaults || !_entries.TryGetValue(Key(slot), out var value))
		{
			return slot.DefaultName;
		}
		if (!slot.Has(value.Value))
		{
			return slot.DefaultName;
		}
		return value.Value;
	}

	public void Select(FontSlot slot, string name)
	{
		if (slot.Has(name) && _entries.TryGetValue(Key(slot), out var value) && !(value.Value == name))
		{
			value.Value = name;
			_category.SaveToFile(false);
		}
	}
}
public class FontsMod : MelonMod
{
	public const string VERSION = "1.2.0";

	private const string UserFolderName = "POGFonts";

	private const string GameFontsFile = "game_fonts.txt";

	private const string ReplacePrefix = "Replace: ";

	private const string GameSuffix = " (game)";

	private const float RetryInterval = 2f;

	private List<FontChoice> _choices = new List<FontChoice>();

	private GameFonts _gameFonts;

	private List<FontSlot> _slots = new List<FontSlot>();

	private FontSettings _settings;

	private FallbackPatcher _patcher;

	private bool _configAvailable = true;

	private bool _applyRequested;

	private bool _rebuildRequested;

	private bool _pending;

	private float _nextTry;

	public override void OnInitializeMelon()
	{
		_patcher = new FallbackPatcher(((MelonBase)this).LoggerInstance);
		string text = Path.Combine(MelonEnvironment.UserDataDirectory, "POGFonts");
		try
		{
			Directory.CreateDirectory(text);
		}
		catch
		{
		}
		_choices = FontCatalog.Build(MelonEnvironment.ModsDirectory, text, delegate(string msg)
		{
			((MelonBase)this).LoggerInstance.Msg(msg);
		}, delegate(string msg)
		{
			((MelonBase)this).LoggerInstance.Warning(msg);
		});
		_gameFonts = new GameFonts(Path.Combine(text, "game_fonts.txt"), delegate(string msg)
		{
			((MelonBase)this).LoggerInstance.Warning(msg);
		});
		_settings = new FontSettings();
		_settings.Changed += delegate
		{
			_applyRequested = true;
		};
		_patcher.GameFontSeen = delegate(string name)
		{
			if (_gameFonts.Add(name))
			{
				_rebuildRequested = true;
			}
		};
		Rebuild();
		((MelonBase)this).LoggerInstance.Msg($"{_choices.Count} fonts installed, {_slots.Count} game fonts");
	}

	private void Rebuild()
	{
		_slots = BuildSlots(_choices, _gameFonts.Names);
		_settings.CapturingDefaults = true;
		try
		{
			if (_configAvailable)
			{
				ConfigPage.Register(_slots, (FontSlot s) => _settings.Selected(s), delegate(FontSlot s, string name)
				{
					_settings.Select(s, name);
				});
			}
		}
		catch (Exception ex) when (ex is FileNotFoundException || ex is TypeLoadException || ex is MissingMethodException)
		{
			_configAvailable = false;
			((MelonBase)this).LoggerInstance.Msg("POG Config not installed: choose fonts in UserData/MelonPreferences.cfg [POG_Fonts]");
		}
		finally
		{
			_settings.CapturingDefaults = false;
		}
		foreach (FontSlot slot in _slots)
		{
			_settings.Bind(slot, delegate(string msg)
			{
				((MelonBase)this).LoggerInstance.Warning(msg);
			});
		}
		_applyRequested = true;
	}

	private static List<FontSlot> BuildSlots(List<FontChoice> choices, IReadOnlyCollection<string> gameFonts)
	{
		SortedSet<string> sortedSet = new SortedSet<string>(gameFonts, StringComparer.Ordinal);
		foreach (FontChoice choice in choices)
		{
			if (!string.IsNullOrEmpty(choice.Target))
			{
				sortedSet.Add(choice.Target);
			}
		}
		List<FontSlot> list = new List<FontSlot>();
		foreach (string target in sortedSet)
		{
			FontSlot fontSlot = new FontSlot
			{
				Target = target,
				Label = GameFonts.Label(target),
				DefaultName = "Vanilla"
			};
			fontSlot.AddOns.AddRange(choices.Where((FontChoice c) => c.Target == target));
			fontSlot.Options.Add(FontOption.VanillaOption);
			foreach (FontChoice item in choices.Where((FontChoice c) => c.Target != target))
			{
				fontSlot.Options.Add(new FontOption
				{
					Kind = OptionKind.Replace,
					Name = "Replace: " + item.Name,
					Choice = item
				});
			}
			foreach (string item2 in gameFonts.Where((string g) => g != target))
			{
				fontSlot.Options.Add(new FontOption
				{
					Kind = OptionKind.Replace,
					Name = "Replace: " + GameFonts.Display(item2) + " (game)",
					GameFont = item2
				});
			}
			list.Add(fontSlot);
		}
		return list.OrderBy((FontSlot s) => GameFonts.Order(s.Target)).ThenBy<FontSlot, string>((FontSlot s) => s.Label, StringComparer.OrdinalIgnoreCase).ToList();
	}

	public override void OnSceneWasLoaded(int buildIndex, string sceneName)
	{
		_applyRequested = true;
	}

	public override void OnUpdate()
	{
		if (_applyRequested || (_pending && Time.unscaledTime >= _nextTry))
		{
			Apply();
		}
		_patcher.FlushLog();
		if (_rebuildRequested)
		{
			_rebuildRequested = false;
			((MelonBase)this).LoggerInstance.Msg("new game font seen; settings rows updated");
			Rebuild();
		}
	}

	private void Apply()
	{
		_applyRequested = false;
		_nextTry = Time.unscaledTime + 2f;
		_pending = _patcher.Apply(_slots, _settings.Selected);
	}
}
internal sealed class GameFonts
{
	private static readonly string[] FoundInGameData = new string[11]
	{
		"LiberationSans SDF", "LiberationSans SDF - Fallback", "Lacquer-Regular SDF", "Nope 8p SDF", "NotoSansJP-SemiBold SDF", "NotoSansSC-SemiBold SDF", "NotoSansTC-SemiBold SDF", "PasseroOne-Regular SDF", "Roboto-Medium SDF", "RulerGold SDF",
		"ZCOOLKuaiLe-Regular SDF"
	};

	private static readonly Dictionary<string, string> Labels = new Dictionary<string, string>
	{
		["PasseroOne-Regular SDF"] = "Menu font (Passero One)",
		["ZCOOLKuaiLe-Regular SDF"] = "In-game UI (ZCOOL KuaiLe)",
		["RulerGold SDF"] = "Lift displays (Ruler Gold)",
		["Lacquer-Regular SDF"] = "Painted signs (Lacquer)",
		["Nope 8p SDF"] = "Price tags (Nope 8p)",
		["Roboto-Medium SDF"] = "Small labels (Roboto)",
		["LiberationSans SDF"] = "Mod settings panel (Liberation Sans)"
	};

	private static readonly Dictionary<string, string> Uses = new Dictionary<string, string>
	{
		["PasseroOne-Regular SDF"] = "Main menu, game settings, intro, news",
		["ZCOOLKuaiLe-Regular SDF"] = "HUD, item names and descriptions, prompts, chat, loading screen",
		["RulerGold SDF"] = "Bucket lift floor and time displays, lobby loading text",
		["Lacquer-Regular SDF"] = "Painted tutorial signs in the tavern",
		["Nope 8p SDF"] = "Shop price tags, gambling stones",
		["Roboto-Medium SDF"] = "Version label, a few input fields",
		["LiberationSans SDF"] = "POG Config's MOD SETTINGS panel",
		["LiberationSans SDF - Fallback"] = "Backup letters for other fonts",
		["NotoSansJP-SemiBold SDF"] = "Japanese letters",
		["NotoSansSC-SemiBold SDF"] = "Simplified Chinese letters",
		["NotoSansTC-SemiBold SDF"] = "Traditional Chinese letters"
	};

	private readonly string _file;

	private readonly SortedSet<string> _names = new SortedSet<string>(StringComparer.Ordinal);

	public IReadOnlyCollection<string> Names => _names;

	public static int Order(string target)
	{
		int num = 0;
		foreach (string key in Labels.Keys)
		{
			if (key == target)
			{
				return num;
			}
			num++;
		}
		return 1000;
	}

	public static string Use(string target)
	{
		if (!Uses.TryGetValue(target, out var value))
		{
			return null;
		}
		return value;
	}

	public GameFonts(string file, Action<string> warn)
	{
		_file = file;
		string[] foundInGameData = FoundInGameData;
		foreach (string item in foundInGameData)
		{
			_names.Add(item);
		}
		try
		{
			if (!File.Exists(file))
			{
				return;
			}
			foundInGameData = File.ReadAllLines(file);
			foreach (string text in foundInGameData)
			{
				if (!string.IsNullOrWhiteSpace(text))
				{
					_names.Add(text.Trim());
				}
			}
		}
		catch (Exception ex)
		{
			warn("could not read " + file + ": " + ex.Message);
		}
	}

	public bool Add(string name)
	{
		if (!_names.Add(name))
		{
			return false;
		}
		try
		{
			File.WriteAllLines(_file, _names.Where((string n) => !FoundInGameData.Contains(n)));
		}
		catch
		{
		}
		return true;
	}

	public static string Label(string target)
	{
		if (!Labels.TryGetValue(target, out var value))
		{
			return Display(target);
		}
		return value;
	}

	public static string Display(string target)
	{
		return target.Replace(" SDF", "");
	}
}