Decompiled source of Custom Titles v1.0.1

CustomTitles.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BrigadeModMenu;
using CustomTitles;
using HarmonyLib;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Localization.Components;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(CustomTitlesMod), "Custom Titles", "1.0.1", "Custom Titles", null)]
[assembly: MelonGame("BoltBlasterGames", "TheSpellBrigade")]
[assembly: MelonOptionalDependencies(new string[] { "BrigadeModMenu" })]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("CustomTitles")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("CustomTitles")]
[assembly: AssemblyTitle("CustomTitles")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BrigadeModMenu
{
	public static class ModMenuCompat
	{
		public static Page Entry(this Page page, MelonPreferences_Entry entry, Func<string> label = null)
		{
			if (entry != null)
			{
				return page.Entry(entry.Raw, label ?? ((Func<string>)(() => entry.DisplayName)));
			}
			return page;
		}

		public static Page Category(this Page page, MelonPreferences_Category category)
		{
			if (category == null)
			{
				return page;
			}
			Menu.HideCategory(category.Identifier);
			foreach (MelonPreferences_Entry e in category.Entries)
			{
				if (e != null && !e.IsHidden)
				{
					page.Entry(e.Raw, (Func<string>)(() => e.DisplayName));
				}
			}
			return page;
		}
	}
}
namespace CustomTitles
{
	public class CustomTitlesMod : MelonMod
	{
		internal const int MaxLength = 40;

		private const char Separator = '|';

		internal static MelonLogger.Instance Log;

		private static MelonPreferences_Category _category;

		internal static MelonPreferences_Entry<bool> ShowOthers;

		private static MelonPreferences_Entry<string> TitlesEntry;

		private static MelonPreferences_Entry<string> ActiveEntry;

		private static readonly Dictionary<IntPtr, (PlayerTitleDisplay display, ulong clientId, bool local)> Shown = new Dictionary<IntPtr, (PlayerTitleDisplay, ulong, bool)>();

		private static readonly HashSet<IntPtr> HookedCode = new HashSet<IntPtr>();

		private const string WithoutModName = "CustomTitles_WithoutMod";

		private static TitlePanelPlayerInfoDisplay _ownPanel;

		private static readonly HashSet<IntPtr> ForcedVisible = new HashSet<IntPtr>();

		internal static List<string> Titles
		{
			get
			{
				List<string> list = new List<string>();
				string[] array = (TitlesEntry.Value ?? "").Split('|');
				foreach (string text in array)
				{
					if (!string.IsNullOrWhiteSpace(text) && !list.Contains(text.Trim()))
					{
						list.Add(text.Trim());
					}
				}
				return list;
			}
		}

		internal static string Active => ActiveEntry.Value ?? "";

		internal static event Action Changed;

		internal static event Action ListChanged;

		public override void OnInitializeMelon()
		{
			Log = base.LoggerInstance;
			_category = MelonPreferences.CreateCategory("CustomTitles", "Custom Titles");
			ShowOthers = _category.CreateEntry("ShowOthers", default_value: true, "Show Others' Custom Titles", "Show custom titles of other players who have this mod");
			TitlesEntry = _category.CreateEntry("Titles", "", "Titles", "Your custom titles, separated by |", is_hidden: true);
			ActiveEntry = _category.CreateEntry("Active", "", "Active Title", "The custom title you're wearing (empty = the game's title)", is_hidden: true);
			_category.SaveToFile(printmsg: false);
			ShowOthers.OnEntryValueChanged.Subscribe(delegate
			{
				RefreshShown();
			});
			bool flag = true;
			flag &= Patch(typeof(PlayerSeatPlayerDetailsPanel), "Show", "SeatShowPostfix");
			flag &= Patch(typeof(TitlePanelPlayerInfoDisplay), "Refresh", "OwnPanelPostfix");
			flag &= Patch(typeof(TitlePanelPlayerInfoDisplay), "OnPlayerTitleIdChanged", "OwnPanelPostfix");
			flag &= Patch(typeof(TitleSelector), "UpdatePlayerTitle", "GameTitlePickedPostfix");
			flag &= Patch(typeof(TitleSelector), "Configure", "ConfigurePostfix", typeof(TitlesTab));
			flag &= Patch(typeof(TitleSelector), "MakeInitialSelection", "MakeInitialSelectionPostfix", typeof(TitlesTab), "MakeInitialSelectionPrefix");
			flag &= Patch(typeof(TitleSelector), "OnSelected", null, typeof(TitlesTab), "OnSelectedPrefix");
			ListChanged += TitlesTab.Refresh;
			TitleNet.Initialize();
			if (Array.Exists(AppDomain.CurrentDomain.GetAssemblies(), (Assembly a) => a.GetName().Name == "BrigadeModMenu"))
			{
				try
				{
					RegisterMenu();
				}
				catch (Exception ex)
				{
					Log.Warning("Mod Menu page: " + ex.Message);
				}
			}
			if (flag)
			{
				Log.Msg((Active.Length > 0) ? $"ready — wearing \"{Active}\" ({Titles.Count} saved)" : $"ready — {Titles.Count} custom titles saved");
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void RegisterMenu()
		{
			MenuPage.Register();
		}

		private bool Patch(Type type, string method, string postfix, Type patchClass = null, string prefix = null)
		{
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if ((object)patchClass == null)
			{
				patchClass = typeof(CustomTitlesMod);
			}
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.Name + "." + method + " not found");
				IntPtr intPtr = NativeCode(methodInfo);
				if (intPtr != IntPtr.Zero && !HookedCode.Add(intPtr))
				{
					Log.Warning($"skipped {type.Name}.{method}: same native code as a method already hooked");
					return true;
				}
				base.HarmonyInstance.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(patchClass, prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(patchClass, postfix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				return true;
			}
			catch (Exception ex)
			{
				Log.Error($"failed to hook {type.Name}.{method}: {ex.Message}");
				return false;
			}
		}

		private static IntPtr NativeCode(MethodBase method)
		{
			try
			{
				if (!(Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod(method)?.GetValue(null) is IntPtr intPtr) || intPtr == IntPtr.Zero)
				{
					return IntPtr.Zero;
				}
				return Marshal.ReadIntPtr(intPtr);
			}
			catch
			{
				return IntPtr.Zero;
			}
		}

		public override void OnUpdate()
		{
			TitleNet.Tick();
			MenuPage.Tick();
		}

		internal static string Clean(string title)
		{
			title = (title ?? "").Replace('|'.ToString(), "").Replace("\n", " ").Replace("\r", "")
				.Replace("\t", " ")
				.Trim();
			title = title.Replace("<", "").Replace(">", "");
			if (title.Length <= 40)
			{
				return title;
			}
			return title.Substring(0, 40);
		}

		internal static bool Add(string title)
		{
			title = Clean(title);
			if (title.Length == 0)
			{
				return false;
			}
			List<string> titles = Titles;
			if (!titles.Contains(title))
			{
				titles.Add(title);
			}
			TitlesEntry.Value = string.Join('|', titles);
			Save();
			CustomTitlesMod.ListChanged?.Invoke();
			CustomTitlesMod.Changed?.Invoke();
			return true;
		}

		internal static void Delete(string title)
		{
			List<string> titles = Titles;
			titles.Remove(title);
			TitlesEntry.Value = string.Join('|', titles);
			if (Active == title)
			{
				SetActive("");
			}
			else
			{
				Save();
				CustomTitlesMod.Changed?.Invoke();
			}
			CustomTitlesMod.ListChanged?.Invoke();
		}

		internal static void SetActive(string title)
		{
			ActiveEntry.Value = Clean(title);
			Save();
			TitleNet.SendOwnTitle();
			RefreshShown();
			CustomTitlesMod.Changed?.Invoke();
		}

		private static void Save()
		{
			_category.SaveToFile(printmsg: false);
		}

		private static void SeatShowPostfix(PlayerSeatPlayerDetailsPanel __instance, PlayerSeatInfo info)
		{
			try
			{
				PlayerSeatPlayerDetailsPanel obj = ((__instance != null) ? ((Il2CppObjectBase)__instance).TryCast<PlayerSeatPlayerDetailsPanel>() : null);
				PlayerTitleDisplay val = ((obj != null) ? obj.playerTitleDisplay : null);
				if (!((Object)(object)val == (Object)null) && info != null)
				{
					ulong clientId = info.ClientId;
					bool flag = IsLocalClient(clientId);
					Shown[((Il2CppObjectBase)val).Pointer] = (val, clientId, flag);
					Apply(val, TitleFor(clientId, flag));
				}
			}
			catch (Exception ex)
			{
				Log.Warning("seat title: " + ex.Message);
			}
		}

		private static void OwnPanelPostfix(TitlePanelPlayerInfoDisplay __instance)
		{
			try
			{
				TitlePanelPlayerInfoDisplay val = ((__instance != null) ? ((Il2CppObjectBase)__instance).TryCast<TitlePanelPlayerInfoDisplay>() : null);
				PlayerTitleDisplay val2 = ((val != null) ? val.playerTitleDisplay : null);
				if (!((Object)(object)val2 == (Object)null))
				{
					Shown[((Il2CppObjectBase)val2).Pointer] = (val2, 0uL, true);
					Apply(val2, Active);
					_ownPanel = val;
					UpdateWithoutModLine();
				}
			}
			catch (Exception ex)
			{
				Log.Warning("title panel: " + ex.Message);
			}
		}

		private static void GameTitlePickedPostfix()
		{
			if (Active.Length > 0)
			{
				SetActive("");
			}
			else
			{
				UpdateWithoutModLine();
			}
		}

		internal static PlayerTitleId? GameTitleId()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				LocalPlayer instance = SingletonPersistent<LocalPlayer>.Instance;
				return ((Object)(object)instance != (Object)null) ? new PlayerTitleId?(instance.GetPlayerTitleId()) : ((PlayerTitleId?)null);
			}
			catch
			{
				return null;
			}
		}

		private static string GameTitleName()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			PlayerTitleId? val = GameTitleId();
			if (!val.HasValue)
			{
				return "";
			}
			List<PlayerTitleConfig> playerTitles = PlayerTitleRepository.PlayerTitles;
			int num = 0;
			while (playerTitles != null && num < playerTitles.Count)
			{
				PlayerTitleConfig val2 = playerTitles[num];
				if ((Object)(object)val2 != (Object)null && val2.PlayerTitleId == val.Value)
				{
					try
					{
						return TitleSelector.TranslateTitle(val2) ?? "";
					}
					catch
					{
						return ((Object)val2).name;
					}
				}
				num++;
			}
			return "";
		}

		internal static void UpdateWithoutModLine()
		{
			try
			{
				if ((Object)(object)_ownPanel == (Object)null || ((Il2CppObjectBase)_ownPanel).WasCollected)
				{
					_ownPanel = null;
					return;
				}
				PlayerTitleDisplay playerTitleDisplay = _ownPanel.playerTitleDisplay;
				object obj;
				if (playerTitleDisplay == null)
				{
					obj = null;
				}
				else
				{
					LocalizeStringEvent playerTitle = playerTitleDisplay.playerTitle;
					obj = ((playerTitle != null) ? ((Component)playerTitle).GetComponent<TMP_Text>() : null);
				}
				TMP_Text val = (TMP_Text)obj;
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				Transform val2 = val.transform.Find("CustomTitles_WithoutMod");
				TMP_Text val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<TMP_Text>() : null);
				bool flag = Active.Length > 0;
				if ((Object)(object)val3 == (Object)null)
				{
					if (!flag)
					{
						return;
					}
					val3 = CreateWithoutModLine(val);
				}
				if (flag)
				{
					string text = GameTitleName();
					val3.text = "Without the mod: " + ((text.Length > 0) ? text : "no title");
				}
				if (((Component)val3).gameObject.activeSelf != flag)
				{
					((Component)val3).gameObject.SetActive(flag);
				}
			}
			catch (Exception ex)
			{
				Log.Warning("without-mod line: " + ex.Message);
			}
		}

		private static TMP_Text CreateWithoutModLine(TMP_Text title)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("CustomTitles_WithoutMod");
			RectTransform obj = val.AddComponent<RectTransform>();
			((Transform)obj).SetParent(title.transform, false);
			obj.anchorMin = new Vector2(0f, 0f);
			obj.anchorMax = new Vector2(1f, 0f);
			obj.pivot = new Vector2(0.5f, 1f);
			obj.anchoredPosition = new Vector2(0f, -2f);
			obj.sizeDelta = new Vector2(200f, title.fontSize * 0.8f);
			TextMeshProUGUI obj2 = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj2).font = title.font;
			((TMP_Text)obj2).fontSharedMaterial = title.fontSharedMaterial;
			((TMP_Text)obj2).fontSize = Mathf.Max(12f, title.fontSize * 0.6f);
			((TMP_Text)obj2).fontStyle = title.fontStyle;
			Color color = ((Graphic)title).color;
			((Graphic)obj2).color = new Color(color.r, color.g, color.b, color.a * 0.7f);
			((TMP_Text)obj2).alignment = (TextAlignmentOptions)258;
			((TMP_Text)obj2).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)obj2).overflowMode = (TextOverflowModes)0;
			((Graphic)obj2).raycastTarget = false;
			return (TMP_Text)(object)obj2;
		}

		private static bool IsLocalClient(ulong clientId)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.IsListening)
			{
				return singleton.LocalClientId == clientId;
			}
			return true;
		}

		private static string TitleFor(ulong clientId, bool local)
		{
			if (local)
			{
				return Active;
			}
			if (!ShowOthers.Value)
			{
				return "";
			}
			return TitleNet.TitleOf(clientId);
		}

		internal static void RefreshShown()
		{
			foreach (var (key, tuple2) in new List<KeyValuePair<IntPtr, (PlayerTitleDisplay, ulong, bool)>>(Shown))
			{
				if ((Object)(object)tuple2.Item1 == (Object)null)
				{
					Shown.Remove(key);
					continue;
				}
				try
				{
					bool local = tuple2.Item3 || IsLocalClient(tuple2.Item2);
					Apply(tuple2.Item1, TitleFor(tuple2.Item2, local));
				}
				catch
				{
					Shown.Remove(key);
				}
			}
			UpdateWithoutModLine();
		}

		private static void Apply(PlayerTitleDisplay display, string custom)
		{
			LocalizeStringEvent playerTitle = display.playerTitle;
			if ((Object)(object)playerTitle == (Object)null)
			{
				return;
			}
			TMP_Text component = ((Component)playerTitle).GetComponent<TMP_Text>();
			if (!string.IsNullOrEmpty(custom))
			{
				((Behaviour)playerTitle).enabled = false;
				if ((Object)(object)component != (Object)null)
				{
					component.text = custom;
				}
				if (!((Component)display).gameObject.activeSelf)
				{
					ForcedVisible.Add(((Il2CppObjectBase)display).Pointer);
				}
				((Component)display).gameObject.SetActive(true);
				((Component)playerTitle).gameObject.SetActive(true);
			}
			else if (!((Behaviour)playerTitle).enabled)
			{
				((Behaviour)playerTitle).enabled = true;
				playerTitle.RefreshString();
				if (ForcedVisible.Remove(((Il2CppObjectBase)display).Pointer))
				{
					((Component)display).gameObject.SetActive(false);
				}
			}
		}
	}
	internal static class MenuPage
	{
		private static readonly Color Gold = new Color(0.95f, 0.76f, 0.31f);

		private static bool _registered;

		private static TMP_InputField _input;

		private static TMP_Text _font;

		private static readonly List<InputAction> Disabled = new List<InputAction>();

		private static bool _capturing;

		private static readonly List<TMP_Text> Ours = new List<TMP_Text>();

		private static Transform _container;

		private static readonly string[] PointerActions = new string[7] { "Point", "Click", "RightClick", "MiddleClick", "ScrollWheel", "TrackedDevicePosition", "TrackedDeviceOrientation" };

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void Register()
		{
			_registered = true;
			Menu.AddPage("CustomTitles", "Custom Titles").Note((Func<string>)(() => "Type a new title and press Add — it appears at the end of the Titles tab, where you pick it like any other title.")).Custom(110f, (Func<RectTransform, Selectable>)BuildInput)
				.Header((Func<string>)(() => "Your titles"))
				.List((Func<IList<ListEntry>>)TitleEntries, (Func<string>)(() => "No custom titles yet."))
				.Entry(CustomTitlesMod.ShowOthers)
				.Note((Func<string>)(() => "Players without this mod still see your normal game title — the game only sends built-in titles. Players with the mod see your custom title when the lobby's host has the mod too."));
			CustomTitlesMod.Changed += Refresh;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void Refresh()
		{
			if (_registered)
			{
				Menu.Refresh();
			}
		}

		private static IList<ListEntry> TitleEntries()
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			List<ListEntry> list = new List<ListEntry>();
			foreach (string title in CustomTitlesMod.Titles)
			{
				string t = title;
				list.Add(new ListEntry(t, (t == CustomTitlesMod.Active) ? "wearing" : null, (MenuButton[])(object)new MenuButton[1]
				{
					new MenuButton("Delete", (Action)delegate
					{
						CustomTitlesMod.Delete(t);
					}, false)
				}));
			}
			return list;
		}

		private static Selectable BuildInput(RectTransform row)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Unknown result type (might be due to invalid IL or missing references)
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
			Canvas componentInParent = ((Component)row).GetComponentInParent<Canvas>();
			TMP_Text val = ((componentInParent != null) ? ((Component)componentInParent).GetComponentInChildren<TMP_Text>(true) : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			_container = ((Transform)row).parent;
			RectTransform val2 = NewRect("NewTitle", (Transform)(object)row);
			val2.anchorMin = new Vector2(0f, 0.1f);
			val2.anchorMax = new Vector2(0.78f, 0.9f);
			Vector2 offsetMin = (val2.offsetMax = Vector2.zero);
			val2.offsetMin = offsetMin;
			Image val3 = ((Component)val2).gameObject.AddComponent<Image>();
			((Graphic)val3).color = new Color(0f, 0f, 0f, 0.35f);
			Image val4 = ((Component)NewRect("Line", (Transform)(object)val2)).gameObject.AddComponent<Image>();
			((Graphic)val4).raycastTarget = false;
			((Graphic)val4).rectTransform.anchorMin = Vector2.zero;
			((Graphic)val4).rectTransform.anchorMax = new Vector2(1f, 0f);
			((Graphic)val4).rectTransform.pivot = new Vector2(0.5f, 0f);
			((Graphic)val4).rectTransform.sizeDelta = new Vector2(0f, 3f);
			RectTransform val5 = NewRect("Text Area", (Transform)(object)val2);
			val5.anchorMin = Vector2.zero;
			val5.anchorMax = Vector2.one;
			val5.offsetMin = new Vector2(24f, 6f);
			val5.offsetMax = new Vector2(-24f, -6f);
			((Component)val5).gameObject.AddComponent<RectMask2D>();
			TMP_Text val6 = Text(val, (Transform)(object)val5, "Placeholder");
			val6.text = $"Type a new title (up to {40} letters)";
			((Graphic)val6).color = new Color(1f, 1f, 1f, 0.35f);
			TMP_Text val7 = Text(val, (Transform)(object)val5, "Text");
			((Graphic)val7).color = Color.white;
			TMP_InputField obj = ((Component)val2).gameObject.AddComponent<TMP_InputField>();
			obj.textViewport = val5;
			obj.textComponent = val7;
			obj.placeholder = (Graphic)(object)val6;
			obj.fontAsset = val7.font;
			obj.pointSize = val7.fontSize;
			obj.lineType = (LineType)0;
			Navigation navigation = ((Selectable)obj).navigation;
			navigation.mode = (Mode)0;
			((Selectable)obj).navigation = navigation;
			obj.characterLimit = 40;
			obj.richText = false;
			obj.restoreOriginalTextOnEscape = false;
			obj.caretColor = Gold;
			obj.customCaretColor = true;
			obj.caretWidth = 3;
			obj.selectionColor = new Color(Gold.r, Gold.g, Gold.b, 0.35f);
			((Selectable)obj).targetGraphic = (Graphic)(object)val3;
			((UnityEvent<string>)(object)obj.onSubmit).AddListener(UnityAction<string>.op_Implicit((Action<string>)delegate
			{
				AddTyped();
			}));
			obj.caretBlinkRate = 0.85f;
			((Behaviour)obj).enabled = false;
			((Behaviour)obj).enabled = true;
			_input = obj;
			TMP_Text val8 = Text(val, (Transform)(object)row, "Add");
			val8.text = "Add";
			((Graphic)val8).color = Gold;
			val8.alignment = (TextAlignmentOptions)514;
			((Graphic)val8).raycastTarget = true;
			val8.rectTransform.anchorMin = new Vector2(0.8f, 0f);
			val8.rectTransform.anchorMax = Vector2.one;
			RectTransform rectTransform = val8.rectTransform;
			offsetMin = (val8.rectTransform.offsetMax = Vector2.zero);
			rectTransform.offsetMin = offsetMin;
			Button obj2 = ((Component)val8).gameObject.AddComponent<Button>();
			((Selectable)obj2).transition = (Transition)0;
			Navigation navigation2 = ((Selectable)obj2).navigation;
			navigation2.mode = (Mode)0;
			((Selectable)obj2).navigation = navigation2;
			((UnityEvent)obj2.onClick).AddListener(UnityAction.op_Implicit((Action)AddTyped));
			((Graphic)val4).color = new Color(1f, 1f, 1f, 0.2f);
			return (Selectable)(object)obj;
		}

		private static void AddTyped()
		{
			if (!((Object)(object)_input == (Object)null) && CustomTitlesMod.Add(_input.text))
			{
				_input.text = "";
				_input.DeactivateInputField(false);
				EventSystem current = EventSystem.current;
				if (current != null)
				{
					current.SetSelectedGameObject((GameObject)null);
				}
				Refresh();
			}
		}

		private static TMP_Text Text(TMP_Text template, Transform parent, string name)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(((Component)template).gameObject, parent);
			((Object)val).name = name;
			val.SetActive(true);
			foreach (MonoBehaviour component2 in val.GetComponents<MonoBehaviour>())
			{
				if ((Object)(object)component2 != (Object)null && (Object)(object)((Il2CppObjectBase)component2).TryCast<TMP_Text>() == (Object)null)
				{
					Object.DestroyImmediate((Object)(object)component2);
				}
			}
			for (int num = val.transform.childCount - 1; num >= 0; num--)
			{
				Object.DestroyImmediate((Object)(object)((Component)val.transform.GetChild(num)).gameObject);
			}
			TMP_Text component = val.GetComponent<TMP_Text>();
			component.text = "";
			component.alignment = (TextAlignmentOptions)4097;
			component.textWrappingMode = (TextWrappingModes)0;
			component.enableAutoSizing = false;
			component.fontStyle = (FontStyles)(component.fontStyle & -57);
			((Graphic)component).raycastTarget = false;
			Ours.Add(component);
			RectTransform rectTransform = component.rectTransform;
			rectTransform.anchorMin = Vector2.zero;
			rectTransform.anchorMax = Vector2.one;
			rectTransform.pivot = new Vector2(0f, 0.5f);
			Vector2 offsetMin = (rectTransform.offsetMax = Vector2.zero);
			rectTransform.offsetMin = offsetMin;
			((Transform)rectTransform).localScale = Vector3.one;
			return component;
		}

		internal static Button TextButton(TMP_Text text, Action onClick)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			((Graphic)text).color = Color.white;
			((Graphic)text).raycastTarget = true;
			Button obj = ((Component)text).gameObject.AddComponent<Button>();
			((Selectable)obj).targetGraphic = (Graphic)(object)text;
			((Selectable)obj).transition = (Transition)1;
			ColorBlock colors = ((Selectable)obj).colors;
			((ColorBlock)(ref colors)).normalColor = Gold;
			((ColorBlock)(ref colors)).highlightedColor = Color.white;
			((ColorBlock)(ref colors)).selectedColor = Color.white;
			((ColorBlock)(ref colors)).pressedColor = new Color(0.8f, 0.8f, 0.8f, 1f);
			((ColorBlock)(ref colors)).colorMultiplier = 1f;
			((ColorBlock)(ref colors)).fadeDuration = 0.05f;
			((Selectable)obj).colors = colors;
			((UnityEvent)obj.onClick).AddListener(UnityAction.op_Implicit(onClick));
			return obj;
		}

		private static RectTransform NewRect(string name, Transform parent)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = new GameObject(name).AddComponent<RectTransform>();
			((Transform)obj).SetParent(parent, false);
			return obj;
		}

		internal static void Tick()
		{
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			MatchMenuSize();
			bool flag = false;
			try
			{
				flag = (Object)(object)_input != (Object)null && _input.isFocused;
			}
			catch
			{
				_input = null;
			}
			if (flag && !_capturing)
			{
				BeginCapture();
			}
			else if (!flag && _capturing)
			{
				EndCapture();
			}
			if (flag && (Object)(object)_input != (Object)null)
			{
				Transform obj2 = ((Component)_input).transform.Find("Line");
				Image val = ((obj2 != null) ? ((Component)obj2).GetComponent<Image>() : null);
				if ((Object)(object)val != (Object)null)
				{
					((Graphic)val).color = Gold;
				}
			}
			else if ((Object)(object)_input != (Object)null)
			{
				Transform obj3 = ((Component)_input).transform.Find("Line");
				Image val2 = ((obj3 != null) ? ((Component)obj3).GetComponent<Image>() : null);
				if ((Object)(object)val2 != (Object)null)
				{
					((Graphic)val2).color = new Color(1f, 1f, 1f, 0.2f);
				}
			}
		}

		private static void MatchMenuSize()
		{
			if (Ours.Count == 0)
			{
				return;
			}
			Ours.RemoveAll((TMP_Text t) => (Object)(object)t == (Object)null || ((Il2CppObjectBase)t).WasCollected);
			float num = LabelSize();
			if (num <= 0f)
			{
				return;
			}
			foreach (TMP_Text our in Ours)
			{
				if (Mathf.Abs(our.fontSize - num) > 0.01f)
				{
					our.fontSize = num;
				}
			}
			try
			{
				if ((Object)(object)_input != (Object)null && Mathf.Abs(_input.pointSize - num) > 0.01f)
				{
					_input.pointSize = num;
				}
			}
			catch
			{
				_input = null;
			}
		}

		private static float LabelSize()
		{
			try
			{
				if ((Object)(object)_container == (Object)null || ((Il2CppObjectBase)_container).WasCollected)
				{
					return 0f;
				}
				for (int i = 0; i < _container.childCount; i++)
				{
					Transform child = _container.GetChild(i);
					Selector componentInChildren = ((Component)child).GetComponentInChildren<Selector>(true);
					if ((Object)(object)componentInChildren == (Object)null)
					{
						continue;
					}
					foreach (TMP_Text componentsInChild in ((Component)child).GetComponentsInChildren<TMP_Text>(true))
					{
						if (!componentsInChild.transform.IsChildOf(((Component)componentInChildren).transform) && ((Component)componentsInChild).gameObject.activeSelf)
						{
							return componentsInChild.enableAutoSizing ? componentsInChild.fontSizeMax : componentsInChild.fontSize;
						}
					}
				}
			}
			catch
			{
			}
			return 0f;
		}

		private static void BeginCapture()
		{
			_capturing = true;
			AppDomain.CurrentDomain.SetData("SpellBrigade.Typing", true);
			foreach (InputActionAsset item in Resources.FindObjectsOfTypeAll<InputActionAsset>())
			{
				InputActionMap val = ((item != null) ? item.FindActionMap("UI", false) : null);
				if (val == null || !val.enabled)
				{
					continue;
				}
				ReadOnlyArray<InputAction> actions = val.actions;
				for (int i = 0; i < actions.Count; i++)
				{
					InputAction val2 = actions[i];
					if (val2 != null && val2.enabled && Array.IndexOf(PointerActions, val2.name) < 0)
					{
						val2.Disable();
						Disabled.Add(val2);
					}
				}
			}
		}

		private static void EndCapture()
		{
			_capturing = false;
			AppDomain.CurrentDomain.SetData("SpellBrigade.Typing", false);
			foreach (InputAction item in Disabled)
			{
				try
				{
					if (item != null)
					{
						item.Enable();
					}
				}
				catch
				{
				}
			}
			Disabled.Clear();
		}
	}
	internal static class TitleNet
	{
		private const string SetMessage = "CustomTitles.Set";

		private const string AllMessage = "CustomTitles.All";

		private static readonly Dictionary<ulong, string> Titles = new Dictionary<ulong, string>();

		private static NetworkManager _registeredOn;

		private static IntPtr _messagingPtr;

		private static bool _sentThisConnection;

		private static int _lastClientCount = -1;

		private static float _nextFailRetry;

		private static HandleNamedMessageDelegate _onSet;

		private static HandleNamedMessageDelegate _onAll;

		internal static void Initialize()
		{
			_onSet = DelegateSupport.ConvertDelegate<HandleNamedMessageDelegate>((Delegate)new Action<ulong, FastBufferReader>(OnSet));
			_onAll = DelegateSupport.ConvertDelegate<HandleNamedMessageDelegate>((Delegate)new Action<ulong, FastBufferReader>(OnAll));
		}

		internal static string TitleOf(ulong clientId)
		{
			if (!Titles.TryGetValue(clientId, out var value))
			{
				return "";
			}
			return value;
		}

		internal static void Tick()
		{
			if (Time.unscaledTime < _nextFailRetry)
			{
				return;
			}
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				CustomMessagingManager val = (((Object)(object)singleton != (Object)null && singleton.IsListening) ? singleton.CustomMessagingManager : null);
				if (val == null)
				{
					if ((Object)(object)_registeredOn != (Object)null)
					{
						Titles.Clear();
						_registeredOn = null;
						_messagingPtr = IntPtr.Zero;
						CustomTitlesMod.RefreshShown();
					}
					_sentThisConnection = false;
					_lastClientCount = -1;
					return;
				}
				if ((Object)(object)_registeredOn == (Object)null || ((Il2CppObjectBase)_registeredOn).Pointer != ((Il2CppObjectBase)singleton).Pointer || _messagingPtr != ((Il2CppObjectBase)val).Pointer)
				{
					val.RegisterNamedMessageHandler("CustomTitles.Set", _onSet);
					val.RegisterNamedMessageHandler("CustomTitles.All", _onAll);
					_registeredOn = singleton;
					_messagingPtr = ((Il2CppObjectBase)val).Pointer;
					_sentThisConnection = false;
					_lastClientCount = -1;
					Titles.Clear();
				}
				if (!singleton.IsServer && !singleton.IsConnectedClient)
				{
					_sentThisConnection = false;
					return;
				}
				if (!_sentThisConnection)
				{
					_sentThisConnection = true;
					SendOwnTitle();
				}
				if (singleton.IsServer)
				{
					int num = ConnectedCount(singleton);
					if (num != _lastClientCount)
					{
						_lastClientCount = num;
						Broadcast();
					}
				}
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("title sync: " + ex.Message);
				_nextFailRetry = Time.unscaledTime + 5f;
			}
		}

		private static int ConnectedCount(NetworkManager nm)
		{
			IReadOnlyList<ulong> connectedClientsIds = nm.ConnectedClientsIds;
			if (connectedClientsIds != null)
			{
				return ((Il2CppObjectBase)connectedClientsIds).Cast<IReadOnlyCollection<ulong>>().Count;
			}
			return 0;
		}

		internal static void SendOwnTitle()
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton == (Object)null) && singleton.IsListening && !((Object)(object)_registeredOn == (Object)null))
				{
					if (singleton.IsServer)
					{
						Store(singleton.LocalClientId, CustomTitlesMod.Active);
						Broadcast();
					}
					else
					{
						Send("CustomTitles.Set", NetworkManager.ServerClientId, CustomTitlesMod.Active, toAll: false);
					}
				}
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("send title: " + ex.Message);
			}
		}

		private static void OnSet(ulong sender, FastBufferReader reader)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton == (Object)null) && singleton.IsServer)
				{
					Store(sender, CustomTitlesMod.Clean(ReadString(reader)));
					Broadcast();
				}
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("receive title: " + ex.Message);
			}
		}

		private static void OnAll(ulong sender, FastBufferReader reader)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || singleton.IsServer)
				{
					return;
				}
				Titles.Clear();
				string[] array = ReadString(reader).Split('\n');
				foreach (string text in array)
				{
					int num = text.IndexOf('\t');
					if (num > 0 && ulong.TryParse(text.Substring(0, num), out var result))
					{
						string text2 = CustomTitlesMod.Clean(text.Substring(num + 1));
						if (text2.Length > 0)
						{
							Titles[result] = text2;
						}
					}
				}
				CustomTitlesMod.RefreshShown();
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("receive titles: " + ex.Message);
			}
		}

		private static void Store(ulong clientId, string title)
		{
			if (string.IsNullOrEmpty(title))
			{
				Titles.Remove(clientId);
			}
			else
			{
				Titles[clientId] = title;
			}
			CustomTitlesMod.RefreshShown();
		}

		private static void Broadcast()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			HashSet<ulong> hashSet = new HashSet<ulong>();
			IReadOnlyList<ulong> connectedClientsIds = singleton.ConnectedClientsIds;
			IReadOnlyCollection<ulong> val = ((Il2CppObjectBase)connectedClientsIds).Cast<IReadOnlyCollection<ulong>>();
			for (int i = 0; i < val.Count; i++)
			{
				hashSet.Add(connectedClientsIds[i]);
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (var (num2, value) in new List<KeyValuePair<ulong, string>>(Titles))
			{
				if (!hashSet.Contains(num2))
				{
					Titles.Remove(num2);
				}
				else
				{
					stringBuilder.Append(num2).Append('\t').Append(value)
						.Append('\n');
				}
			}
			Send("CustomTitles.All", 0uL, stringBuilder.ToString(), toAll: true);
		}

		private static void Send(string name, ulong clientId, string text, bool toAll)
		{
			//IL_00b1: 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)
			byte[] bytes = Encoding.UTF8.GetBytes(text ?? "");
			Il2CppStructArray<byte> val = new Il2CppStructArray<byte>((long)(bytes.Length + 4));
			((Il2CppArrayBase<byte>)(object)val)[0] = (byte)bytes.Length;
			((Il2CppArrayBase<byte>)(object)val)[1] = (byte)(bytes.Length >> 8);
			((Il2CppArrayBase<byte>)(object)val)[2] = (byte)(bytes.Length >> 16);
			((Il2CppArrayBase<byte>)(object)val)[3] = (byte)(bytes.Length >> 24);
			for (int i = 0; i < bytes.Length; i++)
			{
				((Il2CppArrayBase<byte>)(object)val)[i + 4] = bytes[i];
			}
			FastBufferWriter val2 = default(FastBufferWriter);
			((FastBufferWriter)(ref val2))..ctor(((Il2CppArrayBase<byte>)(object)val).Length, (Allocator)2, ((Il2CppArrayBase<byte>)(object)val).Length);
			try
			{
				((FastBufferWriter)(ref val2)).WriteBytesSafe(val, ((Il2CppArrayBase<byte>)(object)val).Length, 0);
				CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
				if (toAll)
				{
					customMessagingManager.SendNamedMessageToAll(name, val2, (NetworkDelivery)3);
				}
				else
				{
					customMessagingManager.SendNamedMessage(name, clientId, val2, (NetworkDelivery)3);
				}
			}
			finally
			{
				((FastBufferWriter)(ref val2)).Dispose();
			}
		}

		private static string ReadString(FastBufferReader reader)
		{
			int num = ((FastBufferReader)(ref reader)).Length - ((FastBufferReader)(ref reader)).Position;
			if (num < 4)
			{
				return "";
			}
			Il2CppStructArray<byte> val = new Il2CppStructArray<byte>(4L);
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref val, 4, 0);
			int num2 = ((Il2CppArrayBase<byte>)(object)val)[0] | (((Il2CppArrayBase<byte>)(object)val)[1] << 8) | (((Il2CppArrayBase<byte>)(object)val)[2] << 16) | (((Il2CppArrayBase<byte>)(object)val)[3] << 24);
			if (num2 <= 0 || num2 > num - 4 || num2 > 65536)
			{
				return "";
			}
			Il2CppStructArray<byte> val2 = new Il2CppStructArray<byte>((long)num2);
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref val2, num2, 0);
			byte[] array = new byte[num2];
			for (int i = 0; i < num2; i++)
			{
				array[i] = ((Il2CppArrayBase<byte>)(object)val2)[i];
			}
			return Encoding.UTF8.GetString(array);
		}
	}
	internal static class TitlesTab
	{
		private static readonly Dictionary<IntPtr, string> CustomButtons = new Dictionary<IntPtr, string>();

		private static TitleSelector _selector;

		private static PlayerTitleConfig _placeholder;

		private const int PlaceholderId = 2147418112;

		private static Sprite _defaultIcon;

		internal static void ConfigurePostfix(TitleSelector __instance)
		{
			try
			{
				TitleSelector val = ((__instance != null) ? ((Il2CppObjectBase)__instance).TryCast<TitleSelector>() : null);
				if (!((Object)(object)val == (Object)null))
				{
					_selector = val;
					Fill(val);
				}
			}
			catch (Exception value)
			{
				CustomTitlesMod.Log.Warning($"titles tab: {value}");
			}
		}

		internal static bool OnSelectedPrefix(TitleSelector __instance, TitleButton titleButton)
		{
			try
			{
				if ((Object)(object)titleButton == (Object)null || !CustomButtons.TryGetValue(((Il2CppObjectBase)titleButton).Pointer, out var value))
				{
					return true;
				}
				Choose(((Il2CppObjectBase)__instance).TryCast<TitleSelector>(), titleButton);
				CustomTitlesMod.SetActive(value);
				return false;
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("select custom title: " + ex.Message);
				return true;
			}
		}

		internal static void MakeInitialSelectionPrefix(TitleSelector __instance)
		{
			try
			{
				object obj;
				if (__instance == null)
				{
					obj = null;
				}
				else
				{
					TitleSelector obj2 = ((Il2CppObjectBase)__instance).TryCast<TitleSelector>();
					obj = ((obj2 != null) ? obj2.titleButtons : null);
				}
				List<TitleButton> val = (List<TitleButton>)obj;
				int num = 0;
				while (val != null && num < val.Count)
				{
					TitleButton val2 = val[num];
					if ((Object)(object)val2 != (Object)null && (Object)(object)val2.config == (Object)null && ((Component)val2).gameObject.activeSelf)
					{
						val2.config = Placeholder();
					}
					num++;
				}
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("titles tab check: " + ex.Message);
			}
		}

		internal static void MakeInitialSelectionPostfix(TitleSelector __instance)
		{
			try
			{
				TitleSelector val = ((__instance != null) ? ((Il2CppObjectBase)__instance).TryCast<TitleSelector>() : null);
				string active = CustomTitlesMod.Active;
				if ((Object)(object)val == (Object)null || active.Length == 0)
				{
					return;
				}
				TitleButton val2 = Find(val, active);
				if (!((Object)(object)val2 == (Object)null))
				{
					Choose(val, val2);
					TitleScroller titleScroller = val.titleScroller;
					if (titleScroller != null)
					{
						titleScroller.ShowPageForElement(val.titleButtons.IndexOf(val2), val.elementsPerPage);
					}
				}
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("titles tab selection: " + ex.Message);
			}
		}

		internal static void Refresh()
		{
			try
			{
				if (!((Object)(object)_selector == (Object)null) && ((Behaviour)_selector).isActiveAndEnabled)
				{
					_selector.Configure();
					string active = CustomTitlesMod.Active;
					TitleButton val = ((active.Length > 0) ? Find(_selector, active) : null);
					if ((Object)(object)val != (Object)null)
					{
						Choose(_selector, val);
					}
				}
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("titles tab refresh: " + ex.Message);
			}
		}

		private static void Fill(TitleSelector selector)
		{
			List<TitleButton> titleButtons = selector.titleButtons;
			if (titleButtons == null || titleButtons.Count == 0)
			{
				return;
			}
			int num = 0;
			for (int i = 0; i < titleButtons.Count; i++)
			{
				TitleButton val = titleButtons[i];
				if (!((Object)(object)val == (Object)null))
				{
					if (CustomButtons.ContainsKey(((Il2CppObjectBase)val).Pointer))
					{
						Restore(val);
					}
					if (((Component)val).gameObject.activeSelf)
					{
						num = i + 1;
					}
				}
			}
			CustomButtons.Clear();
			List<string> titles = CustomTitlesMod.Titles;
			for (int j = 0; j < titles.Count; j++)
			{
				int num2 = num + j;
				TitleButton val2 = ((num2 < titleButtons.Count) ? titleButtons[num2] : Clone(selector, titleButtons[titleButtons.Count - 1]));
				if ((Object)(object)val2 == (Object)null)
				{
					break;
				}
				Relabel(val2, titles[j]);
				CustomButtons[((Il2CppObjectBase)val2).Pointer] = titles[j];
			}
			List<GameObject> pageFillers = selector.pageFillers;
			if (pageFillers == null)
			{
				return;
			}
			for (int k = 0; k < pageFillers.Count; k++)
			{
				GameObject obj = pageFillers[k];
				if (obj != null)
				{
					obj.SetActive(false);
				}
			}
		}

		private static void Relabel(TitleButton button, string title)
		{
			((Component)button).gameObject.SetActive(true);
			button.Deselect();
			button.config = Placeholder();
			LocalizeStringEvent title2 = button.title;
			if ((Object)(object)title2 != (Object)null)
			{
				((Behaviour)title2).enabled = false;
				TMP_Text component = ((Component)title2).GetComponent<TMP_Text>();
				if ((Object)(object)component != (Object)null)
				{
					component.text = title;
				}
			}
			Sprite val = DefaultIcon();
			if ((Object)(object)button.titleCategoryImage != (Object)null && (Object)(object)val != (Object)null)
			{
				button.titleCategoryImage.sprite = val;
				((Behaviour)button.titleCategoryImage).enabled = true;
			}
		}

		private static PlayerTitleConfig Placeholder()
		{
			if ((Object)(object)_placeholder != (Object)null)
			{
				return _placeholder;
			}
			List<PlayerTitleConfig> playerTitles = PlayerTitleRepository.PlayerTitles;
			PlayerTitleConfig val = null;
			int num = 0;
			while (playerTitles != null && num < playerTitles.Count && (Object)(object)val == (Object)null)
			{
				val = playerTitles[num];
				num++;
			}
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			_placeholder = Object.Instantiate<PlayerTitleConfig>(val);
			((Object)_placeholder).name = "CustomTitles_Placeholder";
			((Object)_placeholder).hideFlags = (HideFlags)61;
			_placeholder.PlayerTitleId = (PlayerTitleId)2147418112;
			_placeholder.Icon = DefaultIcon();
			return _placeholder;
		}

		private static Sprite DefaultIcon()
		{
			if ((Object)(object)_defaultIcon != (Object)null)
			{
				return _defaultIcon;
			}
			try
			{
				Dictionary<IntPtr, (Sprite, int)> dictionary = new Dictionary<IntPtr, (Sprite, int)>();
				List<PlayerTitleConfig> playerTitles = PlayerTitleRepository.PlayerTitles;
				int num = 0;
				while (playerTitles != null && num < playerTitles.Count)
				{
					PlayerTitleConfig obj = playerTitles[num];
					Sprite val = ((obj != null) ? obj.Icon : null);
					if (!((Object)(object)val == (Object)null))
					{
						dictionary.TryGetValue(((Il2CppObjectBase)val).Pointer, out var value);
						dictionary[((Il2CppObjectBase)val).Pointer] = (val, value.Item2 + 1);
					}
					num++;
				}
				int num2 = 0;
				foreach (var (_, tuple2) in dictionary)
				{
					if (tuple2.Item2 > num2)
					{
						num2 = tuple2.Item2;
						(_defaultIcon, _) = tuple2;
					}
				}
			}
			catch (Exception ex)
			{
				CustomTitlesMod.Log.Warning("default title icon: " + ex.Message);
			}
			return _defaultIcon;
		}

		private static void Restore(TitleButton button)
		{
			LocalizeStringEvent title = button.title;
			if ((Object)(object)title != (Object)null && !((Behaviour)title).enabled)
			{
				((Behaviour)title).enabled = true;
				title.RefreshString();
			}
		}

		private static TitleButton Clone(TitleSelector selector, TitleButton template)
		{
			GameObject val = Object.Instantiate<GameObject>(((Component)template).gameObject, ((Component)template).transform.parent, false);
			val.transform.SetSiblingIndex(((Component)template).transform.GetSiblingIndex() + 1);
			TitleButton clone = val.GetComponent<TitleButton>();
			clone.OnSelectedAction = Action.op_Implicit((Action)delegate
			{
				selector.OnSelected(clone);
			});
			clone.OnHighlightStartedAction = Action.op_Implicit((Action)delegate
			{
				selector.OnHighlightStarted(clone);
			});
			selector.titleButtons.Add(clone);
			return clone;
		}

		private static void Choose(TitleSelector selector, TitleButton button)
		{
			TitleButton currentTitleButton = selector.currentTitleButton;
			if ((Object)(object)currentTitleButton != (Object)null && ((Il2CppObjectBase)currentTitleButton).Pointer != ((Il2CppObjectBase)button).Pointer)
			{
				currentTitleButton.Deselect();
			}
			selector.currentTitleButton = button;
			button.Select();
		}

		private static TitleButton Find(TitleSelector selector, string title)
		{
			List<TitleButton> titleButtons = selector.titleButtons;
			for (int i = 0; i < titleButtons.Count; i++)
			{
				TitleButton val = titleButtons[i];
				if ((Object)(object)val != (Object)null && CustomButtons.TryGetValue(((Il2CppObjectBase)val).Pointer, out var value) && value == title)
				{
					return val;
				}
			}
			return null;
		}
	}
}
namespace CustomTitles.BepInExPlugin
{
	[BepInPlugin("SpellBrigade.CustomTitles", "Custom Titles", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		public const string Guid = "SpellBrigade.CustomTitles";

		public override void Load()
		{
			MelonCompat.Start<CustomTitlesMod, Runner>((BasePlugin)(object)this, "SpellBrigade.CustomTitles");
		}
	}
	public class Runner : MonoBehaviour
	{
		public Runner(IntPtr ptr)
			: base(ptr)
		{
		}

		private void Update()
		{
			MelonCompat.Update();
		}
	}
}
namespace MelonLoader
{
	[AttributeUsage(AttributeTargets.Assembly)]
	public sealed class MelonInfoAttribute : Attribute
	{
		public MelonInfoAttribute(Type type, string name, string version, string author, string downloadLink = null)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	public sealed class MelonGameAttribute : Attribute
	{
		public MelonGameAttribute(string developer = null, string name = null)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public sealed class MelonOptionalDependenciesAttribute : Attribute
	{
		public MelonOptionalDependenciesAttribute(params string[] names)
		{
		}
	}
	public abstract class MelonBase
	{
		public MelonLogger.Instance LoggerInstance { get; internal set; }

		public Harmony HarmonyInstance { get; internal set; }

		public static object FindMelon(string name, string author)
		{
			try
			{
				foreach (PluginInfo value in ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.Values)
				{
					if (((value != null) ? value.Metadata : null) != null && string.Equals(value.Metadata.Name, name, StringComparison.OrdinalIgnoreCase) && value.Instance != null)
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return null;
		}
	}
	public abstract class MelonMod : MelonBase
	{
		public virtual void OnInitializeMelon()
		{
		}

		public virtual void OnLateInitializeMelon()
		{
		}

		public virtual void OnUpdate()
		{
		}

		public virtual void OnLateUpdate()
		{
		}

		public virtual void OnFixedUpdate()
		{
		}

		public virtual void OnGUI()
		{
		}

		public virtual void OnApplicationQuit()
		{
		}

		public virtual void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
		}

		public virtual void OnSceneWasInitialized(int buildIndex, string sceneName)
		{
		}

		public virtual void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
		}
	}
	public static class MelonLogger
	{
		public sealed class Instance
		{
			private readonly ManualLogSource _log;

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

			public void Msg(string text)
			{
				_log.LogInfo((object)text);
			}

			public void Msg(object value)
			{
				_log.LogInfo(value);
			}

			public void Msg(string format, params object[] args)
			{
				_log.LogInfo((object)string.Format(format, args));
			}

			public void Warning(string text)
			{
				_log.LogWarning((object)text);
			}

			public void Warning(object value)
			{
				_log.LogWarning(value);
			}

			public void Error(string text)
			{
				_log.LogError((object)text);
			}

			public void Error(object value)
			{
				_log.LogError(value);
			}

			public void Error(string text, Exception e)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Expected O, but got Unknown
				ManualLogSource log = _log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("\n");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(e);
				}
				log.LogError(val);
			}
		}
	}
	public static class MelonCompat
	{
		internal static ConfigFile Config;

