Decompiled source of EasyHotbarOrganization v1.0.0

plugins/EasyHotbarOrganization/EasyHotbarOrganization.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FishNet.Object;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Samples.RebindUI;
using UnityEngine.Localization;
using UnityEngine.Localization.Components;
using UnityEngine.Localization.Settings;
using UnityEngine.UI;

[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("EasyHotbarOrganization")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+10fdf42a38ab71a3cb693ab628dc0af6878e609b")]
[assembly: AssemblyProduct("EasyHotbarOrganization")]
[assembly: AssemblyTitle("EasyHotbarOrganization")]
[assembly: AssemblyVersion("1.0.0.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 EasyHotbarOrganization
{
	public class HotbarRow : MonoBehaviour
	{
		public Transform Source;
	}
	public static class ControlsMenu
	{
		private const string TemplateAction = "ChangeBait";

		private static readonly FieldInfo ActionField = AccessTools.Field(typeof(RebindActionUI), "m_Action");

		private static readonly FieldInfo BindingIdField = AccessTools.Field(typeof(RebindActionUI), "m_BindingId");

		private static readonly HashSet<RebindActionUI> Pending = new HashSet<RebindActionUI>();

		private static readonly List<TextMeshProUGUI> Labels = new List<TextMeshProUGUI>();

		private static ModInput _input;

		public static void Init(ModInput input)
		{
			_input = input;
			Strings.LanguageChanged += OnLanguageChanged;
		}

		public static void Notice(RebindActionUI ui)
		{
			if (_input != null && ActionName(ui) == "ChangeBait")
			{
				Pending.Add(ui);
			}
		}

		public static void ProcessPending()
		{
			if (Pending.Count == 0)
			{
				return;
			}
			List<RebindActionUI> list = Pending.ToList();
			Pending.Clear();
			foreach (RebindActionUI item in list)
			{
				try
				{
					if ((Object)(object)item == (Object)null || ActionName(item) != "ChangeBait" || (Object)(object)((Component)item).GetComponentInParent<HotbarRow>(true) != (Object)null)
					{
						continue;
					}
					Transform val = FindRow(((Component)item).transform);
					if (!((Object)(object)val.parent == (Object)null))
					{
						Transform column = FindTargetColumn(val);
						if (!AlreadyInjected(column, val))
						{
							Inject(val, column);
						}
					}
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"Could not add the EasyHotbarOrganization row to the Controls menu: {arg}");
				}
			}
		}

		private static Transform FindRow(Transform t)
		{
			Transform val = t;
			while ((Object)(object)val.parent != (Object)null && !((Component)val.parent).GetComponentsInChildren<RebindActionUI>(true).Any((RebindActionUI u) => ActionName(u) != "ChangeBait"))
			{
				val = val.parent;
			}
			return val;
		}

		private static Transform FindTargetColumn(Transform row)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			Transform parent = row.parent;
			if ((Object)(object)parent.parent == (Object)null)
			{
				return parent;
			}
			Transform result = parent;
			int num = RowCount(parent);
			foreach (Transform item in parent.parent)
			{
				Transform val = item;
				if (!((Object)(object)val == (Object)(object)parent) && !((Object)(object)((Component)val).GetComponent<LayoutGroup>() == (Object)null))
				{
					int num2 = RowCount(val);
					if (num2 > 0 && num2 < num)
					{
						result = val;
						num = num2;
					}
				}
			}
			return result;
		}

		private static int RowCount(Transform column)
		{
			return ((IEnumerable)column).Cast<Transform>().Count((Transform c) => (Object)(object)((Component)c).GetComponentInChildren<RebindActionUI>(true) != (Object)null);
		}

		private static bool AlreadyInjected(Transform column, Transform row)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			foreach (Transform item in column)
			{
				HotbarRow component = ((Component)item).GetComponent<HotbarRow>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.Source == (Object)(object)row)
				{
					return true;
				}
			}
			return false;
		}

		private static void Inject(Transform row, Transform column)
		{
			Transform val = ((IEnumerable)column).Cast<Transform>().LastOrDefault((Func<Transform, bool>)((Transform c) => (Object)(object)((Component)c).GetComponentInChildren<RebindActionUI>(true) != (Object)null)) ?? row;
			int num = (((Object)(object)val.parent == (Object)(object)column) ? val.GetSiblingIndex() : (column.childCount - 1));
			GameObject val2 = Object.Instantiate<GameObject>(((Component)row).gameObject, column, false);
			((Object)val2).name = "EasyHotbar_" + _input.Modifier.name;
			val2.transform.SetSiblingIndex(num + 1);
			val2.AddComponent<HotbarRow>().Source = row;
			Retarget(val2.transform);
			ChainNavigation(val, val2.transform);
			Plugin.Log.LogInfo((object)("Added the EasyHotbarOrganization row to the Controls menu under '" + ((Object)column).name + "'"));
		}

		private static void Retarget(Transform clone)
		{
			//IL_0046: 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)
			//IL_0051: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			HashSet<TextMeshProUGUI> excluded = new HashSet<TextMeshProUGUI>();
			List<Transform> overlays = new List<Transform>();
			TextMeshProUGUI val = null;
			RebindActionUI[] componentsInChildren = ((Component)clone).GetComponentsInChildren<RebindActionUI>(true);
			InputAction val3 = default(InputAction);
			int num = default(int);
			foreach (RebindActionUI val2 in componentsInChildren)
			{
				int num2;
				if (val2.ResolveActionAndBinding(ref val3, ref num))
				{
					InputBinding val4 = InputBinding.MaskByGroup("Controller");
					num2 = (((InputBinding)(ref val4)).Matches(val3.bindings[num]) ? 1 : 0);
				}
				else
				{
					num2 = 0;
				}
				bool flag = (byte)num2 != 0;
				ActionField.SetValue(val2, InputActionReference.Create(_input.Modifier));
				BindingIdField.SetValue(val2, (flag ? ModInput.ModifierControllerId : ModInput.ModifierKeyboardId).ToString());
				val2.UpdateBindingDisplay();
				TextMeshProUGUI[] array = (TextMeshProUGUI[])(object)new TextMeshProUGUI[3] { val2.bindingText, val2.rebindPrompt, val2.rebindInfo };
				foreach (TextMeshProUGUI val5 in array)
				{
					if ((Object)(object)val5 != (Object)null)
					{
						excluded.Add(val5);
					}
				}
				if ((Object)(object)val2.rebindOverlay != (Object)null)
				{
					overlays.Add(val2.rebindOverlay.transform);
				}
				if ((Object)(object)val == (Object)null && (Object)(object)val2.actionLabel != (Object)null && ((TMP_Text)val2.actionLabel).transform.IsChildOf(clone))
				{
					val = val2.actionLabel;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				val = ((IEnumerable<TextMeshProUGUI>)((Component)clone).GetComponentsInChildren<TextMeshProUGUI>(true)).FirstOrDefault((Func<TextMeshProUGUI, bool>)((TextMeshProUGUI t) => !excluded.Contains(t) && !overlays.Any((Transform o) => ((TMP_Text)t).transform.IsChildOf(o))));
			}
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)"No label found in the cloned Controls row");
				return;
			}
			LocalizeStringEvent component = ((Component)val).GetComponent<LocalizeStringEvent>();
			if ((Object)(object)component != (Object)null)
			{
				((Behaviour)component).enabled = false;
			}
			((TMP_Text)val).text = LabelText();
			Labels.Add(val);
		}

		private static void ChainNavigation(Transform anchor, Transform clone)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			//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_0051: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Invalid comparison between Unknown and I4
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			Selectable[] componentsInChildren = ((Component)anchor).GetComponentsInChildren<Selectable>(true);
			Selectable[] componentsInChildren2 = ((Component)clone).GetComponentsInChildren<Selectable>(true);
			if (componentsInChildren2.Length != componentsInChildren.Length)
			{
				return;
			}
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Selectable val = componentsInChildren[i];
				Navigation navigation = val.navigation;
				if ((int)((Navigation)(ref navigation)).mode != 4)
				{
					continue;
				}
				navigation = val.navigation;
				Selectable selectOnDown = ((Navigation)(ref navigation)).selectOnDown;
				Selectable val2 = componentsInChildren2[i];
				Navigation navigation2 = val2.navigation;
				((Navigation)(ref navigation2)).mode = (Mode)4;
				((Navigation)(ref navigation2)).selectOnUp = val;
				((Navigation)(ref navigation2)).selectOnDown = selectOnDown;
				navigation = val.navigation;
				((Navigation)(ref navigation2)).selectOnLeft = MapWithinRow(((Navigation)(ref navigation)).selectOnLeft, componentsInChildren, componentsInChildren2);
				navigation = val.navigation;
				((Navigation)(ref navigation2)).selectOnRight = MapWithinRow(((Navigation)(ref navigation)).selectOnRight, componentsInChildren, componentsInChildren2);
				val2.navigation = navigation2;
				Navigation navigation3 = val.navigation;
				((Navigation)(ref navigation3)).selectOnDown = val2;
				val.navigation = navigation3;
				if (!((Object)(object)selectOnDown != (Object)null))
				{
					continue;
				}
				navigation = selectOnDown.navigation;
				if ((int)((Navigation)(ref navigation)).mode == 4)
				{
					navigation = selectOnDown.navigation;
					if ((Object)(object)((Navigation)(ref navigation)).selectOnUp == (Object)(object)val)
					{
						Navigation navigation4 = selectOnDown.navigation;
						((Navigation)(ref navigation4)).selectOnUp = val2;
						selectOnDown.navigation = navigation4;
					}
				}
			}
		}

		private static Selectable MapWithinRow(Selectable target, Selectable[] original, Selectable[] clone)
		{
			int num = Array.IndexOf(original, target);
			if (num < 0)
			{
				return target;
			}
			return clone[num];
		}

		private static string LabelText()
		{
			return Strings.Get("ModifierRow") + " <size=75%>" + Strings.Get("HoldTag") + "</size>";
		}

		private static void OnLanguageChanged()
		{
			Labels.RemoveAll((TextMeshProUGUI l) => (Object)(object)l == (Object)null);
			foreach (TextMeshProUGUI label in Labels)
			{
				((TMP_Text)label).text = LabelText();
			}
		}

		private static string ActionName(RebindActionUI ui)
		{
			object? value = ActionField.GetValue(ui);
			InputActionReference val = (InputActionReference)((value is InputActionReference) ? value : null);
			if (!((Object)(object)val != (Object)null) || val.action == null)
			{
				return null;
			}
			return val.action.name;
		}
	}
	[HarmonyPatch(typeof(RebindActionUI), "OnEnable")]
	internal static class RebindActionUIOnEnablePatch
	{
		private static void Postfix(RebindActionUI __instance)
		{
			ControlsMenu.Notice(__instance);
		}
	}
	public class HotbarMover : MonoBehaviour
	{
		private const float ConfirmTimeout = 3f;

		private const int MaxQueued = 9;

		private static readonly FieldInfo LocalCurSlotField = AccessTools.Field(typeof(PlayerInventory), "_localCurSlot");

		private static readonly MethodInfo GetTotalSlotsMethod = AccessTools.Method(typeof(PlayerInventory), "GetTotalSlots", (Type[])null, (Type[])null);

		private static readonly MethodInfo UpdateHeldItemMethod = AccessTools.Method(typeof(PlayerInventory), "UpdateHeldItem", (Type[])null, (Type[])null);

		private static readonly FieldInfo ItemSlotsField = AccessTools.Field(typeof(PlayerInventory), "_itemSlots");

		private static readonly PropertyInfo SyncedCurItemProperty = AccessTools.Property(typeof(PlayerInventory), "SyncedCurItem");

		public ConfigEntry<bool> Enabled;

		public ConfigEntry<bool> LogSteps;

		public ModInput Input;

		private readonly Queue<int> _targets = new Queue<int>();

		private PlayerInventory _inventory;

		private Item _movingItem;

		private int _sourceSlot = -1;

		private int _virtualSlot = -1;

		private bool _busy;

		private PlayerInventory _holdingBack;

		private const float UnequipTapMax = 0.5f;

		private bool _deferredUnequip;

		private bool _movedDuringHold;

		private float _unequipPressTime;

		public static HotbarMover Instance { get; private set; }

		private bool ModifierHeld
		{
			get
			{
				if (Enabled != null && Enabled.Value && Input != null)
				{
					return Input.Modifier.IsPressed();
				}
				return false;
			}
		}

		public bool BlocksDrop => _busy;

		private void Awake()
		{
			Instance = this;
		}

		public bool OnSelectSlot(PlayerInventory inventory, int slot)
		{
			if (_busy)
			{
				return Chain(inventory, slot);
			}
			if (!ModifierHeld)
			{
				return false;
			}
			return RequestMove(inventory, (int from) => slot);
		}

		public bool OnScroll(PlayerInventory inventory, int dir)
		{
			if (_busy)
			{
				return Chain(inventory, Wrap(inventory, _virtualSlot + dir));
			}
			if (!ModifierHeld || dir == 0)
			{
				return false;
			}
			return RequestMove(inventory, (int from) => Wrap(inventory, from + dir));
		}

		private static int Wrap(PlayerInventory inventory, int slot)
		{
			int num = TotalSlots(inventory);
			if (num > 0)
			{
				return (slot % num + num) % num;
			}
			return slot;
		}

		public bool OnDeselect(PlayerInventory inventory, CallbackContext context)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (_busy)
			{
				return true;
			}
			if (Enabled == null || !Enabled.Value || Input == null || ((CallbackContext)(ref context)).control == null)
			{
				return false;
			}
			if (!((IEnumerable<InputControl>)(object)Input.Modifier.controls).Contains(((CallbackContext)(ref context)).control))
			{
				return false;
			}
			_inventory = inventory;
			_deferredUnequip = true;
			_movedDuringHold = false;
			_unequipPressTime = Time.unscaledTime;
			return true;
		}

		private void Update()
		{
			if (_deferredUnequip && (Input == null || !Input.Modifier.IsPressed()))
			{
				_deferredUnequip = false;
				if (Time.unscaledTime - _unequipPressTime <= 0.5f && !_movedDuringHold && !_busy && (Object)(object)_inventory != (Object)null && (Object)(object)Player.LocalPlayer != (Object)null && !Player.LocalPlayer.BlockInputs && !Boat.IsDrivingLocally && !Boat.WantToDrive)
				{
					_inventory.LocalTrySelectSlot(-1);
				}
			}
		}

		private bool RequestMove(PlayerInventory inventory, Func<int, int> target)
		{
			Player localPlayer = Player.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)inventory == (Object)null || (Object)(object)localPlayer.Inventory != (Object)(object)inventory || (Object)(object)Server.Instance == (Object)null)
			{
				return false;
			}
			if (!CanStart(localPlayer, inventory, out var source, out var item))
			{
				return false;
			}
			int num = target(source);
			if (num < 0 || num >= TotalSlots(inventory) || num == source)
			{
				return true;
			}
			if (inventory._syncedCurSlot.Value != source)
			{
				return true;
			}
			_sourceSlot = source;
			_movingItem = item;
			_inventory = inventory;
			_virtualSlot = source;
			Enqueue(inventory, source, num);
			((MonoBehaviour)this).StartCoroutine(Run(localPlayer, inventory));
			return true;
		}

		private bool Chain(PlayerInventory inventory, int to)
		{
			if (ModifierHeld && Object.op_Implicit((Object)(object)_movingItem) && (Object)(object)inventory == (Object)(object)_inventory)
			{
				Enqueue(inventory, _virtualSlot, to);
			}
			return true;
		}

		private bool Enqueue(PlayerInventory inventory, int from, int to)
		{
			if (to < 0 || to >= TotalSlots(inventory) || to == from || _targets.Count >= 9)
			{
				return true;
			}
			_targets.Enqueue(to);
			_virtualSlot = to;
			_movedDuringHold = true;
			return true;
		}

		private static bool CanStart(Player player, PlayerInventory inventory, out int source, out Item item)
		{
			source = -1;
			item = null;
			if (player.BlockInputs || Boat.IsDrivingLocally || Boat.WantToDrive || !IsAlive(player))
			{
				return false;
			}
			if ((Object)(object)player.Holding.UninitializedHeldItem != (Object)null)
			{
				return false;
			}
			source = (int)LocalCurSlotField.GetValue(inventory);
			if (source < 0)
			{
				return false;
			}
			item = SlotItem(inventory, source);
			if ((Object)(object)item == (Object)null || (Object)(object)item.DeadPlayer != (Object)null || (Object)(object)item.SyncedHolder != (Object)(object)player)
			{
				return false;
			}
			if ((Object)(object)player.Holding.HeldItem == (Object)(object)item)
			{
				return !item.IsInInventory;
			}
			return false;
		}

		private IEnumerator Run(Player player, PlayerInventory inventory)
		{
			_busy = true;
			_holdingBack = inventory;
			try
			{
				int source = _sourceSlot;
				while (_targets.Count > 0)
				{
					int target = _targets.Dequeue();
					if (!TrySwap(player, inventory, source, target, out var other))
					{
						break;
					}
					float deadline = Time.unscaledTime + 3f;
					while (!Confirmed(inventory, source, target, other))
					{
						if (Time.unscaledTime > deadline || !Object.op_Implicit((Object)(object)player))
						{
							Plugin.Log.LogWarning((object)$"Move {source + 1} → {target + 1}: the host didn't confirm in time");
							_targets.Clear();
							break;
						}
						yield return null;
					}
					if (!((Object)(object)SlotItem(inventory, target) != (Object)(object)_movingItem))
					{
						source = target;
						other = null;
						continue;
					}
					break;
				}
			}
			finally
			{
				HotbarMover hotbarMover = this;
				hotbarMover._holdingBack = null;
				hotbarMover.Reconcile(player, inventory);
				hotbarMover._targets.Clear();
				hotbarMover._movingItem = null;
				hotbarMover._sourceSlot = -1;
				hotbarMover._virtualSlot = -1;
				hotbarMover._busy = false;
			}
		}

		private void Reconcile(Player player, PlayerInventory inventory)
		{
			if (!Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)inventory))
			{
				return;
			}
			try
			{
				int value = inventory._syncedCurSlot.Value;
				SetLocalSlot(inventory, value);
				Item movingItem = _movingItem;
				if (Object.op_Implicit((Object)(object)movingItem) && (Object)(object)SlotItem(inventory, value) == (Object)(object)movingItem && (Object)(object)player.Holding.HeldItem == (Object)(object)movingItem && !movingItem.IsInInventory && (Object)(object)movingItem.Holder == (Object)(object)player)
				{
					SyncedCurItemProperty.SetValue(inventory, movingItem);
					return;
				}
				UpdateHeldItemMethod.Invoke(inventory, new object[1] { value });
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Could not restore the hand after a move: {arg}");
			}
		}

		private static void SetLocalSlot(PlayerInventory inventory, int slot)
		{
			int num = (int)LocalCurSlotField.GetValue(inventory);
			if (num != slot)
			{
				List<InventorySlot> list = (List<InventorySlot>)ItemSlotsField.GetValue(inventory);
				if (num >= 0 && num < list.Count)
				{
					list[num].Deselect();
				}
				if (slot >= 0 && slot < list.Count)
				{
					list[slot].Select();
				}
				LocalCurSlotField.SetValue(inventory, slot);
			}
		}

		private bool Confirmed(PlayerInventory inventory, int source, int target, Item other)
		{
			if ((Object)(object)SlotItem(inventory, target) != (Object)(object)_movingItem || (Object)(object)SlotItem(inventory, source) != (Object)(object)other || inventory._syncedCurSlot.Value != target)
			{
				return false;
			}
			List<InventorySlot> list = (List<InventorySlot>)ItemSlotsField.GetValue(inventory);
			if ((Object)(object)list[target].Item == (Object)(object)_movingItem)
			{
				return (Object)(object)(Object.op_Implicit((Object)(object)list[source].Item) ? list[source].Item : null) == (Object)(object)other;
			}
			return false;
		}

		public bool HoldsBackHeldUpdate(PlayerInventory inventory)
		{
			if ((Object)(object)_holdingBack != (Object)null)
			{
				return (Object)(object)inventory == (Object)(object)_holdingBack;
			}
			return false;
		}

		private bool TrySwap(Player player, PlayerInventory inventory, int source, int target, out Item other)
		{
			other = null;
			Server instance = Server.Instance;
			Item movingItem = _movingItem;
			if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)player) || ((NetworkBehaviour)player).IsDeinitializing || !IsAlive(player))
			{
				return false;
			}
			if ((Object)(object)player.Holding.HeldItem != (Object)(object)movingItem || (Object)(object)player.Holding.UninitializedHeldItem != (Object)null || (int)LocalCurSlotField.GetValue(inventory) != source)
			{
				return false;
			}
			if (target < 0 || target >= TotalSlots(inventory) || (Object)(object)SlotItem(inventory, source) != (Object)(object)movingItem || !Object.op_Implicit((Object)(object)movingItem) || ((NetworkBehaviour)movingItem).IsDeinitializing || movingItem.IsInInventory || (Object)(object)movingItem.SyncedHolder != (Object)(object)player)
			{
				return false;
			}
			other = SlotItem(inventory, target);
			if ((Object)(object)other != (Object)null && (((NetworkBehaviour)other).IsDeinitializing || (Object)(object)other.SyncedHolder != (Object)(object)player || (Object)(object)other.DeadPlayer != (Object)null))
			{
				return false;
			}
			if (LogSteps.Value)
			{
				Plugin.Log.LogInfo((object)($"Move {((Object)movingItem).name} {source + 1} → {target + 1}" + (Object.op_Implicit((Object)(object)other) ? $", {((Object)other).name} → {source + 1}" : "") + (((NetworkBehaviour)inventory).IsServerInitialized ? " (host)" : "")));
			}
			if (((NetworkBehaviour)inventory).IsServerInitialized)
			{
				inventory._items[(byte)source] = other;
				inventory._items[(byte)target] = movingItem;
				inventory.ServerSetSyncedCurSlot(target);
				SetLocalSlot(inventory, target);
				return true;
			}
			instance.RemoveItemFromInventory(player, movingItem);
			instance.SetItemHolder(movingItem, player, (Item)null);
			if (Object.op_Implicit((Object)(object)other))
			{
				instance.RemoveItemFromInventory(player, other);
				instance.PutItemInInventory(player, movingItem, (byte)target);
				instance.SetItemHolder(other, player, movingItem);
				instance.PutItemInInventory(player, other, (byte)source);
			}
			else
			{
				instance.PutItemInInventory(player, movingItem, (byte)target);
			}
			inventory.ApplySlot(target);
			return true;
		}

		private static bool IsAlive(Player player)
		{
			if ((Object)(object)player.Vitals != (Object)null && player.Vitals.Health > 0)
			{
				return !player.Dying.IsDead;
			}
			return false;
		}

		private static int TotalSlots(PlayerInventory inventory)
		{
			return Math.Min(9, (int)GetTotalSlotsMethod.Invoke(inventory, null));
		}

		private static Item SlotItem(PlayerInventory inventory, int slot)
		{
			Item val = default(Item);
			if (!inventory._items.TryGetValue((byte)slot, ref val) || !Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return val;
		}

		private static int FindSlot(PlayerInventory inventory, Item item)
		{
			foreach (KeyValuePair<byte, Item> item2 in ((IEnumerable<KeyValuePair<byte, Item>>)inventory._items).ToList())
			{
				if ((Object)(object)item2.Value == (Object)(object)item)
				{
					return item2.Key;
				}
			}
			return -1;
		}
	}
	public sealed class ModInput
	{
		public const string KeyboardGroup = "Keyboard";

		public const string ControllerGroup = "Controller";

		public static readonly Guid ModifierKeyboardId = new Guid("3e7b9c15-6a2d-4f80-9b41-d52c8e0f7a01");

		public static readonly Guid ModifierControllerId = new Guid("3e7b9c15-6a2d-4f80-9b41-d52c8e0f7a02");

		private readonly InputActionAsset _asset;

		private readonly InputActionMap _map;

		private readonly ConfigEntry<string> _overrides;

		public InputAction Modifier { get; }

		public ModInput(ConfigEntry<string> overrides)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			_overrides = overrides;
			_asset = ScriptableObject.CreateInstance<InputActionAsset>();
			((Object)_asset).name = "EasyHotbarOrganizationInput";
			Object.DontDestroyOnLoad((Object)(object)_asset);
			_map = new InputActionMap("EasyHotbarOrganization");
			InputActionSetupExtensions.AddActionMap(_asset, _map);
			Modifier = InputActionSetupExtensions.AddAction(_map, "MoveInventoryItem", (InputActionType)1, (string)null, (string)null, (string)null, (string)null, (string)null);
			AddBinding(Modifier, ModifierKeyboardId, "<Keyboard>/leftAlt", "Keyboard");
			AddBinding(Modifier, ModifierControllerId, "<Gamepad>/dpad/down", "Controller");
			Load();
			InputSystem.onActionChange += OnActionChange;
			_map.Enable();
		}

		private void AddBinding(InputAction action, Guid id, string path, string group)
		{
			//IL_0008: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			InputActionMap map = _map;
			InputBinding val = default(InputBinding);
			((InputBinding)(ref val)).id = id;
			((InputBinding)(ref val)).path = path;
			((InputBinding)(ref val)).groups = group;
			((InputBinding)(ref val)).action = action.name;
			InputActionSetupExtensions.AddBinding(map, val);
		}

		private void Load()
		{
			if (string.IsNullOrEmpty(_overrides.Value))
			{
				return;
			}
			try
			{
				InputActionRebindingExtensions.LoadBindingOverridesFromJson((IInputActionCollection2)(object)_asset, _overrides.Value, true);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Ignoring invalid saved bindings: " + ex.Message));
			}
		}

		private void OnActionChange(object obj, InputActionChange change)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)change != 8)
			{
				return;
			}
			object obj2 = ((obj is InputAction) ? obj : null);
			if ((((obj2 != null) ? ((InputAction)obj2).actionMap : null) ?? ((obj is InputActionMap) ? obj : null)) == _map || obj == _asset)
			{
				string text = InputActionRebindingExtensions.SaveBindingOverridesAsJson((IInputActionCollection2)(object)_asset);
				if (text != _overrides.Value)
				{
					_overrides.Value = text;
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerInventory), "SelectSlotInput")]
	internal static class SelectSlotInputPatch
	{
		private static bool Prefix(PlayerInventory __instance, CallbackContext context)
		{
			HotbarMover instance = HotbarMover.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				return !instance.OnSelectSlot(__instance, (int)((CallbackContext)(ref context)).ReadValue<float>());
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerInventory), "ScrollSlotInput")]
	internal static class ScrollSlotInputPatch
	{
		private static bool Prefix(PlayerInventory __instance, CallbackContext context)
		{
			HotbarMover instance = HotbarMover.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				return !instance.OnScroll(__instance, -Math.Sign((int)((CallbackContext)(ref context)).ReadValue<float>()));
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerInventory), "DeselectSlotInput")]
	internal static class DeselectSlotInputPatch
	{
		private static bool Prefix(PlayerInventory __instance, CallbackContext context)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			HotbarMover instance = HotbarMover.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				return !instance.OnDeselect(__instance, context);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerInventory), "UpdateHeldItem")]
	internal static class UpdateHeldItemPatch
	{
		private static bool Prefix(PlayerInventory __instance)
		{
			HotbarMover instance = HotbarMover.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				return !instance.HoldsBackHeldUpdate(__instance);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerHolding), "DropInput")]
	internal static class DropInputPatch
	{
		private static bool Prefix()
		{
			HotbarMover instance = HotbarMover.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				return !instance.BlocksDrop;
			}
			return true;
		}
	}
	[BepInPlugin("avidkaos.howtofish.easyhotbarorganization", "EasyHotbarOrganization", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "avidkaos.howtofish.easyhotbarorganization";

		public const string PluginName = "EasyHotbarOrganization";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		private ConfigEntry<string> _bindings;

		private HotbarMover _mover;

		private void Awake()
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			_mover = ((Component)this).gameObject.AddComponent<HotbarMover>();
			_mover.Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Hold the move key (Left Alt / D-pad Down) and press a slot number or scroll to move the selected item.");
			_mover.LogSteps = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogSteps", false, "Write every move step to the log.");
			_bindings = ((BaseUnityPlugin)this).Config.Bind<string>("Controls", "BindingOverrides", "", "Keybinds changed in the game's Controls menu (Move Inventory Item row). Managed by the game menu; clear to reset.");
			new Harmony("avidkaos.howtofish.easyhotbarorganization").PatchAll(typeof(Plugin).Assembly);
			Log.LogInfo((object)"EasyHotbarOrganization 1.0.0 loaded");
		}

		private void Start()
		{
			ModInput input = new ModInput(_bindings);
			_mover.Input = input;
			ControlsMenu.Init(input);
		}

		private void Update()
		{
			ControlsMenu.ProcessPending();
		}
	}
	public static class Strings
	{
		public const string ModifierRow = "ModifierRow";

		public const string HoldTag = "HoldTag";

		private static bool _subscribed;

		private static readonly Dictionary<string, Dictionary<string, string>> Table = new Dictionary<string, Dictionary<string, string>>
		{
			["ModifierRow"] = new Dictionary<string, string>
			{
				["en"] = "Move Inventory Item",
				["zh-CN"] = "移动物品栏中的物品",
				["zh-TW"] = "移動物品欄中的物件",
				["fr"] = "Déplacer un objet de l'inventaire",
				["de"] = "Inventargegenstand verschieben",
				["it"] = "Sposta oggetto inventario",
				["ja"] = "インベントリのアイテムを移動",
				["ko"] = "인벤토리 아이템 이동",
				["pl"] = "Przenieś przedmiot w ekwipunku",
				["pt-BR"] = "Mover item do inventário",
				["ru"] = "Переместить предмет в инвентаре",
				["es-MX"] = "Mover objeto del inventario",
				["es-ES"] = "Mover objeto del inventario",
				["sv"] = "Flytta föremål",
				["tr"] = "Envanter Eşyasını Taşı",
				["uk"] = "Перемістити предмет в інвентарі"
			},
			["HoldTag"] = new Dictionary<string, string>
			{
				["en"] = "(Hold)",
				["zh-CN"] = "(长按)",
				["zh-TW"] = "(長按)",
				["fr"] = "(Maintenir)",
				["de"] = "(halten)",
				["it"] = "(Tieni premuto)",
				["ja"] = "(長押し)",
				["ko"] = "(길게 누르기)",
				["pl"] = "(przytrzymaj)",
				["pt-BR"] = "(Segure)",
				["ru"] = "(удерживайте)",
				["es-MX"] = "(Mantener presionado)",
				["es-ES"] = "(mantén)",
				["sv"] = "(Håll)",
				["tr"] = "(Basılı Tut)",
				["uk"] = "(Утрим.)"
			}
		};

		public static event Action LanguageChanged;

		public static string Get(string key, params object[] args)
		{
			EnsureSubscribed();
			if (!Table.TryGetValue(key, out var value))
			{
				return key;
			}
			string value2 = null;
			string text = CurrentCode();
			if (text != null && !value.TryGetValue(text, out value2))
			{
				string value3 = text.Split('-')[0];
				foreach (KeyValuePair<string, string> item in value)
				{
					if (item.Key.Split('-')[0].Equals(value3, StringComparison.OrdinalIgnoreCase))
					{
						value2 = item.Value;
						break;
					}
				}
			}
			if (value2 == null)
			{
				value2 = value["en"];
			}
			if (args.Length == 0)
			{
				return value2;
			}
			return string.Format(value2, args);
		}

		private static string CurrentCode()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Locale selectedLocale = LocalizationSettings.SelectedLocale;
				object obj;
				if (selectedLocale == null)
				{
					obj = null;
				}
				else
				{
					LocaleIdentifier identifier = selectedLocale.Identifier;
					obj = ((LocaleIdentifier)(ref identifier)).Code;
				}
				string text = (string)obj;
				if (string.IsNullOrEmpty(text))
				{
					return null;
				}
				string[] array = text.Split('-');
				return (array.Length == 2) ? (array[0].ToLowerInvariant() + "-" + array[1].ToUpperInvariant()) : text.ToLowerInvariant();
			}
			catch (Exception)
			{
				return null;
			}
		}

		private static void EnsureSubscribed()
		{
			if (_subscribed)
			{
				return;
			}
			try
			{
				LocalizationSettings.SelectedLocaleChanged += delegate
				{
					Strings.LanguageChanged?.Invoke();
				};
				_subscribed = true;
			}
			catch (Exception)
			{
			}
		}
	}
	internal static class PluginInfo
	{
		public const string Version = "1.0.0";
	}
}