Decompiled source of MochiFlowMods v1.0.0

BepInEx/plugins/MochiFlowMods/MochiFlowMods.dll

Decompiled 3 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using Assets.Scripts.UI;
using Assets.Scripts.UI.Menu.Windows;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("MochiFlowMods")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MochiFlowMods")]
[assembly: AssemblyTitle("MochiFlowMods")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte flag)
		{
			NullableFlags = new byte[1] { flag };
		}

		public NullableAttribute(byte[] flags)
		{
			NullableFlags = flags;
		}
	}
}
namespace MochiFlowMods
{
	internal sealed class ChoiceBinding
	{
		internal static readonly Dictionary<int, ChoiceBinding> Rows = new Dictionary<int, ChoiceBinding>();

		private readonly EnumSetting row;

		private readonly ChoiceSetting choice;

		internal ChoiceBinding(EnumSetting row, ChoiceSetting choice)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			this.row = row;
			this.choice = choice;
			Rows.Add(((Object)row).GetInstanceID(), this);
			((BetterSetting)row)._settingName = choice.ModId + "." + choice.Id;
			((BetterSetting)row).description = choice.Description;
			((BetterSetting)row).options = new Il2CppStringArray(choice.Options);
			GameObject disabledOverlay = ((BetterSetting)row).disabledOverlay;
			if (disabledOverlay != null)
			{
				disabledOverlay.SetActive(false);
			}
			Render();
		}

		internal static bool TryGet(BetterSetting row, out ChoiceBinding binding)
		{
			return Rows.TryGetValue(((Object)row).GetInstanceID(), out binding);
		}

		internal void Render()
		{
			int index = choice.Index;
			((BetterSetting)row)._settingValue = ((Int32)(ref Unsafe.As<int, Int32>(ref index))).BoxIl2CppObject();
			((BetterSetting)row).value = index;
			((TMP_Text)((BetterSetting)row).settingName).text = choice.Label;
			string text = string.Join("  ", from i in Enumerable.Range(0, choice.Options.Length)
				select (i != index) ? "<sprite name=CircleHollow>" : "<sprite name=CircleFilled>");
			((TMP_Text)row.valueText).text = choice.Options[index] + "\n<size=45%>" + text + "</size>";
		}