		private static MelonMod _mod;

		private static bool _lateInit;

		public static void Start<TMod, TRunner>(BasePlugin plugin, string harmonyId) where TMod : MelonMod, new() where TRunner : MonoBehaviour
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			Config = plugin.Config;
			_mod = new TMod
			{
				LoggerInstance = new MelonLogger.Instance(plugin.Log),
				HarmonyInstance = new Harmony(harmonyId)
			};
			try
			{
				_mod.HarmonyInstance.PatchAll(typeof(TMod).Assembly);
			}
			catch (Exception ex)
			{
				ManualLogSource log = plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(17, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Harmony patches: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				log.LogError(val);
			}
			_mod.OnInitializeMelon();
			HookScenes();
			ClassInjector.RegisterTypeInIl2Cpp<TRunner>();
			plugin.AddComponent<TRunner>();
		}

		private static void HookScenes()
		{
			SceneManager.sceneLoaded += DelegateSupport.ConvertDelegate<UnityAction<Scene, LoadSceneMode>>((Delegate)new Action<Scene, LoadSceneMode>(OnSceneLoaded));
			SceneManager.sceneUnloaded += DelegateSupport.ConvertDelegate<UnityAction<Scene>>((Delegate)new Action<Scene>(OnSceneUnloaded));
		}

