Decompiled source of BuildMenuQOL v0.3.0

BuildMenuQOL.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BuildMenuQOL")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0+b374dbcb01618e1bd4e4f7554866c9c7c3f8fda9")]
[assembly: AssemblyProduct("BuildMenuQOL")]
[assembly: AssemblyTitle("BuildMenuQOL")]
[assembly: AssemblyVersion("0.3.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[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;
		}
	}
	[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 BuildMenuQOL
{
	[BepInPlugin("ShaolinShade.BuildMenuQOL", "BuildMenuQOL", "0.3.0")]
	public sealed class BuildMenuQOLPlugin : BaseUnityPlugin
	{
		private sealed class BadgeVisuals
		{
			public readonly GameObject Root;

			public readonly List<KeyValuePair<Component, PropertyInfo>> Texts = new List<KeyValuePair<Component, PropertyInfo>>();

			public readonly List<Behaviour> Visuals = new List<Behaviour>();

			public BadgeVisuals(GameObject root)
			{
				Root = root;
				Component[] componentsInChildren = root.GetComponentsInChildren<Component>(true);
				foreach (Component val in componentsInChildren)
				{
					if (!((Object)(object)val == (Object)null))
					{
						Type type = ((object)val).GetType();
						PropertyInfo property;
						bool flag = TryGetTextProperty(type, out property);
						if (flag)
						{
							Texts.Add(new KeyValuePair<Component, PropertyInfo>(val, property));
						}
						bool flag2 = type.FullName == "UnityEngine.UI.Image";
						Behaviour val2 = (Behaviour)(object)((val is Behaviour) ? val : null);
						if (val2 != null && (flag || flag2))
						{
							Visuals.Add(val2);
						}
					}
				}
			}
		}

		public const string PluginGuid = "ShaolinShade.BuildMenuQOL";

		public const string PluginName = "BuildMenuQOL";

		public const string PluginVersion = "0.3.0";

		internal static ManualLogSource Log = null;

		internal static ConfigEntry<KeyboardShortcut> RepairHotkey = null;

		internal static ConfigEntry<KeyboardShortcut> FilterHotkey = null;

		internal static ConfigEntry<KeyboardShortcut> PreviousTabHotkey = null;

		internal static ConfigEntry<KeyboardShortcut> NextTabHotkey = null;

		internal static ConfigEntry<bool> ShowTabSwitchHotkeyBadges = null;

		internal static ConfigEntry<bool> ShowRepairHotkeyBadge = null;

		internal static ConfigEntry<bool> ShowFilterHotkeyBadge = null;

		internal static ConfigEntry<bool> VerboseLogging = null;

		internal static ConfigEntry<bool> EquipToggle = null;

		internal static ConfigEntry<bool> ReequipPreviousGear = null;

		private const BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly Type? BuildUiType = AccessTools.TypeByName("BuildUi");

		private static readonly FieldInfo? PieceListsField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_pieceLists"));

		private static readonly FieldInfo? RecentPieceListField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_recentPieceList"));

		private static readonly FieldInfo? CurrentPieceListField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_currentPieceList"));

		private static readonly FieldInfo? CurrentBuildToolField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_currentBuildTool"));

		private static readonly FieldInfo? SpecialPieceButtonField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_specialPieceButton"));

		private static readonly FieldInfo? SpecialButtonsContainerField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_specialButtonsContainer"));

		private static readonly FieldInfo? PieceButtonPrefabField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_pieceButtonPrefab"));

		private static readonly FieldInfo? SearchFieldField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_searchField"));

		private static readonly FieldInfo? BuildUiTabHandlerField = ((BuildUiType == null) ? null : AccessTools.Field(BuildUiType, "m_tabHandler"));

		private static readonly Type? InputHintType = AccessTools.TypeByName("UIInputHint");

		private static readonly Type? ZInputType = AccessTools.TypeByName("ZInput");

		private static readonly Func<bool>? IsGamepadActive = MakeStaticBoolDelegate(ZInputType, "IsGamepadActive");

		private static readonly Func<bool>? IsMouseActive = MakeStaticBoolDelegate(ZInputType, "IsMouseActive");

		private static readonly Func<KeyCode, bool>? ZInputKeyDown = MakeZInputKeyDelegate(ZInputType, "GetKeyDown");

		private static readonly Func<KeyCode, bool>? ZInputKeyHeld = MakeZInputKeyDelegate(ZInputType, "GetKey");

		private static readonly MethodInfo? SetTagListActiveMethod = ((BuildUiType == null) ? null : AccessTools.Method(BuildUiType, "SetTagListActive", new Type[2]
		{
			typeof(bool),
			typeof(bool)
		}, (Type[])null));

		private static readonly MethodInfo? ConfigureButtonNavigationMethod = ((BuildUiType == null) ? null : AccessTools.Method(BuildUiType, "ConfigureButtonNavigation", (Type[])null, (Type[])null));

		private static BuildUi? _buildUi;

		private static TabHandler? _tabHandler;

		private static float _nextBuildUiLookup;

		private static float _nextTabBadgeSearch;

		private static Component? _filterField;

		private static BadgeVisuals? _filterBadge;

		private static BadgeVisuals? _repairBadge;

		private static Transform? _repairButtonTransform;

		private static BadgeVisuals? _previousTabBadge;

		private static BadgeVisuals? _nextTabBadge;

		private static string _repairText = "";

		private static string _filterText = "";

		private static string _previousTabText = "";

		private static string _nextTabText = "";

		private static readonly Vector3[] WorldCorners = (Vector3[])(object)new Vector3[4];

		private static readonly HashSet<string> LoggedErrors = new HashSet<string>();

		private static int _tabBadgeAttempts;

		private const int MaxTabBadgeAttempts = 3;

		private EventHandler? _shortcutChangedHandler;

		private Harmony? _harmony;

		private const float PendingGraceSeconds = 1.5f;

		private const float PendingHardCapSeconds = 90f;

		private static ItemData? _pendingHammer;

		private static float _pendingStarted;

		private static float _pendingGraceUntil;

		private static ItemData? _savedHammer;

		private static ItemData? _savedRight;

		private static ItemData? _savedLeft;

		private static readonly MethodInfo? TakeInputMethod = AccessTools.Method(typeof(Player), "TakeInput", (Type[])null, (Type[])null);

		private static readonly MethodInfo? ToggleEquippedMethod = AccessTools.Method(typeof(Player), "ToggleEquipped", new Type[1] { typeof(ItemData) }, (Type[])null);

		private static readonly Func<string, bool>? ZInputButton = MakeZInputButtonDelegate(ZInputType, "GetButton");

		private static readonly Func<string, bool>? ZInputButtonDown = MakeZInputButtonDelegate(ZInputType, "GetButtonDown");

		private static readonly Action<string>? ZInputResetButton = MakeZInputResetDelegate(ZInputType);

		private static int _fallbackWarnings;

		private static float _nextHeartbeat;

		private static long _updateFrames;

		private static readonly Type? LocalizationType = AccessTools.TypeByName("Localization");

		private static readonly PropertyInfo? LocalizationInstanceProperty = ((LocalizationType == null) ? null : AccessTools.Property(LocalizationType, "instance"));

		private static readonly MethodInfo? LocalizeMethod = ((LocalizationType == null) ? null : AccessTools.Method(LocalizationType, "Localize", new Type[1] { typeof(string) }, (Type[])null));

		private static readonly MethodInfo? GetSelectedLanguageMethod = ((LocalizationType == null) ? null : AccessTools.Method(LocalizationType, "GetSelectedLanguage", Type.EmptyTypes, (Type[])null));

		private static readonly Dictionary<string, string> KeyLocalizationTokens = new Dictionary<string, string>
		{
			["Mouse0"] = "$button_mouse0",
			["Mouse1"] = "$button_mouse1",
			["Mouse2"] = "$button_mouse2",
			["Space"] = "$button_space",
			["Return"] = "$button_return",
			["LeftShift"] = "$button_lshift",
			["RightShift"] = "$button_rshift",
			["LeftAlt"] = "$button_lalt",
			["RightAlt"] = "$button_ralt",
			["LeftControl"] = "$button_lctrl",
			["RightControl"] = "$button_rctrl"
		};

		private static string _textLanguage = "";

		private static float _nextLanguageCheck;

		private static readonly Dictionary<string, string> KeySymbols = new Dictionary<string, string>
		{
			["Exclaim"] = "!",
			["DoubleQuote"] = "\"",
			["Hash"] = "#",
			["Dollar"] = "$",
			["Percent"] = "%",
			["Ampersand"] = "&",
			["Quote"] = "'",
			["LeftParen"] = "(",
			["RightParen"] = ")",
			["Asterisk"] = "*",
			["Plus"] = "+",
			["Comma"] = ",",
			["Minus"] = "-",
			["Period"] = ".",
			["Slash"] = "/",
			["Colon"] = ":",
			["Semicolon"] = ";",
			["Less"] = "<",
			["Equals"] = "=",
			["Greater"] = ">",
			["Question"] = "?",
			["At"] = "@",
			["LeftBracket"] = "[",
			["Backslash"] = "\\",
			["RightBracket"] = "]",
			["Caret"] = "^",
			["Underscore"] = "_",
			["BackQuote"] = "`",
			["LeftCurlyBracket"] = "{",
			["Pipe"] = "|",
			["RightCurlyBracket"] = "}",
			["Tilde"] = "~"
		};

		private static readonly Dictionary<string, string> KeyShortNames = new Dictionary<string, string>
		{
			["Return"] = "Enter",
			["Escape"] = "Esc",
			["Delete"] = "Del",
			["Insert"] = "Ins",
			["Backspace"] = "Bksp",
			["PageUp"] = "PgUp",
			["PageDown"] = "PgDn",
			["CapsLock"] = "Caps",
			["LeftArrow"] = "←",
			["RightArrow"] = "→",
			["UpArrow"] = "↑",
			["DownArrow"] = "↓",
			["LeftShift"] = "LShift",
			["RightShift"] = "RShift",
			["LeftControl"] = "LCtrl",
			["RightControl"] = "RCtrl",
			["LeftAlt"] = "LAlt",
			["RightAlt"] = "RAlt"
		};

		private void Awake()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			RepairHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "Repair Mode", new KeyboardShortcut((KeyCode)96, Array.Empty<KeyCode>()), "Repair hotkey. Requires the hammer to be equipped unless 'EquipToggle' is enabled. Works with the build menu open or closed. #See the readme or mod description page for keycode references if editing the config file manually");
			FilterHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "Focus Filter", new KeyboardShortcut((KeyCode)102, Array.Empty<KeyCode>()), "Filter hotkey. Focuses the Filter field while the hammer is equipped and the build menu is open. #See the readme or mod description page for keycode references if editing the config file manually");
			PreviousTabHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "Previous Tab", new KeyboardShortcut((KeyCode)113, Array.Empty<KeyCode>()), "Previous build menu tab hotkey. #See the readme or mod description page for keycode references if editing the config file manually");
			NextTabHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "Next Tab", new KeyboardShortcut((KeyCode)101, Array.Empty<KeyCode>()), "Next build menu tab hotkey. #See the readme or mod description page for keycode references if editing the config file manually");
			ShowTabSwitchHotkeyBadges = ((BaseUnityPlugin)this).Config.Bind<bool>("Hotkeys", "Show Tab Switch Hotkey Badges", true, "Show or hide both the Previous Tab and Next Tab hotkey badges in the build menu. #Only applies when using keyboard/mouse, hotkey badges are always shown when using controller");
			ShowFilterHotkeyBadge = ((BaseUnityPlugin)this).Config.Bind<bool>("Hotkeys", "Show Filter Hotkey Badge", true, "Show the Filter hotkey icon/badge in the build menu. #Only applies when using keyboard/mouse, hotkey badges are always shown when using controller");
			ShowRepairHotkeyBadge = ((BaseUnityPlugin)this).Config.Bind<bool>("Hotkeys", "Show Repair Hotkey Badge", true, "Show the Repair hotkey icon/badge in the build menu. #Only applies when using keyboard/mouse, hotkey badges are always shown when using controller");
			EquipToggle = ((BaseUnityPlugin)this).Config.Bind<bool>("Hotkeys", "Equip Toggle", true, "If true, the Repair hotkey equips your hammer first if it isn't equipped (it must be in your inventory), then switches to Repair; pressing it again while already in Repair mode unequips the hammer.");
			ReequipPreviousGear = ((BaseUnityPlugin)this).Config.Bind<bool>("Hotkeys", "Re-equip Previous Gear", true, "Re-equips previous gear when unequipping the hammer with the repair hotkey. Only has an effect if Equip Toggle is enabled.");
			VerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Verbose Logging", false, "Write extra diagnostic information to the BepInEx log (patch results, badge discovery, tab-switch timings). Leave off unless you're troubleshooting.");
			RefreshShortcutText();
			_shortcutChangedHandler = delegate
			{
				RefreshShortcutText();
			};
			RepairHotkey.SettingChanged += _shortcutChangedHandler;
			FilterHotkey.SettingChanged += _shortcutChangedHandler;
			PreviousTabHotkey.SettingChanged += _shortcutChangedHandler;
			NextTabHotkey.SettingChanged += _shortcutChangedHandler;
			try
			{
				_harmony = new Harmony("ShaolinShade.BuildMenuQOL");
				InstallPatches();
				Log.LogInfo((object)("BuildMenuQOL 0.3.0 loaded. " + $"Repair hotkey: {RepairHotkey.Value}; " + $"Filter hotkey: {FilterHotkey.Value}"));
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Could not install patches: {arg}");
				Harmony? harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
				_harmony = null;
			}
		}

		private void OnDisable()
		{
			Dbg("Plugin component disabled; hotkeys and badge syncing are not running.");
		}

		private void OnDestroy()
		{
			Dbg("Plugin component destroyed; unpatching.");
			if (_shortcutChangedHandler != null)
			{
				RepairHotkey.SettingChanged -= _shortcutChangedHandler;
				FilterHotkey.SettingChanged -= _shortcutChangedHandler;
				PreviousTabHotkey.SettingChanged -= _shortcutChangedHandler;
				NextTabHotkey.SettingChanged -= _shortcutChangedHandler;
				_shortcutChangedHandler = null;
			}
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_harmony = null;
		}

		internal static void Dbg(string message)
		{
			if (VerboseLogging != null && VerboseLogging.Value)
			{
				Log.LogInfo((object)("[verbose] " + message));
			}
		}

		private static void LogOnce(string where, Exception ex)
		{
			if (LoggedErrors.Add(where))
			{
				Log.LogError((object)$"{where} failed (further errors from it suppressed): {ex}");
			}
		}

		private static void RefreshShortcutText()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			_textLanguage = CurrentLanguage();
			_repairText = FormatShortcut(RepairHotkey.Value);
			_filterText = FormatShortcut(FilterHotkey.Value);
			_previousTabText = FormatShortcut(PreviousTabHotkey.Value);
			_nextTabText = FormatShortcut(NextTabHotkey.Value);
			Dbg("Badge text: repair '" + _repairText + "', filter '" + _filterText + "', previous tab '" + _previousTabText + "', next tab '" + _nextTabText + "'");
		}

		private void Update()
		{
			_updateFrames++;
			if (VerboseLogging.Value && Time.unscaledTime >= _nextHeartbeat)
			{
				_nextHeartbeat = Time.unscaledTime + 60f;
				Dbg($"heartbeat: frames={_updateFrames}, enabled={((Behaviour)this).enabled}, buildUiCached={(Object)(object)_buildUi != (Object)null}, " + $"legacyAnyKey={Input.anyKey}, gameKeyApi={ZInputKeyDown != null}, timeScale={Time.timeScale}");
			}
			BuildUi val = null;
			try
			{
				val = GetActiveBuildUi();
			}
			catch (Exception ex)
			{
				LogOnce("Build menu lookup", ex);
			}
			if ((Object)(object)val != (Object)null)
			{
				try
				{
					HandleTabSwitchHotkeys(val);
				}
				catch (Exception ex2)
				{
					LogOnce("Tab hotkeys", ex2);
				}
			}
			try
			{
				HandleRepairHotkey(val);
			}
			catch (Exception ex3)
			{
				LogOnce("Repair hotkey", ex3);
			}
		}

		private void LateUpdate()
		{
			try
			{
				BuildUi activeBuildUi = GetActiveBuildUi();
				if ((Object)(object)activeBuildUi != (Object)null)
				{
					SyncBadges(activeBuildUi);
				}
			}
			catch (Exception ex)
			{
				LogOnce("Badge sync", ex);
			}
		}

		private static BuildUi? GetActiveBuildUi()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			BuildUi val = _buildUi;
			if ((Object)(object)val == (Object)null)
			{
				if ((Object)(object)Player.m_localPlayer == (Object)null || Time.unscaledTime < _nextBuildUiLookup)
				{
					return null;
				}
				_nextBuildUiLookup = Time.unscaledTime + 2f;
				BuildUi[] array = Resources.FindObjectsOfTypeAll<BuildUi>();
				foreach (BuildUi val2 in array)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						Scene scene = ((Component)val2).gameObject.scene;
						if (((Scene)(ref scene)).IsValid())
						{
							CacheBuildUi(val2);
							val = val2;
							break;
						}
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
			}
			if (!((Component)val).gameObject.activeInHierarchy)
			{
				return null;
			}
			return val;
		}

		private static void CacheBuildUi(object instance)
		{
			BuildUi val = (BuildUi)((instance is BuildUi) ? instance : null);
			if (val != null && (_buildUi != val || !((Object)(object)_tabHandler != (Object)null)))
			{
				if (_buildUi != val)
				{
					_previousTabBadge = null;
					_nextTabBadge = null;
					_tabBadgeAttempts = 0;
				}
				_buildUi = val;
				object? obj = BuildUiTabHandlerField?.GetValue(val);
				_tabHandler = (TabHandler?)((obj is TabHandler) ? obj : null);
			}
		}

		private static Func<string, bool>? MakeZInputButtonDelegate(Type? type, string methodName)
		{
			if (type == null)
			{
				return null;
			}
			MethodInfo methodInfo = AccessTools.Method(type, methodName, new Type[1] { typeof(string) }, (Type[])null);
			if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(bool))
			{
				return null;
			}
			return (Func<string, bool>)Delegate.CreateDelegate(typeof(Func<string, bool>), methodInfo);
		}

		private static Action<string>? MakeZInputResetDelegate(Type? type)
		{
			if (type == null)
			{
				return null;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "ResetButtonStatus", new Type[1] { typeof(string) }, (Type[])null);
			if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(void))
			{
				return null;
			}
			return (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo);
		}

		private static void HandleRepairHotkey(BuildUi? ui)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (_pendingHammer != null)
			{
				ContinuePendingRepair(Player.m_localPlayer);
			}
			if (_savedHammer != null && _pendingHammer == null && !_savedHammer.m_equipped)
			{
				ClearSavedGear("the hammer is no longer equipped");
			}
			if (ShortcutDown(RepairHotkey.Value))
			{
				Dbg("Repair hotkey press detected.");
				PerformRepairAction(ui);
			}
		}

		private static bool PerformRepairAction(BuildUi? ui)
		{
			string textInputBlocker = GetTextInputBlocker(ui);
			if (textInputBlocker != null)
			{
				Dbg("Repair hotkey ignored: " + textInputBlocker + " is active.");
				return false;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				Dbg("Repair hotkey ignored: no local player.");
				return false;
			}
			if (_pendingHammer != null)
			{
				Dbg("Repair hotkey ignored: still waiting for the hammer to finish equipping.");
				return true;
			}
			bool value = EquipToggle.Value;
			if (!HasEquippedCraftingHammer(localPlayer))
			{
				if (!value)
				{
					Dbg("Repair hotkey ignored: no hammer equipped (EquipToggle is off).");
					return false;
				}
				if (!CanTakeInput(localPlayer))
				{
					Dbg("Repair hotkey ignored: the game isn't taking player input (inventory, map or a menu is open).");
					return false;
				}
				return BeginEquipHammer(localPlayer);
			}
			bool flag = (Object)(object)ui != (Object)null || Hud.IsPieceSelectionVisible();
			if (value && !flag && IsRepairSelected(localPlayer))
			{
				if (!CanTakeInput(localPlayer))
				{
					Dbg("Repair hotkey ignored: the game isn't taking player input (inventory, map or a menu is open).");
					return false;
				}
				UnequipHammer(localPlayer);
				return true;
			}
			return SelectRepairPiece(localPlayer);
		}

		private static bool IsRepairSelected(Player player)
		{
			Piece selectedPiece = player.GetSelectedPiece();
			if ((Object)(object)selectedPiece != (Object)null)
			{
				return selectedPiece.m_repairPiece;
			}
			return false;
		}

		private static bool SelectRepairPiece(Player player)
		{
			List<Piece> buildPieces = player.GetBuildPieces();
			if (buildPieces == null)
			{
				return false;
			}
			Piece val = ((IEnumerable<Piece>)buildPieces).FirstOrDefault((Func<Piece, bool>)((Piece piece) => (Object)(object)piece != (Object)null && piece.m_repairPiece));
			if ((Object)(object)val == (Object)null)
			{
				Dbg("Repair hotkey pressed, but no vanilla Repair piece was found in the current build category.");
				return false;
			}
			if (player.SetSelectedPiece(val))
			{
				Dbg("Selected the vanilla Repair piece.");
				Hud.CloseBuildUi();
				return true;
			}
			return false;
		}

		private static bool CanTakeInput(Player player)
		{
			if (TakeInputMethod == null)
			{
				return true;
			}
			try
			{
				object obj = TakeInputMethod.Invoke(player, null);
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				return num == 0 || flag;
			}
			catch
			{
				return true;
			}
		}

		private static bool IsCraftingHammer(ItemData item)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			if (item.m_shared != null && (int)item.m_shared.m_itemType == 19 && (int)item.m_shared.m_skillType == 107)
			{
				return item.m_shared.m_name.IndexOf("hammer", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return false;
		}

		private static ItemData? FindCraftingHammer(Player player)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return null;
			}
			ItemData val = null;
			foreach (ItemData item in inventory.GetAllItemsInGridOrder())
			{
				if (item != null && IsCraftingHammer(item))
				{
					if (item.m_equipped)
					{
						return item;
					}
					if (val == null)
					{
						val = item;
					}
				}
			}
			return val;
		}

		private static bool RequestEquip(Player player, ItemData item)
		{
			try
			{
				if (ToggleEquippedMethod != null)
				{
					object obj = ToggleEquippedMethod.Invoke(player, new object[1] { item });
					bool flag = default(bool);
					int num;
					if (obj is bool)
					{
						flag = (bool)obj;
						num = 1;
					}
					else
					{
						num = 0;
					}
					return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				}
				return ((Humanoid)player).EquipItem(item, true);
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not equip '" + item.m_shared.m_name + "': " + ex.GetBaseException().Message));
				return false;
			}
		}

		private static bool BeginEquipHammer(Player player)
		{
			ItemData val = FindCraftingHammer(player);
			if (val == null)
			{
				Dbg("Repair hotkey ignored: no hammer in the inventory.");
				return false;
			}
			if (player.IsEquipActionQueued(val))
			{
				Dbg("Repair hotkey ignored: the hammer's equip is already queued.");
				return true;
			}
			_savedHammer = val;
			_savedRight = ((Humanoid)player).RightItem;
			_savedLeft = ((Humanoid)player).LeftItem;
			if (!RequestEquip(player, val))
			{
				Dbg("Equip toggle: the game refused to equip the hammer.");
				ClearSavedGear(null);
				return false;
			}
			_pendingHammer = val;
			_pendingStarted = Time.time;
			_pendingGraceUntil = 0f;
			Dbg("Equip toggle: equipping '" + val.m_shared.m_name + "' (remembered right: " + (_savedRight?.m_shared.m_name ?? "none") + ", left: " + (_savedLeft?.m_shared.m_name ?? "none") + ").");
			ContinuePendingRepair(player);
			return true;
		}

		private static void ContinuePendingRepair(Player? player)
		{
			ItemData pendingHammer = _pendingHammer;
			if (pendingHammer == null)
			{
				return;
			}
			if ((Object)(object)player == (Object)null || Time.time - _pendingStarted > 90f)
			{
				Dbg("Equip toggle: gave up waiting for the hammer to equip.");
				_pendingHammer = null;
				ClearSavedGear(null);
				return;
			}
			if (pendingHammer.m_equipped && ((Character)player).InPlaceMode())
			{
				_pendingHammer = null;
				Dbg("Equip toggle: the hammer is equipped; selecting Repair.");
				SelectRepairPiece(player);
				return;
			}
			if (player.IsEquipActionQueued(pendingHammer))
			{
				_pendingGraceUntil = 0f;
				return;
			}
			if (_pendingGraceUntil <= 0f)
			{
				_pendingGraceUntil = Time.time + 1.5f;
			}
			if (Time.time > _pendingGraceUntil)
			{
				Dbg("Equip toggle: the hammer is no longer queued and isn't equipped; giving up.");
				_pendingHammer = null;
				ClearSavedGear(null);
			}
		}

		private static void UnequipHammer(Player player)
		{
			ItemData val = FindCraftingHammer(player);
			if (val != null && val.m_equipped)
			{
				ItemData val2 = null;
				ItemData val3 = null;
				if (ReequipPreviousGear.Value && _savedHammer == val)
				{
					val2 = _savedRight;
					val3 = _savedLeft;
				}
				ClearSavedGear(null);
				((Humanoid)player).UnequipItem(val, true);
				Dbg("Equip toggle: unequipped the hammer.");
				if (Hud.IsPieceSelectionVisible())
				{
					Hud.CloseBuildUi();
				}
				if (val2 != null)
				{
					ReequipSaved(player, val2, "right hand");
				}
				if (val3 != null)
				{
					ReequipSaved(player, val3, "left hand");
				}
			}
		}

		private static void ReequipSaved(Player player, ItemData item, string hand)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null || !inventory.ContainsItem(item))
			{
				Dbg("Equip toggle: previous " + hand + " item is no longer in the inventory; not re-equipping.");
			}
			else if (!((Humanoid)player).IsItemEquiped(item))
			{
				bool flag = RequestEquip(player, item);
				Dbg("Equip toggle: re-equipping '" + item.m_shared.m_name + "' (" + hand + "): " + (flag ? "requested" : "refused") + ".");
			}
		}

		private static void ClearSavedGear(string? reason)
		{
			if (reason != null && (_savedRight != null || _savedLeft != null))
			{
				Dbg("Equip toggle: forgetting remembered gear (" + reason + ").");
			}
			_savedHammer = null;
			_savedRight = null;
			_savedLeft = null;
		}

		private static bool ControllerRepairComboPressed()
		{
			if (ZInputButtonDown == null || ZInputButton == null || IsGamepadActive == null)
			{
				return false;
			}
			try
			{
				return ZInputButtonDown("JoyButtonY") && ZInputButton("JoyAltKeys") && IsGamepadActive();
			}
			catch
			{
				return false;
			}
		}

		private static void InventoryGuiUpdatePrefix()
		{
			try
			{
				if (!ControllerRepairComboPressed() || Hud.IsPieceSelectionVisible())
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer == (Object)null) && CanTakeInput(localPlayer))
				{
					Dbg("Controller Alt + Y press detected.");
					if (PerformRepairAction(null))
					{
						ZInputResetButton?.Invoke("JoyButtonY");
						ZInputResetButton?.Invoke("Inventory");
						ZInputResetButton?.Invoke("JoyInventory");
					}
				}
			}
			catch (Exception ex)
			{
				LogOnce("Controller repair combo", ex);
			}
		}

		private static void HandleTabSwitchHotkeys(BuildUi ui)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			bool flag = ShortcutDown(PreviousTabHotkey.Value);
			bool flag2 = ShortcutDown(NextTabHotkey.Value);
			if (!flag && !flag2)
			{
				return;
			}
			Dbg($"Tab hotkey press detected (previous: {flag}, next: {flag2}).");
			string textInputBlocker = GetTextInputBlocker(ui);
			if (textInputBlocker != null)
			{
				Dbg("Tab hotkey ignored: " + textInputBlocker + " is active.");
				return;
			}
			TabHandler tabHandler = _tabHandler;
			if ((Object)(object)tabHandler == (Object)null || !((Behaviour)tabHandler).isActiveAndEnabled)
			{
				Dbg("Tab hotkey ignored: the build menu's tab handler is missing or disabled.");
				return;
			}
			foreach (GameObject blockingElement in tabHandler.m_blockingElements)
			{
				if ((Object)(object)blockingElement != (Object)null && blockingElement.activeSelf)
				{
					Dbg("Tab hotkey ignored: blocking element '" + ((Object)blockingElement).name + "' is visible.");
					return;
				}
			}
			List<Tab> tabs = tabHandler.m_tabs;
			int count = tabs.Count;
			if (count < 2)
			{
				return;
			}
			int num = ((!flag) ? 1 : (-1));
			int activeTab = tabHandler.GetActiveTab();
			int num2 = activeTab;
			for (int i = 0; i < count; i++)
			{
				int num3 = num2 + num;
				if (num3 < 0 || num3 >= count)
				{
					if (!tabHandler.m_cycling)
					{
						return;
					}
					num3 = (num3 + count) % count;
				}
				num2 = num3;
				if ((Object)(object)tabs[num2].m_button != (Object)null)
				{
					break;
				}
			}
			if (num2 == activeTab || (Object)(object)tabs[num2].m_button == (Object)null)
			{
				return;
			}
			try
			{
				long num4 = (VerboseLogging.Value ? Stopwatch.GetTimestamp() : 0);
				((UnityEvent)tabs[num2].m_button.onClick).Invoke();
				if (VerboseLogging.Value)
				{
					double num5 = (double)(Stopwatch.GetTimestamp() - num4) * 1000.0 / (double)Stopwatch.Frequency;
					Dbg($"Tab {activeTab} -> {num2}: tab click took {num5:F2} ms");
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not switch build-menu tab: " + ex.GetBaseException().Message));
			}
		}

		private static string? GetTextInputBlocker(BuildUi? ui)
		{
			if (UnifiedPopup.IsVisible())
			{
				return "a popup";
			}
			if (Console.IsVisible())
			{
				return "the console";
			}
			if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus())
			{
				return "chat";
			}
			if (TextInput.IsVisible())
			{
				return "a text input window";
			}
			if (Minimap.InTextInput())
			{
				return "map text input";
			}
			if ((Object)(object)ui != (Object)null && ui.SearchFieldFocused)
			{
				return "the build menu filter field";
			}
			return null;
		}

		private static bool HasEquippedCraftingHammer(Player player)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return false;
			}
			foreach (ItemData item in inventory.GetAllItemsInGridOrder())
			{
				if (item != null && item.m_equipped && IsCraftingHammer(item))
				{
					return true;
				}
			}
			return false;
		}

		private void InstallPatches()
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Expected O, but got Unknown
			//IL_0158: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Expected O, but got Unknown
			if (BuildUiType == null)
			{
				throw new MissingMemberException("Could not find game type BuildUi.");
			}
			MethodInfo methodInfo = AccessTools.Method(BuildUiType, "UpdateTagButtons", new Type[1] { typeof(bool) }, (Type[])null) ?? throw new MissingMethodException("BuildUi.UpdateTagButtons not found.");
			MethodInfo methodInfo2 = AccessTools.Method(BuildUiType, "UpdatePieceButtons", (Type[])null, (Type[])null) ?? throw new MissingMethodException("BuildUi.UpdatePieceButtons not found.");
			MethodInfo methodInfo3 = AccessTools.Method(BuildUiType, "NavigationUpdate", (Type[])null, (Type[])null) ?? throw new MissingMethodException("BuildUi.NavigationUpdate not found.");
			_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(BuildMenuQOLPlugin), "UpdateTagButtonsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(BuildMenuQOLPlugin), "UpdatePieceButtonsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(BuildMenuQOLPlugin), "NavigationUpdateTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(TabHandler), "Update", (Type[])null, (Type[])null);
			if (methodInfo4 != null)
			{
				_harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(BuildMenuQOLPlugin), "TabHandlerUpdatePrefix", (Type[])null), new HarmonyMethod(typeof(BuildMenuQOLPlugin), "TabHandlerUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Dbg("Installed TabHandler keyboard-navigation interception.");
			}
			else
			{
				Log.LogWarning((object)"Could not find TabHandler.Update; vanilla tab-key interception was not installed.");
			}
			MethodInfo methodInfo5 = AccessTools.Method(typeof(InventoryGui), "Update", (Type[])null, (Type[])null);
			if (methodInfo5 != null && ZInputButton != null && ZInputButtonDown != null && ZInputResetButton != null)
			{
				_harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(BuildMenuQOLPlugin), "InventoryGuiUpdatePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Dbg("Installed the controller repair combo (Alt + Y).");
			}
			else
			{
				Log.LogWarning((object)"Could not hook InventoryGui.Update or the ZInput button API; the controller repair combo was not installed.");
			}
		}

		private static void TabHandlerUpdatePrefix(TabHandler __instance, ref bool __state)
		{
			__state = false;
			if (__instance == _tabHandler && __instance.m_keybaordInput)
			{
				__instance.m_keybaordInput = false;
				__state = true;
			}
		}

		private static void TabHandlerUpdatePostfix(TabHandler __instance, bool __state)
		{
			if (__state)
			{
				__instance.m_keybaordInput = true;
			}
		}

		private static void UpdateTagButtonsPostfix(object __instance)
		{
			CacheBuildUi(__instance);
			if (IsRecentTab(__instance))
			{
				object obj = CurrentBuildToolField?.GetValue(__instance);
				if (obj != null && !IsAdvancedMenuHidden(obj))
				{
					SetTagListActiveMethod?.Invoke(__instance, new object[2] { true, true });
				}
			}
		}

		private static void UpdatePieceButtonsPostfix(object __instance)
		{
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Expected O, but got Unknown
			CacheBuildUi(__instance);
			object? obj = SearchFieldField?.GetValue(__instance);
			Component val = (Component)((obj is Component) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				EnsureFilterBadge(val);
			}
			if (!IsRecentTab(__instance))
			{
				if ((Object)(object)val != (Object)null)
				{
					object? obj2 = SpecialPieceButtonField?.GetValue(__instance);
					Component val2 = (Component)((obj2 is Component) ? obj2 : null);
					if (val2 != null)
					{
						CreateRepairHotkeyBadge(val2.gameObject, val);
					}
				}
				return;
			}
			object obj3 = CurrentBuildToolField?.GetValue(__instance);
			if (obj3 == null || IsAdvancedMenuHidden(obj3) || !(AccessTools.Field(obj3.GetType(), "m_availablePieces")?.GetValue(obj3) is IEnumerable<Piece> source))
			{
				return;
			}
			Piece val3 = source.FirstOrDefault((Func<Piece, bool>)((Piece piece) => (Object)(object)piece != (Object)null && piece.m_repairPiece));
			if ((Object)(object)val3 == (Object)null && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				val3 = Player.m_localPlayer.GetBuildPieces()?.FirstOrDefault((Func<Piece, bool>)((Piece piece) => (Object)(object)piece != (Object)null && piece.m_repairPiece));
			}
			if ((Object)(object)val3 == (Object)null)
			{
				return;
			}
			object? obj4 = SpecialPieceButtonField?.GetValue(__instance);
			BuildUiPieceButton val4 = (BuildUiPieceButton)((obj4 is BuildUiPieceButton) ? obj4 : null);
			if (val4 != null)
			{
				val4.Setup(val3, (BuildUi)__instance);
				((Component)val4).gameObject.SetActive(true);
				object? obj5 = SpecialButtonsContainerField?.GetValue(__instance);
				Transform val5 = (Transform)((obj5 is Transform) ? obj5 : null);
				if (val5 != null)
				{
					((Component)val5).gameObject.SetActive(true);
				}
				CreateRepairHotkeyBadge(((Component)val4).gameObject, val);
				ConfigureButtonNavigationMethod?.Invoke(__instance, null);
				return;
			}
			object? obj6 = PieceButtonPrefabField?.GetValue(__instance);
			GameObject val6 = (GameObject)((obj6 is GameObject) ? obj6 : null);
			if (val6 != null)
			{
				object? obj7 = SpecialButtonsContainerField?.GetValue(__instance);
				Transform val7 = (Transform)((obj7 is Transform) ? obj7 : null);
				if (val7 != null)
				{
					GameObject val8 = Object.Instantiate<GameObject>(val6, val7);
					val8.transform.SetAsFirstSibling();
					BuildUiPieceButton component = val8.GetComponent<BuildUiPieceButton>();
					if ((Object)(object)component == (Object)null)
					{
						Object.Destroy((Object)(object)val8);
						Log.LogWarning((object)"Vanilla special-button prefab has no BuildUiPieceButton.");
						return;
					}
					component.Setup(val3, (BuildUi)__instance);
					val8.SetActive(true);
					((Component)val7).gameObject.SetActive(true);
					SpecialPieceButtonField?.SetValue(__instance, component);
					CreateRepairHotkeyBadge(val8, val);
					ConfigureButtonNavigationMethod?.Invoke(__instance, null);
					return;
				}
			}
			Log.LogWarning((object)"Couldn't access the vanilla special-button prefab/container.");
		}

		private static void SyncBadges(BuildUi ui)
		{
			if (Time.unscaledTime >= _nextLanguageCheck)
			{
				_nextLanguageCheck = Time.unscaledTime + 1f;
				if (!string.Equals(CurrentLanguage(), _textLanguage, StringComparison.Ordinal))
				{
					RefreshShortcutText();
				}
			}
			ApplyBadge(_filterBadge, _filterText, ShowFilterHotkeyBadge.Value, toggleRoot: false);
			if (_repairBadge != null && (Object)(object)_repairBadge.Root != (Object)null)
			{
				if ((Object)(object)_repairButtonTransform != (Object)null)
				{
					PositionRepairBadge(((Component)_repairButtonTransform).gameObject);
				}
				ApplyBadge(_repairBadge, _repairText, ShowRepairHotkeyBadge.Value && KeyboardHintsActive(), toggleRoot: true);
			}
			EnsureTabBadges(ui);
			bool value = ShowTabSwitchHotkeyBadges.Value;
			ApplyBadge(_previousTabBadge, _previousTabText, value, toggleRoot: false);
			ApplyBadge(_nextTabBadge, _nextTabText, value, toggleRoot: false);
		}

		private static void ApplyBadge(BadgeVisuals? badge, string text, bool visible, bool toggleRoot)
		{
			if (badge == null || (Object)(object)badge.Root == (Object)null)
			{
				return;
			}
			if (toggleRoot && badge.Root.activeSelf != visible)
			{
				badge.Root.SetActive(visible);
			}
			foreach (Behaviour visual in badge.Visuals)
			{
				if ((Object)(object)visual != (Object)null && visual.enabled != visible)
				{
					visual.enabled = visible;
				}
			}
			if (!visible)
			{
				return;
			}
			foreach (KeyValuePair<Component, PropertyInfo> text2 in badge.Texts)
			{
				if ((Object)(object)text2.Key == (Object)null)
				{
					continue;
				}
				try
				{
					if (text2.Value.GetValue(text2.Key) as string != text)
					{
						text2.Value.SetValue(text2.Key, text);
					}
				}
				catch
				{
				}
			}
		}

		private static void EnsureFilterBadge(Component searchField)
		{
			if (_filterField != searchField || _filterBadge == null || !((Object)(object)_filterBadge.Root != (Object)null))
			{
				_filterField = searchField;
				Transform val = FindChildByName(searchField.transform, "Mouse");
				_filterBadge = (((Object)(object)val != (Object)null) ? new BadgeVisuals(((Component)val).gameObject) : null);
			}
		}

		private static void CreateRepairHotkeyBadge(GameObject repairButton, Component? searchField)
		{
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)searchField == (Object)null || (Object)(object)repairButton == (Object)null)
			{
				return;
			}
			Transform parent = repairButton.transform.parent;
			if ((Object)(object)parent == (Object)null)
			{
				return;
			}
			if (_repairBadge != null && (Object)(object)_repairBadge.Root != (Object)null && (Object)(object)_repairButtonTransform == (Object)(object)repairButton.transform && (Object)(object)_repairBadge.Root.transform.parent == (Object)(object)parent)
			{
				PositionRepairBadge(repairButton);
				return;
			}
			if (_repairBadge != null && (Object)(object)_repairBadge.Root != (Object)null)
			{
				Object.Destroy((Object)(object)_repairBadge.Root);
			}
			_repairBadge = null;
			_repairButtonTransform = null;
			Transform val = FindChildByName(searchField.transform, "Mouse");
			if ((Object)(object)val == (Object)null)
			{
				Log.LogWarning((object)"Couldn't find the Filter field's keyboard badge to copy its style.");
				return;
			}
			GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, parent, false);
			((Object)val2).name = "BuildMenuQOLRepairHotkeyBadge";
			val2.SetActive(true);
			Transform[] componentsInChildren = val2.GetComponentsInChildren<Transform>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Component)componentsInChildren[i]).gameObject.SetActive(true);
			}
			Behaviour[] componentsInChildren2 = val2.GetComponentsInChildren<Behaviour>(true);
			foreach (Behaviour val3 in componentsInChildren2)
			{
				if (((object)val3).GetType().Name.Contains("UIInputHint"))
				{
					val3.enabled = false;
				}
			}
			Transform transform = val2.transform;
			RectTransform val4 = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if (val4 != null)
			{
				RectTransform val5 = (RectTransform)(object)((val is RectTransform) ? val : null);
				if (val5 != null)
				{
					val4.sizeDelta = val5.sizeDelta;
				}
				((Transform)val4).localScale = Vector3.one;
			}
			_repairBadge = new BadgeVisuals(val2);
			_repairButtonTransform = repairButton.transform;
			PositionRepairBadge(repairButton);
			val2.transform.SetAsLastSibling();
			ApplyBadge(_repairBadge, _repairText, ShowRepairHotkeyBadge.Value && KeyboardHintsActive(), toggleRoot: true);
			Dbg("Created the Repair hotkey badge.");
		}

		private static void PositionRepairBadge(GameObject repairButton)
		{
			//IL_0053: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			if (_repairBadge == null || (Object)(object)_repairBadge.Root == (Object)null)
			{
				return;
			}
			Transform transform = _repairBadge.Root.transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if (val != null)
			{
				Transform transform2 = repairButton.transform;
				RectTransform val2 = (RectTransform)(object)((transform2 is RectTransform) ? transform2 : null);
				if (val2 != null)
				{
					val2.GetWorldCorners(WorldCorners);
					((Transform)val).position = WorldCorners[1] + new Vector3(-12f, 12f, 0f);
					((Transform)val).SetAsLastSibling();
				}
			}
		}

		private static void EnsureTabBadges(BuildUi ui)
		{
			if ((_previousTabBadge == null || !((Object)(object)_previousTabBadge.Root != (Object)null) || _nextTabBadge == null || !((Object)(object)_nextTabBadge.Root != (Object)null)) && _tabBadgeAttempts < 3 && !(Time.unscaledTime < _nextTabBadgeSearch))
			{
				_nextTabBadgeSearch = Time.unscaledTime + 1f;
				_tabBadgeAttempts++;
				CacheTabHotkeyBadges(ui);
				if (_tabBadgeAttempts >= 3 && (_previousTabBadge == null || _nextTabBadge == null))
				{
					Log.LogWarning((object)"Could not locate the tab-switch hotkey badges; they will keep showing the vanilla keys. Enable VerboseLogging for details.");
				}
			}
		}

		private static void CacheTabHotkeyBadges(BuildUi ui)
		{
			Component val = FindTabInputHint(ui);
			if ((Object)(object)val == (Object)null)
			{
				Dbg("Tab badge discovery: no UIInputHint found for the tab bar.");
				return;
			}
			GameObject hintObject = GetHintObject(val, "m_mouseKeyboardHint");
			GameObject hintObject2 = GetHintObject(val, "m_gamepadHint");
			GameObject hintObject3 = GetHintObject(val, "m_gamepadMouseHint");
			Transform val2 = (((Object)(object)hintObject != (Object)null) ? hintObject.transform : val.transform);
			if (VerboseLogging.Value)
			{
				string text = (((Object)(object)hintObject != (Object)null) ? ((Object)hintObject).name : "none");
				Dbg("Tab badge discovery: hint at " + GetPath(val.transform) + "; keyboard hint object: " + text);
				DumpHierarchy(val2);
			}
			List<Component> list = new List<Component>();
			Component[] componentsInChildren = ((Component)val2).GetComponentsInChildren<Component>(true);
			foreach (Component val3 in componentsInChildren)
			{
				if (!((Object)(object)val3 == (Object)null) && TryGetTextProperty(((object)val3).GetType(), out PropertyInfo _))
				{
					Transform transform = val3.transform;
					if ((!((Object)(object)hintObject2 != (Object)null) || !transform.IsChildOf(hintObject2.transform)) && (!((Object)(object)hintObject3 != (Object)null) || !transform.IsChildOf(hintObject3.transform)))
					{
						list.Add(val3);
					}
				}
			}
			if (list.Count < 2)
			{
				Dbg($"Tab badge discovery found {list.Count} text element(s) under the tab hint; expected at least 2.");
				return;
			}
			list.Sort((Component a, Component b) => a.transform.position.x.CompareTo(b.transform.position.x));
			Transform transform2 = list[0].transform;
			Transform transform3 = list[list.Count - 1].transform;
			Transform val4 = ClimbToBadgeRoot(transform2, transform3, val2);
			Transform val5 = ClimbToBadgeRoot(transform3, transform2, val2);
			if ((Object)(object)val4 == (Object)(object)val5)
			{
				Dbg("Tab badge discovery could not separate the previous and next badges.");
				return;
			}
			_previousTabBadge = new BadgeVisuals(((Component)val4).gameObject);
			_nextTabBadge = new BadgeVisuals(((Component)val5).gameObject);
			Dbg("Cached tab badges. Previous: " + GetPath(val4) + "; Next: " + GetPath(val5));
		}

		private static Component? FindTabInputHint(BuildUi ui)
		{
			if (InputHintType == null)
			{
				return null;
			}
			Component[] componentsInChildren = ((Component)ui).GetComponentsInChildren(InputHintType, true);
			foreach (Component val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && (((Object)val).name == "InputHelp" || IsUnder(val.transform, "TabContainer")))
				{
					return val;
				}
			}
			return null;
		}

		private static GameObject? GetHintObject(Component hint, string fieldName)
		{
			object? obj = ((InputHintType == null) ? null : AccessTools.Field(InputHintType, fieldName))?.GetValue(hint);
			return (GameObject?)((obj is GameObject) ? obj : null);
		}

		private static bool IsUnder(Transform node, string ancestorName)
		{
			Transform parent = node.parent;
			while ((Object)(object)parent != (Object)null)
			{
				if (((Object)parent).name == ancestorName)
				{
					return true;
				}
				parent = parent.parent;
			}
			return false;
		}

		private static Transform ClimbToBadgeRoot(Transform text, Transform other, Transform limit)
		{
			Transform val = text;
			while ((Object)(object)val.parent != (Object)null && (Object)(object)val.parent != (Object)(object)limit && !other.IsChildOf(val.parent))
			{
				val = val.parent;
			}
			return val;
		}

		private static bool KeyboardHintsActive()
		{
			if (IsGamepadActive == null || IsMouseActive == null)
			{
				return true;
			}
			if (!IsGamepadActive())
			{
				return IsMouseActive();
			}
			return false;
		}

		private static Func<KeyCode, bool>? MakeZInputKeyDelegate(Type? type, string methodName)
		{
			if (type == null)
			{
				return null;
			}
			MethodInfo methodInfo = AccessTools.Method(type, methodName, new Type[1] { typeof(KeyCode) }, (Type[])null);
			if (methodInfo != null && methodInfo.IsStatic && methodInfo.ReturnType == typeof(bool))
			{
				return (Func<KeyCode, bool>)Delegate.CreateDelegate(typeof(Func<KeyCode, bool>), methodInfo);
			}
			MethodInfo methodInfo2 = AccessTools.Method(type, methodName, new Type[2]
			{
				typeof(KeyCode),
				typeof(bool)
			}, (Type[])null);
			if (methodInfo2 != null && methodInfo2.IsStatic && methodInfo2.ReturnType == typeof(bool))
			{
				Func<KeyCode, bool, bool> d = (Func<KeyCode, bool, bool>)Delegate.CreateDelegate(typeof(Func<KeyCode, bool, bool>), methodInfo2);
				return (KeyCode key) => d(key, arg2: false);
			}
			return null;
		}

		private static bool ModifiersHeldViaGame(KeyboardShortcut shortcut)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref shortcut)).Modifiers)
			{
				if (!ZInputKeyHeld(modifier))
				{
					return false;
				}
			}
			return true;
		}

		internal static bool ShortcutDown(KeyboardShortcut shortcut)
		{
			//IL_001b: 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_0038: 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)
			if (((KeyboardShortcut)(ref shortcut)).IsDown())
			{
				return true;
			}
			if (ZInputKeyDown == null || ZInputKeyHeld == null || (int)((KeyboardShortcut)(ref shortcut)).MainKey == 0)
			{
				return false;
			}
			try
			{
				if (!ZInputKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey) || !ModifiersHeldViaGame(shortcut))
				{
					return false;
				}
			}
			catch
			{
				return false;
			}
			if (_fallbackWarnings < 5)
			{
				_fallbackWarnings++;
				Log.LogWarning((object)$"Legacy input missed '{shortcut}' but the game's input saw it; using the game's input (warning {_fallbackWarnings}/5).");
			}
			return true;
		}

		internal static bool ShortcutPressed(KeyboardShortcut shortcut)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			if (((KeyboardShortcut)(ref shortcut)).IsPressed())
			{
				return true;
			}
			if (ZInputKeyHeld == null || (int)((KeyboardShortcut)(ref shortcut)).MainKey == 0)
			{
				return false;
			}
			try
			{
				return ZInputKeyHeld(((KeyboardShortcut)(ref shortcut)).MainKey) && ModifiersHeldViaGame(shortcut);
			}
			catch
			{
				return false;
			}
		}

		private static Func<bool>? MakeStaticBoolDelegate(Type? type, string methodName)
		{
			if (type == null)
			{
				return null;
			}
			MethodInfo methodInfo = AccessTools.Method(type, methodName, Type.EmptyTypes, (Type[])null);
			if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(bool))
			{
				return null;
			}
			return (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo);
		}

		private static bool TryGetTextProperty(Type type, out PropertyInfo property)
		{
			property = null;
			PropertyInfo property2;
			try
			{
				property2 = type.GetProperty("text", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			}
			catch (AmbiguousMatchException)
			{
				return false;
			}
			if (property2 == null || property2.PropertyType != typeof(string) || property2.GetIndexParameters().Length != 0 || !property2.CanRead || !property2.CanWrite)
			{
				return false;
			}
			property = property2;
			return true;
		}

		private static string? ReadText(Component component)
		{
			if (!TryGetTextProperty(((object)component).GetType(), out PropertyInfo property))
			{
				return null;
			}
			try
			{
				return property.GetValue(component) as string;
			}
			catch
			{
				return null;
			}
		}

		private static void DumpHierarchy(Transform node, int depth = 0)
		{
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			if (!VerboseLogging.Value || depth > 8)
			{
				return;
			}
			List<string> list = new List<string>();
			Component[] components = ((Component)node).GetComponents<Component>();
			foreach (Component val in components)
			{
				if (!((Object)(object)val == (Object)null))
				{
					string text = ((object)val).GetType().Name;
					string text2 = ReadText(val);
					if (text2 != null)
					{
						text = text + "(\"" + text2 + "\")";
					}
					list.Add(text);
				}
			}
			string text3 = (((Component)node).gameObject.activeSelf ? "" : " [inactive]");
			Dbg("  " + new string(' ', depth * 2) + ((Object)node).name + text3 + ": " + string.Join(", ", list));
			foreach (Transform item in node)
			{
				DumpHierarchy(item, depth + 1);
			}
		}

		private static string GetPath(Transform transform)
		{
			List<string> list = new List<string>();
			Transform val = transform;
			while ((Object)(object)val != (Object)null)
			{
				list.Add(((Object)val).name);
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}

		private static Transform? FindChildByName(Transform root, string name)
		{
			Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (((Object)val).name == name)
				{
					return val;
				}
			}
			return null;
		}

		private static string CurrentLanguage()
		{
			try
			{
				object obj = LocalizationInstanceProperty?.GetValue(null);
				if (obj == null || GetSelectedLanguageMethod == null)
				{
					return "";
				}
				return (GetSelectedLanguageMethod.Invoke(obj, null) as string) ?? "";
			}
			catch
			{
				return "";
			}
		}

		private unsafe static string? LocalizedKeyName(KeyCode key)
		{
			if (!KeyLocalizationTokens.TryGetValue(((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString(), out string value))
			{
				return null;
			}
			return LocalizeToken(value);
		}

		private static string? LocalizeToken(string token)
		{
			string text = CurrentLanguage();
			if (text.Length == 0 || text.Equals("English", StringComparison.OrdinalIgnoreCase))
			{
				return null;
			}
			try
			{
				object obj = LocalizationInstanceProperty?.GetValue(null);
				if (obj == null || LocalizeMethod == null)
				{
					return null;
				}
				string text2 = LocalizeMethod.Invoke(obj, new object[1] { token }) as string;
				if (string.IsNullOrEmpty(text2) || text2.StartsWith("[", StringComparison.Ordinal) || text2.IndexOf('$') >= 0)
				{
					return null;
				}
				return text2;
			}
			catch
			{
				return null;
			}
		}

		private unsafe static string FormatShortcut(KeyboardShortcut shortcut)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected I4, but got Unknown
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			foreach (KeyCode item2 in ((KeyboardShortcut)(ref shortcut)).Modifiers.OrderBy((KeyCode key) => ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString()))
			{
				string text = LocalizedKeyName(item2);
				if (text == null)
				{
					string text2;
					switch (item2 - 303)
					{
					case 2:
					case 3:
						text2 = "Ctrl";
						break;
					case 0:
					case 1:
						text2 = "Shift";
						break;
					case 4:
					case 5:
						text2 = "Alt";
						break;
					default:
						text2 = ((object)(*(KeyCode*)(&item2))/*cast due to .constrained prefix*/).ToString();
						break;
					}
					text = text2;
				}
				string item = text;
				if (!list.Contains(item))
				{
					list.Add(item);
				}
			}
			list.Add(FormatKeyName(((KeyboardShortcut)(ref shortcut)).MainKey));
			return string.Join(" + ", list);
		}

		private unsafe static string FormatKeyName(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			string text = LocalizedKeyName(key);
			if (text != null)
			{
				return text;
			}
			string text2 = ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString();
			if (KeySymbols.TryGetValue(text2, out string value))
			{
				return value;
			}
			if (KeyShortNames.TryGetValue(text2, out string value2))
			{
				return value2;
			}
			if (text2.StartsWith("Alpha", StringComparison.Ordinal))
			{
				return text2.Substring(5);
			}
			if (text2.StartsWith("Keypad", StringComparison.Ordinal))
			{
				string text3 = text2.Substring(6);
				return "Num " + text3 switch
				{
					"Period" => ".", 
					"Divide" => "/", 
					"Multiply" => "*", 
					"Minus" => "-", 
					"Plus" => "+", 
					"Equals" => "=", 
					_ => text3, 
				};
			}
			if (text2.StartsWith("Mouse", StringComparison.Ordinal) && int.TryParse(text2.Substring(5), out var result))
			{
				return result switch
				{
					0 => "LMB", 
					1 => "RMB", 
					2 => "MMB", 
					_ => "Mouse " + (result + 1), 
				};
			}
			return text2;
		}

		private static bool IsRecentTab(object buildUi)
		{
			if (PieceListsField?.GetValue(buildUi) is IList list && CurrentPieceListField?.GetValue(buildUi) is int num)
			{
				object obj = RecentPieceListField?.GetValue(buildUi);
				if (obj != null)
				{
					if (num >= 0 && num < list.Count)
					{
						return list[num] == obj;
					}
					return false;
				}
			}
			return false;
		}

		private static bool IsAdvancedMenuHidden(object buildTool)
		{
			object obj = AccessTools.Field(buildTool.GetType(), "m_hideAdvancedMenu")?.GetValue(buildTool);
			bool flag = default(bool);
			int num;
			if (obj is bool)
			{
				flag = (bool)obj;
				num = 1;
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}

		private static IEnumerable<CodeInstruction> NavigationUpdateTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			Type type = AccessTools.TypeByName("ZInput");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "GetKey", new Type[2]
			{
				typeof(KeyCode),
				typeof(bool)
			}, (Type[])null));
			MethodInfo operand = AccessTools.Method(typeof(BuildMenuQOLPlugin), "IsConfiguredFilterShortcutPressed", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogWarning((object)"Could not find ZInput.GetKey(KeyCode, bool); Filter hotkey remains vanilla.");
				return instructions;
			}
			List<CodeInstruction> list = instructions.ToList();
			int num = 0;
			for (int i = 2; i < list.Count; i++)
			{
				if (list[i - 1].opcode == OpCodes.Ldc_I4_1 && list[i].operand is MethodInfo methodInfo2 && methodInfo2 == methodInfo && IsKeyCodeConstant(list[i - 2], (KeyCode)102))
				{
					list[i].operand = operand;
					num++;
				}
			}
			Dbg($"Filter shortcut transpiler replaced {num} key check(s).");
			if (num == 0)
			{
				Log.LogWarning((object)"Filter shortcut transpiler found no key check to replace; Filter hotkey remains vanilla.");
			}
			return list;
		}

		private static bool IsKeyCodeConstant(CodeInstruction instruction, KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Expected I4, but got Unknown
			int num = (int)key;
			if (instruction.opcode == OpCodes.Ldc_I4_S)
			{
				if (instruction.operand is sbyte b)
				{
					return b == num;
				}
				if (instruction.operand is byte b2)
				{
					return b2 == num;
				}
				if (instruction.operand is int num2)
				{
					return num2 == num;
				}
			}
			if (instruction.opcode == OpCodes.Ldc_I4 && instruction.operand is int num3)
			{
				return num3 == num;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_M1)
			{
				return num == -1;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_0)
			{
				return num == 0;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_1)
			{
				return num == 1;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_2)
			{
				return num == 2;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_3)
			{
				return num == 3;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_4)
			{
				return num == 4;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_5)
			{
				return num == 5;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_6)
			{
				return num == 6;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_7)
			{
				return num == 7;
			}
			if (instruction.opcode == OpCodes.Ldc_I4_8)
			{
				return num == 8;
			}
			return false;
		}

		private static bool IsConfiguredFilterShortcutPressed(KeyCode _, bool __)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (FilterHotkey != null)
			{
				return ShortcutPressed(FilterHotkey.Value);
			}
			return false;
		}
	}
}