Decompiled source of Simple Sort v0.8.0

SimpleSort.dll

Decompiled 4 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
public class AedenthornUtils
{
	public static bool IgnoreKeyPresses(bool extra = false)
	{
		if (!extra)
		{
			int result;
			if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Minimap.IsOpen() && !Console.IsVisible() && !TextInput.IsVisible() && !ZNet.instance.InPasswordDialog())
			{
				Chat instance = Chat.instance;
				result = ((instance != null && instance.HasFocus()) ? 1 : 0);
			}
			else
			{
				result = 1;
			}
			return (byte)result != 0;
		}
		int result2;
		if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Minimap.IsOpen() && !Console.IsVisible() && !TextInput.IsVisible() && !ZNet.instance.InPasswordDialog())
		{
			Chat instance2 = Chat.instance;
			if ((instance2 == null || !instance2.HasFocus()) && !StoreGui.IsVisible() && !InventoryGui.IsVisible() && !Menu.IsVisible())
			{
				TextViewer instance3 = TextViewer.instance;
				result2 = ((instance3 != null && instance3.IsVisible()) ? 1 : 0);
				goto IL_00d2;
			}
		}
		result2 = 1;
		goto IL_00d2;
		IL_00d2:
		return (byte)result2 != 0;
	}

	public static bool CheckKeyDown(string value)
	{
		try
		{
			return Input.GetKeyDown(value.ToLower());
		}
		catch
		{
			return false;
		}
	}

	public static bool CheckKeyHeld(string value, bool req = true)
	{
		try
		{
			return Input.GetKey(value.ToLower());
		}
		catch
		{
			return !req;
		}
	}
}
public class SortUtils
{
	public static void SortByName(List<ItemData> items, bool asc, bool player)
	{
		items.Sort((ItemData a, ItemData b) => (a.m_shared.m_name == b.m_shared.m_name) ? CompareInts(a.m_stack, b.m_stack, asc: false) : CompareStrings(Localization.instance.Localize(a.m_shared.m_name), Localization.instance.Localize(b.m_shared.m_name), asc));
	}

	public static void SortByWeight(List<ItemData> items, bool asc, bool player)
	{
		items.Sort((ItemData a, ItemData b) => (a.m_shared.m_weight == b.m_shared.m_weight) ? ((a.m_shared.m_name == b.m_shared.m_name) ? CompareInts(a.m_stack, b.m_stack, asc: false) : CompareStrings(Localization.instance.Localize(a.m_shared.m_name), Localization.instance.Localize(b.m_shared.m_name), asc: true)) : CompareFloats(a.m_shared.m_weight, b.m_shared.m_weight, asc));
	}

	public static void SortByValue(List<ItemData> items, bool asc, bool player)
	{
		items.Sort((ItemData a, ItemData b) => (a.m_shared.m_value == b.m_shared.m_value) ? ((a.m_shared.m_name == b.m_shared.m_name) ? CompareInts(a.m_stack, b.m_stack, asc: false) : CompareStrings(Localization.instance.Localize(a.m_shared.m_name), Localization.instance.Localize(b.m_shared.m_name), asc: true)) : CompareInts(a.m_shared.m_value, b.m_shared.m_value, asc));
	}

	public static int CompareStrings(string a, string b, bool asc)
	{
		if (asc)
		{
			return a.CompareTo(b);
		}
		return b.CompareTo(a);
	}

	public static int CompareFloats(float a, float b, bool asc)
	{
		if (asc)
		{
			return a.CompareTo(b);
		}
		return b.CompareTo(a);
	}

	public static int CompareInts(float a, float b, bool asc)
	{
		if (asc)
		{
			return a.CompareTo(b);
		}
		return b.CompareTo(a);
	}
}
namespace SimpleSort;

[BepInPlugin("aedenthorn.SimpleSort", "Simple Sort", "0.8.0")]
public class BepInExPlugin : BaseUnityPlugin
{
	public enum SortType
	{
		Name,
		Weight,
		Value
	}