		private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Guard(delegate
			{
				_mod.OnSceneWasLoaded(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
			});
			Guard(delegate
			{
				_mod.OnSceneWasInitialized(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
			});
		}

		private static void OnSceneUnloaded(Scene scene)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Guard(delegate
			{
				_mod.OnSceneWasUnloaded(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
			});
		}

		public static void Update()
		{
			if (_mod != null)
			{
				if (!_lateInit)
				{
					_lateInit = true;
					Guard(_mod.OnLateInitializeMelon);
				}
				_mod.OnUpdate();
			}
		}

		public static void LateUpdate()
		{
			_mod?.OnLateUpdate();
		}

		public static void FixedUpdate()
		{
			_mod?.OnFixedUpdate();
		}

		public static void OnGUI()
		{
			_mod?.OnGUI();
		}

		public static void Quit()
		{
			_mod?.OnApplicationQuit();
		}

		private static void Guard(Action a)
		{
			try
			{
				a();
			}
			catch (Exception ex)
			{
				_mod.LoggerInstance.Error(ex.ToString());
			}
		}
	}
	public static class MelonPreferences
	{
		private static readonly Dictionary<string, MelonPreferences_Category> Categories = new Dictionary<string, MelonPreferences_Category>();

		public static MelonPreferences_Category CreateCategory(string identifier, string displayName = null, bool is_hidden = false, bool is_inlined = false)
		{
			if (!Categories.TryGetValue(identifier, out var value))
			{
				value = (Categories[identifier] = new MelonPreferences_Category(identifier, displayName ?? identifier)
				{
					IsHidden = is_hidden
				});
			}
			return value;
		}