		internal void Adjust(int direction)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			int num = Math.Clamp(choice.Index + Math.Sign(direction), 0, choice.Options.Length - 1);
			if (num != choice.Index)
			{
				try
				{
					choice.Write(num);
				}
				catch (Exception ex)
				{
					ManualLogSource log = ((BasePlugin)HubPlugin.Instance).Log;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(18, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not save ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(choice.ModId);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("/");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(choice.Id);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					log.LogError(val);
				}
			}
			Render();
		}
	}
	[HarmonyPatch]
	internal static class ChoiceRefreshPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			string[] array = new string[5] { "Start", "RefreshLanguage", "UpdateValue", "CheckVisibility", "SaveValue" };
			foreach (string text in array)
			{
				yield return AccessTools.Method(typeof(BetterSetting), text, (Type[])null, (Type[])null);
			}
			yield return AccessTools.Method(typeof(EnumSetting), "ShowValue", (Type[])null, (Type[])null);
		}

		private static bool Prefix(BetterSetting __instance)
		{
			if (!ChoiceBinding.TryGet(__instance, out ChoiceBinding binding))
			{
				return true;
			}
			binding.Render();
			return false;
		}
	}
	[HarmonyPatch(typeof(EnumSetting), "UpdateValue")]
	internal static class ChoiceArrowPatch
	{
		private static bool Prefix(EnumSetting __instance, int dir)
		{
			if (!ChoiceBinding.TryGet((BetterSetting)(object)__instance, out ChoiceBinding binding))
			{
				return true;
			}
			binding.Adjust(dir);
			return false;
		}
	}
	[HarmonyPatch(typeof(EnumSetting), "ControllerInputDir")]
	internal static class ChoiceControllerPatch
	{
		private static bool Prefix(EnumSetting __instance, int dir)
		{
			if (!ChoiceBinding.TryGet((BetterSetting)(object)__instance, out ChoiceBinding binding))
			{
				return true;
			}
			binding.Adjust(dir);
			return false;
		}
	}
	[HarmonyPatch(typeof(BetterSetting), "OnDestroy")]
	internal static class ChoiceDestroyPatch
	{
		private static void Prefix(BetterSetting __instance)
		{
			ChoiceBinding.Rows.Remove(((Object)__instance).GetInstanceID());
		}
	}
	[BepInPlugin("mochiflow.mods", "MochiFlow Mods", "1.0.0")]
	public sealed class HubPlugin : BasePlugin
	{
		public const string Id = "mochiflow.mods";

		public const string Version = "1.0.0";

		internal static HubPlugin Instance { get; private set; }

		public override void Load()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			Instance = this;
			new Harmony("mochiflow.mods").PatchAll(typeof(HubPlugin).Assembly);
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(44, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("MochiFlow Mods ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.0.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": shared settings tab loaded.");
			}
			log.LogInfo(val);
		}
	}
	public static class SettingsRegistry
	{
		private static readonly List<ChoiceSetting> Registered = new List<ChoiceSetting>();

		internal static IReadOnlyList<ChoiceSetting> Choices => Registered;

		internal static int Revision { get; private set; }

		public static void RegisterChoice(string modId, string sectionTitle, string settingId, string label, string description, string[] options, Func<int> readIndex, Action<int> writeIndex)
		{
			if (string.IsNullOrWhiteSpace(modId) || string.IsNullOrWhiteSpace(sectionTitle) || string.IsNullOrWhiteSpace(settingId) || string.IsNullOrWhiteSpace(label))
			{
				throw new ArgumentException("A mod ID, section title, setting ID, and label are required.");
			}
			if (options == null || options.Length < 2 || options.Any(string.IsNullOrWhiteSpace))
			{
				throw new ArgumentException("A choice setting needs at least two named options.", "options");
			}
			ArgumentNullException.ThrowIfNull(readIndex, "readIndex");
			ArgumentNullException.ThrowIfNull(writeIndex, "writeIndex");
			if (Registered.Any((ChoiceSetting c) => c.ModId == modId && c.Id == settingId))
			{
				throw new InvalidOperationException($"Setting {modId}/{settingId} is already registered.");
			}
			Registered.Add(new ChoiceSetting(modId, sectionTitle, settingId, label, description ?? "", (string[])options.Clone(), readIndex, writeIndex));
			Revision++;
		}

		public static void RegisterToggle(string modId, string sectionTitle, string settingId, string label, string description, Func<bool> readValue, Action<bool> writeValue)
		{
			RegisterChoice(modId, sectionTitle, settingId, label, description, new string[2] { "Off", "On" }, () => readValue() ? 1 : 0, delegate(int index)
			{
				writeValue(index == 1);
			});
		}

		public static void UnregisterMod(string modId)
		{
			if (Registered.RemoveAll((ChoiceSetting c) => c.ModId == modId) > 0)
			{
				Revision++;
			}
		}
	}
	internal sealed record ChoiceSetting(string ModId, string Section, string Id, string Label, string Description, string[] Options, Func<int> Read, Action<int> Write)
	{
		internal int Index => Math.Clamp(Read(), 0, Options.Length - 1);

		private bool PrintMembers(StringBuilder builder)
		{
			RuntimeHelpers.EnsureSufficientExecutionStack();
			builder.Append("ModId = ");
			builder.Append((object?)ModId);
			builder.Append(", Section = ");
			builder.Append((object?)Section);
			builder.Append(", Id = ");
			builder.Append((object?)Id);
			builder.Append(", Label = ");
			builder.Append((object?)Label);
			builder.Append(", Description = ");
			builder.Append((object?)Description);
			builder.Append(", Options = ");
			builder.Append(Options);
			builder.Append(", Read = ");
			builder.Append(Read);
			builder.Append(", Write = ");
			builder.Append(Write);
			return true;
		}
	}
	internal sealed class SettingsUi
	{
		private static readonly Dictionary<int, SettingsUi> Screens = new Dictionary<int, SettingsUi>();

		private readonly Settings settings;

		private readonly GameObject panel;

		private readonly RectTransform content;

		private readonly MyButtonTabs tab;

		private readonly List<int> rowIds = new List<int>();

		private int revision = -1;

		private UnityAction? selectAction;

		internal static void Ensure(Settings settings)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			if ((Object)(object)settings.gameContent == (Object)null || (Object)(object)settings.enumPrefab == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)settings).GetInstanceID();
			if (!Screens.TryGetValue(instanceID, out SettingsUi value))
			{
				try
				{
					value = new SettingsUi(settings);
					Screens.Add(instanceID, value);
				}
				catch (Exception ex)
				{
					ManualLogSource log = ((BasePlugin)HubPlugin.Instance).Log;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(41, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not build MochiFlow Mods settings: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					log.LogError(val);
					return;
				}
			}
			value.Refresh();
		}

		internal static void Forget(Settings settings)
		{
			if (Screens.Remove(((Object)settings).GetInstanceID(), out SettingsUi value))
			{
				value.ReleaseBindings();
			}
		}

		private SettingsUi(Settings settings)
		{
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			this.settings = settings;
			MyButtonTabs val = ((IEnumerable<MyButtonTabs>)((Component)settings).GetComponentsInChildren<MyButtonTabs>(true)).First((MyButtonTabs t) => (Object)(object)t.associatedContent != (Object)null && settings.otherContent.IsChildOf(t.associatedContent.transform));
			panel = Object.Instantiate<GameObject>(val.associatedContent, val.associatedContent.transform.parent);
			((Object)panel).name = "MochiFlowModsPanel";
			panel.SetActive(false);
			ScrollRect componentInChildren = panel.GetComponentInChildren<ScrollRect>(true);
			componentInChildren.vertical = true;
			componentInChildren.horizontal = false;
			content = componentInChildren.content;
			ClearContent();
			GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, ((Component)val).transform.parent);
			((Object)val2).name = "B_MochiFlowMods";
			tab = val2.GetComponent<MyButtonTabs>();
			tab.selected = false;
			tab.associatedContent = panel;
			val2.GetComponentInChildren<TMP_Text>(true).text = "MochiFlow Mods";
			((MyButton)tab).button.onClick = new ButtonClickedEvent();
			ButtonNavigationSelectionOnly navigation = ((Component)val).GetComponentInParent<ButtonNavigationSelectionOnly>();
			if (navigation.buttons != null)
			{
				MyButtonTabs[] array = ((IEnumerable<MyButtonTabs>)navigation.buttons).ToArray();
				int index = array.Length;
				navigation.buttons = new Il2CppReferenceArray<MyButtonTabs>(array.Append(tab).ToArray());
				selectAction = UnityAction.op_Implicit((Action)delegate
				{
					navigation.ButtonPressed(index, true);
				});
				((UnityEvent)((MyButton)tab).button.onClick).AddListener(selectAction);
			}
			((BasePlugin)HubPlugin.Instance).Log.LogInfo((object)"Added the MochiFlow Mods settings tab.");
		}

		private void ClearContent()
		{
			ReleaseBindings();
			for (int num = ((Transform)content).childCount - 1; num >= 0; num--)
			{
				Object.DestroyImmediate((Object)(object)((Component)((Transform)content).GetChild(num)).gameObject);
			}
		}

		private void ReleaseBindings()
		{
			foreach (int rowId in rowIds)
			{
				ChoiceBinding.Rows.Remove(rowId);
			}
			rowIds.Clear();
		}

		private void Refresh()
		{
			if (revision != SettingsRegistry.Revision)
			{
				ClearContent();
				if (SettingsRegistry.Choices.Count == 0)
				{
					AddText("MochiFlow Mods", header: true);
					AddText("Settings from installed MochiFlow mods appear here.", header: false);
				}
				foreach (IGrouping<(string, string), ChoiceSetting> item in from c in SettingsRegistry.Choices
					group c by (ModId: c.ModId, Section: c.Section))
				{
					AddText(item.Key.Item2, header: true);
					foreach (ChoiceSetting item2 in item)
					{
						GameObject obj = Object.Instantiate<GameObject>(settings.enumPrefab, (Transform)(object)content);
						((Object)obj).name = "MochiFlowSetting_" + item2.ModId + "_" + item2.Id;
						EnumSetting component = obj.GetComponent<EnumSetting>();
						((BetterSetting)component).settings = settings;
						new ChoiceBinding(component, item2);
						rowIds.Add(((Object)component).GetInstanceID());
						if (!string.IsNullOrWhiteSpace(item2.Description))
						{
							AddText(item2.Description, header: false);
						}
					}
				}
				revision = SettingsRegistry.Revision;
			}
			foreach (EnumSetting componentsInChild in ((Component)content).GetComponentsInChildren<EnumSetting>(true))
			{
				if (ChoiceBinding.TryGet((BetterSetting)(object)componentsInChild, out ChoiceBinding binding))
				{
					binding.Render();
				}
			}
			UiUtility.RebuildUi(((Component)settings).transform);
			TabsExplicitNavigation settingsNav = settings.settingsNav;
			if (settingsNav != null)
			{
				settingsNav.Refresh();
			}
			Window settingsWindow = settings.settingsWindow;
			if (settingsWindow != null)
			{
				settingsWindow.FindAllButtonsInWindow();
			}
		}

		private void AddText(string value, bool header)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(settings.headerPrefab, (Transform)(object)content);
			((Object)val).name = (header ? "MochiFlowSection" : "MochiFlowDescription");
			SettingsHeaderMonoObject component = val.GetComponent<SettingsHeaderMonoObject>();
			if ((Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			TMP_Text componentInChildren = val.GetComponentInChildren<TMP_Text>(true);
			componentInChildren.text = value;
			if (!header)
			{
				componentInChildren.fontSize = 23f;
				((Graphic)componentInChildren).color = new Color(0.78f, 0.85f, 0.85f, 1f);
				LayoutElement obj = val.GetComponent<LayoutElement>() ?? val.AddComponent<LayoutElement>();
				obj.minHeight = 70f;
				obj.preferredHeight = 70f;
			}
		}
	}
	[HarmonyPatch(typeof(Settings), "UpdateSettings")]
	internal static class SettingsBuildPatch
	{
		private static void Postfix(Settings __instance)
		{
			SettingsUi.Ensure(__instance);
		}
	}
	[HarmonyPatch(typeof(Settings), "OnEnable")]
	internal static class SettingsOpenPatch
	{
		private static void Postfix(Settings __instance)
		{
			SettingsUi.Ensure(__instance);
		}
	}
	[HarmonyPatch(typeof(Settings), "OnDestroy")]
	internal static class SettingsClosePatch
	{
		private static void Prefix(Settings __instance)
		{
			SettingsUi.Forget(__instance);
		}
	}
}