Decompiled source of CDEV RebindFavoriteKey v0.1.0

plugins\CDEV.RebindFavoriteKey\CDEV.RebindFavoriteKey.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Valheim.SettingsGui;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("CDEV.RebindFavoriteKey")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+dc973356a9e1d4377ae0cec010ca435f57d87290")]
[assembly: AssemblyProduct("CDEV.RebindFavoriteKey")]
[assembly: AssemblyTitle("CDEV.RebindFavoriteKey")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[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 CDEV.RebindFavoriteKey
{
	internal static class FavoriteButton
	{
		[HarmonyPatch(typeof(ZInput), "Reset")]
		private static class Register
		{
			private static void Postfix(ZInput __instance)
			{
				Add(__instance);
			}
		}

		internal const string Name = "CDEV_FavoritePiece";

		private const string VanillaMiddleMouse = "MouseMiddle";

		private static void Add(ZInput input)
		{
			//IL_002a: 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)
			try
			{
				if (input?.m_buttons != null && !input.m_buttons.ContainsKey("CDEV_FavoritePiece"))
				{
					string text = ZInput.KeyCodeToPath(ModConfig.DefaultKey.Value, false);
					if (string.IsNullOrEmpty(text))
					{
						RebindFavoriteKeyPlugin.Log.LogWarning((object)$"No input path for {ModConfig.DefaultKey.Value}; falling back to {(object)(KeyCode)102}.");
						text = ZInput.KeyCodeToPath((KeyCode)102, false);
					}
					input.AddButton("CDEV_FavoritePiece", text, false, true, true, 0f, 0f);
				}
			}
			catch (Exception ex)
			{
				RebindFavoriteKeyPlugin.Log.LogError((object)("Could not register the favorite key: " + ex));
			}
		}

		internal static bool CollidesWithVanillaClick()
		{
			if (!ModConfig.MiddleClickFavorite.Value || ZInput.instance == null)
			{
				return false;
			}
			string boundKeyString = ZInput.instance.GetBoundKeyString("CDEV_FavoritePiece", true);
			if (!string.IsNullOrEmpty(boundKeyString))
			{
				return boundKeyString == ZInput.instance.GetBoundKeyString("MouseMiddle", true);
			}
			return false;
		}
	}
	internal static class ModConfig
	{
		internal static ConfigEntry<KeyCode> DefaultKey;

		internal static ConfigEntry<bool> MiddleClickFavorite;

		internal static void Bind(ConfigFile config)
		{
			DefaultKey = config.Bind<KeyCode>("Keys", "DefaultKey", (KeyCode)102, "The key that favorites the piece under the cursor in the build menu, before it is rebound. Rebind it in the game's own Settings -> Controls (row \"Favorite piece\"); changing it here after that does nothing, because the game then has a binding of its own saved for it.");
			MiddleClickFavorite = config.Bind<bool>("Keys", "MiddleClickFavorite", true, "Keep the vanilla middle click on a piece as \"add to favorites\". Switch it off to free the middle mouse button; the key above keeps working either way.");
		}
	}
	[BepInPlugin("cdev.rebindfavoritekey", "CDEV.RebindFavoriteKey", "0.1.0")]
	[BepInProcess("valheim.exe")]
	public sealed class RebindFavoriteKeyPlugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("cdev.rebindfavoritekey");
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class Texts
	{
		private static bool Ru
		{
			get
			{
				if (Localization.instance != null)
				{
					return Localization.instance.GetSelectedLanguage() == "Russian";
				}
				return false;
			}
		}

		internal static string RowLabel
		{
			get
			{
				if (!Ru)
				{
					return "Favorite piece (build menu)";
				}
				return "В избранное (меню постройки)";
			}
		}
	}
	internal static class BuildInfo
	{
		public const string Name = "CDEV.RebindFavoriteKey";

		public const string Guid = "cdev.rebindfavoritekey";

		public const string Version = "0.1.0";
	}
}
namespace CDEV.RebindFavoriteKey.UI
{
	internal static class SettingsRow
	{
		[HarmonyPatch(typeof(KeyboardMouseSettings), "Initialize")]
		private static class AddRow
		{
			private static void Prefix(KeyboardMouseSettings __instance)
			{
				Add(__instance);
			}
		}

		[HarmonyPatch(typeof(KeyboardMouseSettings), "UpdateBindings")]
		private static class KeepLabel
		{
			private static void Postfix()
			{
				if ((Object)(object)_label != (Object)null)
				{
					_label.text = Texts.RowLabel;
				}
			}
		}

		private static TMP_Text _label;

		private static void Add(KeyboardMouseSettings settings)
		{
			//IL_00ca: 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)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Expected O, but got Unknown
			try
			{
				if (settings?.m_keys == null || settings.m_keys.Count == 0)
				{
					return;
				}
				foreach (KeySetting key in settings.m_keys)
				{
					if (key != null && key.m_keyName == "CDEV_FavoritePiece")
					{
						return;
					}
				}
				KeySetting val = settings.m_keys.Find((KeySetting key) => (Object)(object)key?.m_keyTransform != (Object)null);
				if (val == null)
				{
					return;
				}
				Transform parent = ((Transform)val.m_keyTransform).parent;
				RectTransform val2 = (RectTransform)(object)((parent is RectTransform) ? parent : null);
				if (val2 == null)
				{
					return;
				}
				GridLayoutGroup component = ((Component)val2).GetComponent<GridLayoutGroup>();
				if ((Object)(object)component == (Object)null)
				{
					return;
				}
				float num = component.cellSize.y + component.spacing.y;
				int num2 = RowsPerColumn(val2, num);
				if (num2 <= 0)
				{
					return;
				}
				val2.sizeDelta += new Vector2(0f, num);
				settings.m_keyRows = num2 + 1;
				RectTransform val3 = Object.Instantiate<RectTransform>(val.m_keyTransform, (Transform)(object)val2);
				((Object)val3).name = "CDEV_FavoritePiece";
				int num3 = SiblingOfActive(val2, num2);
				((Transform)val3).SetSiblingIndex(num3);
				Button componentInChildren = ((Component)val3).GetComponentInChildren<Button>(true);
				if ((Object)(object)componentInChildren == (Object)null)
				{
					Object.Destroy((Object)(object)((Component)val3).gameObject);
					val2.sizeDelta -= new Vector2(0f, num);
					settings.m_keyRows = num2;
					return;
				}
				((UnityEventBase)componentInChildren.onClick).RemoveAllListeners();
				TMP_Text componentInChildren2 = ((Component)componentInChildren).GetComponentInChildren<TMP_Text>(true);
				TMP_Text[] componentsInChildren = ((Component)val3).GetComponentsInChildren<TMP_Text>(true);
				foreach (TMP_Text val4 in componentsInChildren)
				{
					if ((Object)(object)val4 != (Object)(object)componentInChildren2)
					{
						_label = val4;
						_label.text = Texts.RowLabel;
						break;
					}
				}
				KeySetting item = new KeySetting
				{
					m_keyName = "CDEV_FavoritePiece",
					m_keyTransform = val3,
					m_blockedButtons = val.m_blockedButtons
				};
				int num5 = Mathf.Min(IndexOfSibling(settings.m_keys, num3), settings.m_keys.Count);
				settings.m_keys.Insert(num5, item);
				RebindFavoriteKeyPlugin.Log.LogDebug((object)$"Key row added as {num5 + 1} of {settings.m_keys.Count} ({settings.m_keyRows} per column).");
			}
			catch (Exception ex)
			{
				RebindFavoriteKeyPlugin.Log.LogError((object)("Could not add the settings row: " + ex));
			}
		}

		private static int RowsPerColumn(RectTransform grid, float step)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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)
			if (step <= 0f)
			{
				return 0;
			}
			GridLayoutGroup component = ((Component)grid).GetComponent<GridLayoutGroup>();
			Rect rect = grid.rect;
			float num = ((Rect)(ref rect)).height - (float)((LayoutGroup)component).padding.top - (float)((LayoutGroup)component).padding.bottom;
			return Mathf.Max(1, Mathf.FloorToInt((num + component.spacing.y) / step));
		}

		private static int SiblingOfActive(RectTransform grid, int activeRows)
		{
			int num = 0;
			for (int i = 0; i < ((Transform)grid).childCount; i++)
			{
				Transform child = ((Transform)grid).GetChild(i);
				if (((Component)child).gameObject.activeSelf && ++num == activeRows)
				{
					return i + 1;
				}
			}
			return ((Transform)grid).childCount;
		}

		private static int IndexOfSibling(List<KeySetting> keys, int sibling)
		{
			for (int i = 0; i < keys.Count; i++)
			{
				RectTransform val = keys[i]?.m_keyTransform;
				if ((Object)(object)val != (Object)null && ((Transform)val).GetSiblingIndex() >= sibling)
				{
					return i;
				}
			}
			return keys.Count;
		}
	}
}
namespace CDEV.RebindFavoriteKey.Patches
{
	internal static class BuildUiPatches
	{
		[HarmonyPatch(typeof(BuildUi), "Update")]
		private static class ReadKey
		{
			private static void Postfix(BuildUi __instance)
			{
				try
				{
					if (ZInput.GetButtonDown("CDEV_FavoritePiece") && !FavoriteButton.CollidesWithVanillaClick())
					{
						BuildUiPieceButton currentHoveredPieceButton = __instance.m_currentHoveredPieceButton;
						if (!((Object)(object)currentHoveredPieceButton == (Object)null) && !((Object)(object)currentHoveredPieceButton.Piece == (Object)null))
						{
							__instance.PressedFavoriteButton(currentHoveredPieceButton);
						}
					}
				}
				catch (Exception ex)
				{
					RebindFavoriteKeyPlugin.Log.LogError((object)("Favoriting a piece by key failed: " + ex));
				}
			}
		}

		[HarmonyPatch(typeof(BuildUiPieceButton), "OnMiddleClick")]
		private static class MiddleClick
		{
			private static bool Prefix()
			{
				return ModConfig.MiddleClickFavorite.Value;
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}