		public static MelonPreferences_Category GetCategory(string identifier)
		{
			if (!Categories.TryGetValue(identifier, out var value))
			{
				return null;
			}
			return value;
		}

		public static void Save()
		{
			ConfigFile config = MelonCompat.Config;
			if (config != null)
			{
				config.Save();
			}
		}
	}
	public sealed class MelonPreferences_Category
	{
		public readonly List<MelonPreferences_Entry> Entries = new List<MelonPreferences_Entry>();

		public string Identifier { get; }

		public string DisplayName { get; }

		public bool IsHidden { get; internal set; }

		internal MelonPreferences_Category(string identifier, string displayName)
		{
			Identifier = identifier;
			DisplayName = displayName;
		}

		public MelonPreferences_Entry<T> CreateEntry<T>(string identifier, T default_value, string display_name = null, string description = null, bool is_hidden = false, bool dont_save_default = false, ValueValidator validator = null, string oldIdentifier = null)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
			{
				DispName = (display_name ?? identifier),
				Browsable = (!is_hidden && !IsHidden),
				Order = -Entries.Count,
				Category = DisplayName
			};
			AcceptableValueBase val = validator?.ToAcceptable(typeof(T));
			ConfigEntry<T> cfg = MelonCompat.Config.Bind<T>(Identifier, identifier, default_value, new ConfigDescription(description ?? "", val, new object[1] { configurationManagerAttributes }));
			MelonPreferences_Entry<T> melonPreferences_Entry = new MelonPreferences_Entry<T>(this, cfg, identifier, display_name ?? identifier, description, is_hidden);
			Entries.Add(melonPreferences_Entry);
			return melonPreferences_Entry;
		}