	[HarmonyPatch(typeof(InventoryGui), "Show")]
	private static class InventoryGui_Show_Patch
	{
		private static void Postfix(Container ___m_currentContainer)
		{
			if (modEnabled.Value)
			{
				if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && playerStickySort.Value && allowPlayerInventorySort.Value)
				{
					SortByType(playerSortType.Value, ((Humanoid)Player.m_localPlayer).GetInventory(), playerSortAsc.Value, player: true);
				}
				if (containerStickySort.Value && ((___m_currentContainer != null) ? ___m_currentContainer.GetInventory() : null) != null)
				{
					SortByType(containerSortType.Value, ___m_currentContainer.GetInventory(), containerSortAsc.Value, player: false);
				}
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "Update")]
	private static class InventoryGui_Update_Patch
	{
		private static void Postfix(InventoryGui __instance, Container ___m_currentContainer, int ___m_activeGroup)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			Vector3 mousePosition = Input.mousePosition;
			if (!modEnabled.Value || (!AedenthornUtils.CheckKeyHeld(ascModKey.Value, req: false) && !AedenthornUtils.CheckKeyHeld(descModKey.Value, req: false)))
			{
				return;
			}
			bool flag = AedenthornUtils.CheckKeyHeld(ascModKey.Value, req: false);
			if (AedenthornUtils.CheckKeyHeld(descModKey.Value))
			{
				flag = false;
			}
			string text = "";
			SortType sortType = SortType.Name;
			PointerEventData val = new PointerEventData(EventSystem.current)
			{
				position = Vector2.op_Implicit(mousePosition)
			};
			List<RaycastResult> list = new List<RaycastResult>();
			EventSystem.current.RaycastAll(val, list);
			foreach (RaycastResult item in list)
			{
				RaycastResult current = item;
				if (((RaycastResult)(ref current)).gameObject.layer == LayerMask.NameToLayer("UI") && ((Object)((RaycastResult)(ref current)).gameObject).name == "Bkg" && (((Object)((RaycastResult)(ref current)).gameObject.transform.parent).name == "Player" || ((Object)((RaycastResult)(ref current)).gameObject.transform.parent).name == "Container"))
				{
					if (AedenthornUtils.CheckKeyDown(sortByNameKey.Value))
					{
						text = ((Object)((RaycastResult)(ref current)).gameObject.transform.parent).name;
						sortType = SortType.Name;
						break;
					}
					if (AedenthornUtils.CheckKeyDown(sortByWeightKey.Value))
					{
						text = ((Object)((RaycastResult)(ref current)).gameObject.transform.parent).name;
						sortType = SortType.Weight;
						break;
					}
					if (AedenthornUtils.CheckKeyDown(sortByValueKey.Value))
					{
						text = ((Object)((RaycastResult)(ref current)).gameObject.transform.parent).name;
						sortType = SortType.Value;
						break;
					}
					return;
				}
			}
			if (text == "" && useGamePad.Value)
			{
				if (___m_activeGroup == 0 && !__instance.IsContainerOpen())
				{
					return;
				}
				if (___m_activeGroup == 0 || ___m_activeGroup == 1)
				{
					if (AedenthornUtils.CheckKeyDown(sortByNameKey.Value))
					{
						text = ((___m_activeGroup == 0) ? "Container" : "Player");
						sortType = SortType.Name;
					}
					else if (AedenthornUtils.CheckKeyDown(sortByWeightKey.Value))
					{
						text = ((___m_activeGroup == 0) ? "Container" : "Player");
						sortType = SortType.Weight;
					}
					else if (AedenthornUtils.CheckKeyDown(sortByValueKey.Value))
					{
						text = ((___m_activeGroup == 0) ? "Container" : "Player");
						sortType = SortType.Value;
					}
				}
			}
			if (!(text == "") && (!(text == "Player") || allowPlayerInventorySort.Value))
			{
				Dbgl(string.Format("Sorting {0} inventory by {1} {2}", text, sortType, flag ? "asc" : "desc"));
				if (text == "Player")
				{
					playerSortType.Value = sortType;
					playerSortAsc.Value = flag;
					((BaseUnityPlugin)context).Config.Save();
					SortByType(sortType, ((Humanoid)Player.m_localPlayer).GetInventory(), flag, player: true);
				}
				else if (text == "Container")
				{
					containerSortType.Value = sortType;
					containerSortAsc.Value = flag;
					((BaseUnityPlugin)context).Config.Save();
					SortByType(sortType, ___m_currentContainer.GetInventory(), flag, player: false);
				}
			}
		}
	}

	[HarmonyPatch(typeof(Terminal), "InputText")]
	private static class InputText_Patch
	{
		private static bool Prefix(Terminal __instance)
		{
			if (!modEnabled.Value)
			{
				return true;
			}
			string text = ((TMP_InputField)__instance.m_input).text;
			if (text.ToLower().Equals(typeof(BepInExPlugin).Namespace.ToLower() + " reset"))
			{
				((BaseUnityPlugin)context).Config.Reload();
				((BaseUnityPlugin)context).Config.Save();
				Traverse.Create((object)__instance).Method("AddString", new object[1] { text }).GetValue();
				Traverse.Create((object)__instance).Method("AddString", new object[1] { ((BaseUnityPlugin)context).Info.Metadata.Name + " config reloaded" }).GetValue();
				return false;
			}
			return true;
		}
	}

	private static readonly bool isDebug = true;

	private static BepInExPlugin context;

	private Harmony harmony;

	public static ConfigEntry<bool> modEnabled;

	public static ConfigEntry<bool> useGamePad;

	public static ConfigEntry<bool> allowPlayerInventorySort;

	public static ConfigEntry<bool> playerStickySort;

	public static ConfigEntry<bool> containerStickySort;

	public static ConfigEntry<SortType> playerSortType;

	public static ConfigEntry<SortType> containerSortType;

	public static ConfigEntry<bool> playerSortAsc;

	public static ConfigEntry<bool> containerSortAsc;

	public static ConfigEntry<string> ascModKey;

	public static ConfigEntry<string> descModKey;

	public static ConfigEntry<string> sortByNameKey;

	public static ConfigEntry<string> sortByWeightKey;

	public static ConfigEntry<string> sortByValueKey;

	public static ConfigEntry<int> playerSortStartRow;

	public static ConfigEntry<int> playerSortEndRow;

	public static ConfigEntry<int> nexusID;

	public static void Dbgl(string str = "", bool pref = true)
	{
		if (isDebug)
		{
			Debug.Log((object)((pref ? (typeof(BepInExPlugin).Namespace + " ") : "") + str));
		}
	}

	private void Awake()
	{
		//IL_0263: Unknown result type (might be due to invalid IL or missing references)
		//IL_026d: Expected O, but got Unknown
		context = this;
		modEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable this mod");
		useGamePad = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "useGamePad", false, "Allow sorting with gamepad?");
		allowPlayerInventorySort = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AllowPlayerInventorySort", true, "Allow player inventory sorting?");
		playerStickySort = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "PlayerStickySort", true, "Automatically apply last sort type to player inventory on open");
		containerStickySort = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ContainerStickySort", true, "Automatically apply last sort type to container inventory on open");
		playerSortAsc = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "playerSortAsc", true, "Current player sort method (changes automatically for sticky sorting)");
		containerSortAsc = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "containerSortAsc", true, "Current container sort method (changes automatically for sticky sorting)");
		playerSortType = ((BaseUnityPlugin)this).Config.Bind<SortType>("General", "PlayerSortType", SortType.Name, "Current player sort type (changes automatically for sticky sorting)");
		containerSortType = ((BaseUnityPlugin)this).Config.Bind<SortType>("General", "ContainerSortType", SortType.Name, "Current container sort type (changes automatically for sticky sorting)");
		sortByValueKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "SortByValueKey", "v", "Sort by value key. Use https://docs.unity3d.com/Manual/class-InputManager.html format.");
		sortByWeightKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "SortByWeightKey", "h", "Sort by weight key. Use https://docs.unity3d.com/Manual/class-InputManager.html format.");
		sortByNameKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "SortByNameKey", "n", "Sort by name key. Use https://docs.unity3d.com/Manual/class-InputManager.html format.");
		ascModKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "AscModKey", "left alt", "Sort ascending mod key. Use https://docs.unity3d.com/Manual/class-InputManager.html format.");
		descModKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "DescModKey", "left ctrl", "Sort descending mod key. Use https://docs.unity3d.com/Manual/class-InputManager.html format.");
		playerSortStartRow = ((BaseUnityPlugin)this).Config.Bind<int>("General", "PlayerSortStartRow", 2, "Player sort start row");
		playerSortEndRow = ((BaseUnityPlugin)this).Config.Bind<int>("General", "PlayerSortEndRow", -1, "Player sort end row (use -1 to sort to the end)");
		nexusID = ((BaseUnityPlugin)this).Config.Bind<int>("General", "NexusID", 584, "Nexus mod ID for updates");
		if (modEnabled.Value)
		{
			harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
			harmony.PatchAll();
		}
	}

	private void OnDestroy()
	{
		Dbgl("Destroying plugin");
		harmony.UnpatchAll((string)null);
	}

	private static void SortByType(SortType type, Inventory inventory, bool asc, bool player)
	{
		List<ItemData> allItems = inventory.GetAllItems();
		SortUtils.SortByName(allItems, asc: true, player);
		for (int i = 0; i < allItems.Count; i++)
		{
			if (player && ((playerSortStartRow.Value > 1 && allItems[i].m_gridPos.y < playerSortStartRow.Value - 1) || (playerSortEndRow.Value > 0 && allItems[i].m_gridPos.y >= playerSortEndRow.Value)))
			{
				continue;
			}
			while (i < allItems.Count - 1 && allItems[i].m_stack < allItems[i].m_shared.m_maxStackSize && allItems[i + 1].m_shared.m_name == allItems[i].m_shared.m_name)
			{
				int num = Mathf.Min(allItems[i].m_shared.m_maxStackSize - allItems[i].m_stack, allItems[i + 1].m_stack);
				ItemData obj = allItems[i];
				obj.m_stack += num;
				if (num == allItems[i + 1].m_stack)
				{
					allItems.RemoveAt(i + 1);
					continue;
				}
				ItemData obj2 = allItems[i + 1];
				obj2.m_stack -= num;
			}
		}
		switch (type)
		{
		case SortType.Name:
			SortUtils.SortByName(allItems, asc, player);
			break;
		case SortType.Weight:
			SortUtils.SortByWeight(allItems, asc, player);
			break;
		case SortType.Value:
			SortUtils.SortByValue(allItems, asc, player);
			break;
		}
		SortToGrid(inventory, player);
	}

	public static void SortToGrid(Inventory inventory, bool player)
	{
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		List<ItemData> allItems = inventory.GetAllItems();
		int value = Traverse.Create((object)inventory).Field("m_width").GetValue<int>();
		int num = 0;
		for (int i = 0; i < allItems.Count; i++)
		{
			if (!player || ((playerSortStartRow.Value <= 1 || allItems[i].m_gridPos.y >= playerSortStartRow.Value - 1) && (playerSortEndRow.Value <= 0 || allItems[i].m_gridPos.y < playerSortEndRow.Value)))
			{
				int num2 = num % value;
				int num3 = num / value + (player ? (playerSortStartRow.Value - 1) : 0);
				allItems[i].m_gridPos = new Vector2i(num2, num3);
				num++;
			}
		}
		Traverse.Create((object)inventory).Method("Changed", Array.Empty<object>()).GetValue();
	}
}