		public MelonPreferences_Entry GetEntry(string identifier)
		{
			return Entries.Find((MelonPreferences_Entry e) => e.Identifier == identifier);
		}

		public MelonPreferences_Entry<T> GetEntry<T>(string identifier)
		{
			return GetEntry(identifier) as MelonPreferences_Entry<T>;
		}

		public bool HasEntry(string identifier)
		{
			return GetEntry(identifier) != null;
		}

		public void SaveToFile(bool printmsg = true)
		{
			ConfigFile config = MelonCompat.Config;
			if (config != null)
			{
				config.Save();
			}
		}

		public void LoadFromFile(bool printmsg = true)
		{
			ConfigFile config = MelonCompat.Config;
			if (config != null)
			{
				config.Reload();
			}
		}
	}
	public abstract class MelonPreferences_Entry
	{
		public readonly MelonEvent<object, object> OnEntryValueChangedUntyped = new MelonEvent<object, object>();

		public MelonPreferences_Category Category { get; protected set; }

		public string Identifier { get; protected set; }

		public string DisplayName { get; protected set; }

		public string Description { get; protected set; }

		public bool IsHidden { get; protected set; }

		public abstract ConfigEntryBase Raw { get; }

		public abstract object BoxedValue { get; set; }

		public abstract void ResetToDefault();
	}
	public sealed class MelonPreferences_Entry<T> : MelonPreferences_Entry
	{
		private readonly ConfigEntry<T> _cfg;

		private T _last;

		public readonly MelonEvent<T, T> OnEntryValueChanged = new MelonEvent<T, T>();

		public readonly MelonEvent<T, T> OnValueChanged;

		public T Value
		{
			get
			{
				return _cfg.Value;
			}
			set
			{
				_cfg.Value = value;
			}
		}

		public T DefaultValue => (T)((ConfigEntryBase)_cfg).DefaultValue;

		public override ConfigEntryBase Raw => (ConfigEntryBase)(object)_cfg;

		public override object BoxedValue
		{
			get
			{
				return ((ConfigEntryBase)_cfg).BoxedValue;
			}
			set
			{
				((ConfigEntryBase)_cfg).BoxedValue = value;
			}
		}

		internal MelonPreferences_Entry(MelonPreferences_Category category, ConfigEntry<T> cfg, string identifier, string displayName, string description, bool hidden)
		{
			base.Category = category;
			_cfg = cfg;
			base.Identifier = identifier;
			base.DisplayName = displayName;
			base.Description = description;
			base.IsHidden = hidden;
			OnValueChanged = OnEntryValueChanged;
			_last = cfg.Value;
			cfg.SettingChanged += OnSettingChanged;
		}

		private void OnSettingChanged(object sender, EventArgs e)
		{
			T last = _last;
			_last = _cfg.Value;
			if (!EqualityComparer<T>.Default.Equals(last, _last))
			{
				OnEntryValueChanged.Invoke(last, _last);
				OnEntryValueChangedUntyped.Invoke(last, _last);
			}
		}

		public override void ResetToDefault()
		{
			_cfg.Value = DefaultValue;
		}
	}
	public sealed class MelonEvent<T1, T2>
	{
		private readonly List<Action<T1, T2>> _handlers = new List<Action<T1, T2>>();

		public void Subscribe(Action<T1, T2> handler, int priority = 0, bool unsubscribeOnFirstInvocation = false)
		{
			_handlers.Add(handler);
		}

		public void Unsubscribe(Action<T1, T2> handler)
		{
			_handlers.Remove(handler);
		}

		internal void Invoke(T1 a, T2 b)
		{
			Action<T1, T2>[] array = _handlers.ToArray();
			foreach (Action<T1, T2> action in array)
			{
				try
				{
					action(a, b);
				}
				catch (Exception ex)
				{
					Debug.LogError(Object.op_Implicit(ex.ToString()));
				}
			}
		}
	}
	public sealed class ConfigurationManagerAttributes
	{
		public string DispName;

		public bool? Browsable;

		public int? Order;

		public string Category;
	}
}
namespace MelonLoader.Preferences
{
	public abstract class ValueValidator
	{
		public abstract AcceptableValueBase ToAcceptable(Type type);
	}
	public sealed class ValueRange<T> : ValueValidator where T : IComparable
	{
		public T MinValue { get; }

		public T MaxValue { get; }

		public ValueRange(T min, T max)
		{
			MinValue = min;
			MaxValue = max;
		}

		public override AcceptableValueBase ToAcceptable(Type type)
		{
			if (!(type == typeof(T)))
			{
				return null;
			}
			return (AcceptableValueBase)(object)new AcceptableValueRange<T>(MinValue, MaxValue);
		}
	}
}
namespace Il2CppTMPro
{
	internal static class NamespaceStandIn
	{
	}
}
namespace Il2Cpp
{
	internal static class NamespaceStandIn
	{
	}
}