Decompiled source of DeepChest v0.1.2

DeepChest.dll

Decompiled 3 hours 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.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
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("DeepChest")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DeepChest")]
[assembly: AssemblyTitle("DeepChest")]
[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 ValheimLocalMods
{
	internal enum TransferGroup
	{
		All,
		Food,
		Gear,
		Metals,
		Materials,
		Tools,
		Trophies,
		Other
	}
	internal sealed class TransferCategories
	{
		private readonly HashSet<string> ingredients = new HashSet<string>(StringComparer.Ordinal);

		private readonly HashSet<string> metals = new HashSet<string>(StringComparer.Ordinal);

		internal TransferCategories(ObjectDB items, ZNetScene scene)
		{
			if (Object.op_Implicit((Object)(object)items))
			{
				foreach (Recipe recipe in items.m_recipes)
				{
					if (!Object.op_Implicit((Object)(object)recipe) || !Object.op_Implicit((Object)(object)recipe.m_item) || !IsFood(recipe.m_item.m_itemData) || recipe.m_resources == null)
					{
						continue;
					}
					Requirement[] resources = recipe.m_resources;
					foreach (Requirement val in resources)
					{
						if (val != null && val.m_amount > 0)
						{
							AddItemName(ingredients, val.m_resItem);
						}
					}
				}
			}
			if (!Object.op_Implicit((Object)(object)scene))
			{
				return;
			}
			CookingStation val2 = default(CookingStation);
			foreach (GameObject prefab3 in scene.m_prefabs)
			{
				if (!Object.op_Implicit((Object)(object)prefab3) || !prefab3.TryGetComponent<CookingStation>(ref val2))
				{
					continue;
				}
				foreach (ItemConversion item2 in val2.m_conversion)
				{
					if (Object.op_Implicit((Object)(object)item2?.m_to) && IsFood(item2.m_to.m_itemData))
					{
						AddItemName(ingredients, item2.m_from);
					}
				}
			}
			GameObject prefab = scene.GetPrefab("windmill");
			Smelter val3 = default(Smelter);
			if (Object.op_Implicit((Object)(object)prefab) && prefab.TryGetComponent<Smelter>(ref val3))
			{
				foreach (ItemConversion item3 in val3.m_conversion)
				{
					if (Object.op_Implicit((Object)(object)item3?.m_to) && ingredients.Contains(item3.m_to.m_itemData.m_shared.m_name))
					{
						AddItemName(ingredients, item3.m_from);
					}
				}
			}
			string[] array = new string[2] { "smelter", "blastfurnace" };
			Smelter val4 = default(Smelter);
			foreach (string text in array)
			{
				GameObject prefab2 = scene.GetPrefab(text);
				if (!Object.op_Implicit((Object)(object)prefab2) || !prefab2.TryGetComponent<Smelter>(ref val4))
				{
					continue;
				}
				foreach (ItemConversion item4 in val4.m_conversion)
				{
					AddItemName(metals, item4?.m_from);
					AddItemName(metals, item4?.m_to);
				}
			}
			array = new string[3] { "Bronze", "BronzeNails", "IronNails" };
			ItemDrop item = default(ItemDrop);
			foreach (string text2 in array)
			{
				GameObject val5 = (Object.op_Implicit((Object)(object)items) ? items.GetItemPrefab(text2) : null);
				if (Object.op_Implicit((Object)(object)val5) && val5.TryGetComponent<ItemDrop>(ref item))
				{
					AddItemName(metals, item);
				}
			}
		}

		internal TransferGroup GroupOf(ItemData item)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected I4, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Invalid comparison between Unknown and I4
			SharedData shared = item.m_shared;
			if (IsFood(item) || (int)shared.m_itemType == 21)
			{
				return TransferGroup.Food;
			}
			if (metals.Contains(shared.m_name))
			{
				return TransferGroup.Metals;
			}
			ItemType itemType = shared.m_itemType;
			switch (itemType - 1)
			{
			case 0:
				if (!ingredients.Contains(shared.m_name))
				{
					return TransferGroup.Materials;
				}
				return TransferGroup.Food;
			case 14:
			case 18:
				return TransferGroup.Tools;
			case 12:
				return TransferGroup.Trophies;
			case 2:
			case 13:
			case 21:
				if ((int)shared.m_skillType != 12)
				{
					return TransferGroup.Gear;
				}
				return TransferGroup.Tools;
			case 3:
			case 4:
			case 5:
			case 6:
			case 8:
			case 10:
			case 11:
			case 16:
			case 17:
			case 22:
			case 23:
				return TransferGroup.Gear;
			default:
				if (!ingredients.Contains(shared.m_name))
				{
					return TransferGroup.Other;
				}
				return TransferGroup.Food;
			}
		}

		private static bool IsFood(ItemData item)
		{
			SharedData val = item?.m_shared;
			if (val != null)
			{
				if (!(val.m_food > 0f) && !(val.m_foodStamina > 0f))
				{
					return val.m_foodEitr > 0f;
				}
				return true;
			}
			return false;
		}

		private static void AddItemName(HashSet<string> names, ItemDrop item)
		{
			if (Object.op_Implicit((Object)(object)item))
			{
				string text = item.m_itemData?.m_shared?.m_name;
				if (text != null)
				{
					names.Add(text);
				}
			}
		}
	}
	internal static class ChestTransfer
	{
		internal static (int moved, int left) Move(Inventory source, Inventory destination, Predicate<ItemData> include)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			if (source == destination)
			{
				return (moved: 0, left: 0);
			}
			List<ItemData> list = new List<ItemData>(destination.GetAllItems());
			Queue<Vector2i> queue = new Queue<Vector2i>();
			for (int i = 0; i < destination.GetHeight(); i++)
			{
				for (int j = 0; j < destination.GetWidth(); j++)
				{
					if (destination.GetItemAt(j, i) == null)
					{
						queue.Enqueue(new Vector2i(j, i));
					}
				}
			}
			int num = 0;
			int num2 = 0;
			ItemData[] array = source.GetAllItems().ToArray();
			foreach (ItemData val in array)
			{
				if (val.m_stack <= 0 || !source.ContainsItem(val) || !include(val))
				{
					continue;
				}
				int stack = val.m_stack;
				if (val.m_shared.m_maxStackSize > 1)
				{
					foreach (ItemData item in list)
					{
						if (val.m_stack == 0)
						{
							break;
						}
						int num3 = item.m_shared.m_maxStackSize - item.m_stack;
						if (num3 > 0 && CanMerge(val, item))
						{
							destination.MoveItemToThis(source, val, Math.Min(num3, val.m_stack), item.m_gridPos.x, item.m_gridPos.y);
						}
					}
				}
				while (val.m_stack > 0 && queue.Count != 0)
				{
					Vector2i val2 = queue.Dequeue();
					int num4 = Math.Min(val.m_stack, val.m_shared.m_maxStackSize);
					if (destination.MoveItemToThis(source, val, num4, val2.x, val2.y))
					{
						ItemData itemAt = destination.GetItemAt(val2.x, val2.y);
						if (itemAt != null)
						{
							list.Add(itemAt);
						}
					}
				}
				int num5 = (source.ContainsItem(val) ? val.m_stack : 0);
				num += stack - num5;
				num2 += num5;
			}
			return (moved: num, left: num2);
		}

		private static bool CanMerge(ItemData item, ItemData candidate)
		{
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Invalid comparison between Unknown and I4
			if (!item.IsSameType(candidate) || (Object)(object)item.m_dropPrefab != (Object)(object)candidate.m_dropPrefab || item.m_quality != candidate.m_quality || item.m_variant != candidate.m_variant || item.m_durability != candidate.m_durability || item.m_equipped != candidate.m_equipped || item.m_cheated != candidate.m_cheated || item.m_crafterID != candidate.m_crafterID || item.m_crafterName != candidate.m_crafterName || item.m_customData.Count != candidate.m_customData.Count)
			{
				return false;
			}
			if ((int)item.m_shared.m_itemType == 13 && item.m_pickedUp != candidate.m_pickedUp)
			{
				return false;
			}
			foreach (KeyValuePair<string, string> customDatum in item.m_customData)
			{
				if (!candidate.m_customData.TryGetValue(customDatum.Key, out var value) || customDatum.Value != value)
				{
					return false;
				}
			}
			return true;
		}
	}
	[BepInPlugin("local.valheim.deepchest", "Deep Chest", "0.1.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class DeepChestPlugin : BaseUnityPlugin
	{
		[HarmonyPatch]
		private static class ChestPatches
		{
			[HarmonyPatch(typeof(Container), "Awake")]
			[HarmonyPostfix]
			private static void RegisterInventory(Container __instance)
			{
				if (IsDeepChest(__instance))
				{
					Inventory inventory = __instance.GetInventory();
					if (inventory != null)
					{
						Inventories.Add(inventory, __instance);
					}
				}
			}

			[HarmonyPatch(typeof(Container), "TakeAll")]
			[HarmonyPrefix]
			private static bool TakeAll(Container __instance)
			{
				if (IsDeepChest(__instance))
				{
					return Owns(__instance);
				}
				return true;
			}

			[HarmonyPatch(typeof(Container), "RPC_TakeAllResponse")]
			[HarmonyPrefix]
			private static bool TakeAllResponse(Container __instance)
			{
				return TakeAll(__instance);
			}

			[HarmonyPatch(typeof(InventoryGui), "UpdateContainer")]
			[HarmonyPrefix]
			private static bool RefreshOnOpen(InventoryGui __instance, Container ___m_currentContainer)
			{
				if (!IsDeepChest(___m_currentContainer))
				{
					return true;
				}
				if (!Owns(___m_currentContainer))
				{
					if (!enforceOwnershipInGui)
					{
						return true;
					}
					if (((Component)__instance.m_container).gameObject.activeSelf && __instance.ContainerGrid.GetInventory() == ___m_currentContainer.GetInventory())
					{
						__instance.Hide();
					}
					else
					{
						((Component)__instance.m_container).gameObject.SetActive(false);
					}
					return false;
				}
				if (!___m_currentContainer.IsInUse())
				{
					Refresh(___m_currentContainer);
				}
				return true;
			}

			[HarmonyPatch(typeof(Inventory), "StackAll")]
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static bool StackAll(Inventory __instance, Inventory fromInventory)
			{
				if (CanWrite(__instance))
				{
					return CanWrite(fromInventory);
				}
				return false;
			}

			[HarmonyPatch(typeof(Inventory), "MoveAll")]
			[HarmonyPrefix]
			private static bool MoveAll(Inventory __instance, Inventory fromInventory)
			{
				if (CanWrite(__instance))
				{
					return CanWrite(fromInventory);
				}
				return false;
			}

			[HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[]
			{
				typeof(Inventory),
				typeof(ItemData)
			})]
			[HarmonyPrefix]
			private static bool MoveItem(Inventory __instance, Inventory fromInventory)
			{
				if (CanWrite(__instance))
				{
					return CanWrite(fromInventory);
				}
				return false;
			}

			[HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[]
			{
				typeof(Inventory),
				typeof(ItemData),
				typeof(int),
				typeof(int),
				typeof(int)
			})]
			[HarmonyPrefix]
			private static bool MoveStack(Inventory __instance, Inventory fromInventory)
			{
				if (CanWrite(__instance))
				{
					return CanWrite(fromInventory);
				}
				return false;
			}

			[HarmonyPatch(typeof(InventoryGrid), "DropItem")]
			[HarmonyPrefix]
			private static bool Drop(InventoryGrid __instance, Inventory __0)
			{
				if (CanWrite(__instance.GetInventory()))
				{
					return CanWrite(__0);
				}
				return false;
			}
		}

		internal const string Id = "local.valheim.deepchest";

		internal const string PrefabName = "LocalMods_DeepChest";

		private const string MultiUserId = "com.maxsch.valheim.MultiUserChest";

		private const int Columns = 8;

		private const int Rows = 32;

		private static readonly ConditionalWeakTable<Inventory, Container> Inventories = new ConditionalWeakTable<Inventory, Container>();

		private static readonly FieldRef<Container, ZNetView> NetworkView = AccessTools.FieldRefAccess<Container, ZNetView>("m_nview");

		private static readonly Func<Container, bool> Load = AccessTools.MethodDelegate<Func<Container, bool>>(AccessTools.Method(typeof(Container), "Load", (Type[])null, (Type[])null), (object)null, true);

		private static Func<object, Inventory> multiUserInventory;

		private static bool enforceOwnershipInGui;

		private Harmony harmony;

		private Harmony multiUserPatches;

		private Harmony storagePatches;

		private Harmony storageFilter;

		private Harmony transferPatches;

		private StorageMasterBridge storageMaster;

		private StorageMasterTransfer storageTransfer;

		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			harmony = new Harmony("local.valheim.deepchest");
			harmony.PatchAll(typeof(ChestPatches));
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			string text = "English";
			string text2 = "piece_localmods_deepchest";
			localization.AddTranslation(ref text, ref text2, "Deep Chest");
			text = "English";
			text2 = "piece_localmods_deepchest_description";
			localization.AddTranslation(ref text, ref text2, "A chest with 256 slots. Scroll to reach every row.");
			PrefabManager.OnVanillaPrefabsAvailable += RegisterChest;
			harmony.PatchAll(typeof(DeepChestSearch));
			if (Chainloader.PluginInfos.TryGetValue("com.maxsch.valheim.MultiUserChest", out var value))
			{
				multiUserPatches = new Harmony("local.valheim.deepchest.multiuser");
				try
				{
					KeepExclusiveOwnership(((object)value.Instance).GetType().Assembly);
				}
				catch (Exception arg)
				{
					multiUserPatches.UnpatchSelf();
					multiUserInventory = null;
					enforceOwnershipInGui = true;
					((BaseUnityPlugin)this).Logger.LogWarning((object)$"Could not configure MultiUserChest compatibility. Deep Chest requires local ownership to open. {arg}");
				}
			}
			if (Chainloader.PluginInfos.TryGetValue("charmingbeaver.valheim.storagemaster", out var value2))
			{
				ConfigureStorageMaster(value2);
			}
		}

		private void RegisterChest()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			PrefabManager.OnVanillaPrefabsAvailable -= RegisterChest;
			PieceConfig val = new PieceConfig
			{
				Name = "$piece_localmods_deepchest",
				Description = "$piece_localmods_deepchest_description",
				PieceTable = PieceTables.Hammer,
				Category = PieceCategories.Furniture,
				CraftingStation = CraftingStations.Workbench
			};
			val.AddRequirement("Wood", 30, true);
			CustomPiece val2 = new CustomPiece("LocalMods_DeepChest", "piece_chest_blackmetal", val);
			Container val3 = default(Container);
			if (!Object.op_Implicit((Object)(object)val2.PiecePrefab) || !val2.PiecePrefab.TryGetComponent<Container>(ref val3))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"The black metal chest prefab was unavailable. Deep Chest could not register.");
				return;
			}
			val3.m_name = val.Name;
			val3.m_width = 8;
			val3.m_height = 32;
			val3.m_privacy = (PrivacySetting)2;
			val3.m_checkGuardStone = true;
			PieceManager.Instance.AddPiece(val2);
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Registered Deep Chest with {256} slots.");
		}

		private void Update()
		{
			storageMaster?.Update();
			storageTransfer?.Update();
		}

		private void ConfigureStorageMaster(PluginInfo storage)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)storage.Instance))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Storage Master did not load. Deep Chest is available for direct access.");
				return;
			}
			Assembly assembly = ((object)storage.Instance).GetType().Assembly;
			storagePatches = new Harmony("local.valheim.deepchest.storagemaster");
			try
			{
				storageMaster = new StorageMasterBridge(assembly, storagePatches, ((BaseUnityPlugin)this).Logger);
			}
			catch (Exception arg)
			{
				storagePatches.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogWarning((object)$"Could not configure Storage Master ownership checks. Deep Chest is available for direct access. {arg}");
			}
			if (storageMaster != null)
			{
				transferPatches = new Harmony("local.valheim.deepchest.transfer");
				try
				{
					storageTransfer = new StorageMasterTransfer(assembly, storageMaster, transferPatches, ((BaseUnityPlugin)this).Logger);
				}
				catch (Exception arg2)
				{
					transferPatches.UnpatchSelf();
					((BaseUnityPlugin)this).Logger.LogWarning((object)$"Could not add the Storage Master transfer panel. {arg2}");
				}
			}
			bool guardInstalled = Chainloader.PluginInfos.ContainsKey("local.valheim.storageguard");
			if (storageMaster != null && guardInstalled)
			{
				return;
			}
			bool directAccessOnly = storageMaster == null;
			storageFilter = new Harmony("local.valheim.deepchest.storagefilter");
			try
			{
				StorageMasterChestFilter.Install(assembly, storageFilter, (Container chest) => (directAccessOnly && IsDeepChest(chest)) || (!guardInstalled && StorageMasterChestFilter.IsLegacyChest(chest)));
			}
			catch (Exception arg3)
			{
				storageFilter.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogWarning((object)$"Could not filter chests from Storage Master. {arg3}");
			}
		}

		private void KeepExclusiveOwnership(Assembly assembly)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			Type type = assembly.GetType("MultiUserChest.InventoryIgnore");
			Type type2 = assembly.GetType("MultiUserChest.InventoryOwner");
			PropertyInfo inventoryProperty = type2?.GetProperty("Inventory");
			if (inventoryProperty == null || type == null)
			{
				throw new InvalidOperationException("Cannot enable exclusive Deep Chest access with this version of MultiUserChest.");
			}
			multiUserInventory = delegate(object item)
			{
				object? value = inventoryProperty.GetValue(item);
				return (Inventory)((value is Inventory) ? value : null);
			};
			multiUserPatches.Patch((MethodBase)AccessTools.Method(type, "IgnoreInventory", new Type[1] { typeof(Container) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(DeepChestPlugin), "IgnoreContainer", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			multiUserPatches.Patch((MethodBase)AccessTools.Method(type, "IgnoreInventory", new Type[1] { type2 }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(DeepChestPlugin), "IgnoreInventoryOwner", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void IgnoreContainer(Container __0, ref bool __result)
		{
			__result |= IsDeepChest(__0);
		}

		private static void IgnoreInventoryOwner(object __0, ref bool __result)
		{
			if (!__result && __0 != null)
			{
				Inventory val = multiUserInventory(__0);
				if (val != null && Inventories.TryGetValue(val, out var _))
				{
					__result = true;
				}
			}
		}

		internal static bool IsDeepChest(Container container)
		{
			if (Object.op_Implicit((Object)(object)container))
			{
				return Utils.GetPrefabName(((Object)container).name) == "LocalMods_DeepChest";
			}
			return false;
		}

		internal static bool Owns(Container container)
		{
			if (Object.op_Implicit((Object)(object)container) && Object.op_Implicit((Object)(object)NetworkView.Invoke(container)) && NetworkView.Invoke(container).IsValid())
			{
				return NetworkView.Invoke(container).IsOwner();
			}
			return false;
		}

		internal static void Refresh(Container container)
		{
			Load(container);
		}

		private static bool CanWrite(Inventory inventory)
		{
			if (inventory != null && Inventories.TryGetValue(inventory, out var value))
			{
				return Owns(value);
			}
			return true;
		}

		private void OnDestroy()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= RegisterChest;
			Harmony obj = transferPatches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			storageTransfer?.Dispose();
			Harmony obj2 = multiUserPatches;
			if (obj2 != null)
			{
				obj2.UnpatchSelf();
			}
			Harmony obj3 = storagePatches;
			if (obj3 != null)
			{
				obj3.UnpatchSelf();
			}
			Harmony obj4 = storageFilter;
			if (obj4 != null)
			{
				obj4.UnpatchSelf();
			}
			DeepChestSearch.Dispose();
			Harmony obj5 = harmony;
			if (obj5 != null)
			{
				obj5.UnpatchSelf();
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "Update")]
	internal static class DeepChestSearch
	{
		private static readonly FieldRef<InventoryGrid, List<InventoryElement>> Elements = AccessTools.FieldRefAccess<InventoryGrid, List<InventoryElement>>("m_elements");

		private static readonly Dictionary<string, bool> Matches = new Dictionary<string, bool>(StringComparer.Ordinal);

		private static TMP_InputField field;

		private static Container openChest;

		private static string query = string.Empty;

		private static bool findFirst;

		[HarmonyPrefix]
		private static void PreserveSearchInput(Container ___m_currentContainer)
		{
			if (Object.op_Implicit((Object)(object)field) && field.isFocused && ((Component)field).gameObject.activeInHierarchy && (Object)(object)openChest == (Object)(object)___m_currentContainer)
			{
				ZInput.ResetButtonStatus("Use");
				ZInput.ResetButtonStatus("Inventory");
			}
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Update(InventoryGui __instance, Container ___m_currentContainer)
		{
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			InventoryGrid containerGrid = __instance.ContainerGrid;
			if (!DeepChestPlugin.IsDeepChest(___m_currentContainer) || !DeepChestPlugin.Owns(___m_currentContainer) || !((Component)__instance.m_container).gameObject.activeInHierarchy || containerGrid.GetInventory() != ___m_currentContainer.GetInventory())
			{
				if (Object.op_Implicit((Object)(object)field) && ((Component)field).gameObject.activeSelf)
				{
					((Component)field).gameObject.SetActive(false);
				}
				openChest = null;
				return;
			}
			if (!Object.op_Implicit((Object)(object)field) || (Object)(object)((Component)field).transform.parent != (Object)(object)__instance.m_container)
			{
				Dispose();
				field = CreateField(__instance);
			}
			if ((Object)(object)openChest != (Object)(object)___m_currentContainer)
			{
				openChest = ___m_currentContainer;
				field.SetTextWithoutNotify(string.Empty);
				SetQuery(string.Empty);
				((Component)field).gameObject.SetActive(true);
			}
			if (query.Length == 0)
			{
				return;
			}
			Inventory inventory = containerGrid.GetInventory();
			int width = inventory.GetWidth();
			List<InventoryElement> list = Elements.Invoke(containerGrid);
			int num = list.Count;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				Vector2i gridPos = allItem.m_gridPos;
				int num2 = gridPos.y * width + gridPos.x;
				if (gridPos.x >= 0 && gridPos.x < width && num2 >= 0 && num2 < list.Count)
				{
					string name = allItem.m_shared.m_name;
					if (!Matches.TryGetValue(name, out var value))
					{
						value = Localization.instance.Localize(name).IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0;
						Matches.Add(name, value);
					}
					if (value)
					{
						num = Mathf.Min(num, num2);
						continue;
					}
					Image icon = list[num2].m_icon;
					Color color = ((Graphic)icon).color;
					color.a *= 0.22f;
					((Graphic)icon).color = color;
				}
			}
			if (findFirst && num < list.Count)
			{
				Reveal(containerGrid, list[num].GetElementRectTransform());
			}
			findFirst = false;
		}

		private static void SetQuery(string value)
		{
			query = value.Trim();
			Matches.Clear();
			findFirst = query.Length != 0;
		}

		private static void Reveal(InventoryGrid grid, RectTransform item)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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_007d: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			ScrollRect componentInParent = ((Component)grid.m_gridRoot).GetComponentInParent<ScrollRect>();
			if (Object.op_Implicit((Object)(object)componentInParent) && componentInParent.vertical)
			{
				RectTransform val = (RectTransform)(Object.op_Implicit((Object)(object)componentInParent.viewport) ? ((object)componentInParent.viewport) : ((object)(RectTransform)((Component)componentInParent).transform));
				Rect rect = componentInParent.content.rect;
				float height = ((Rect)(ref rect)).height;
				rect = val.rect;
				float num = height - ((Rect)(ref rect)).height;
				if (!(num <= 0f))
				{
					rect = item.rect;
					float y = ((Transform)val).InverseTransformPoint(((Transform)item).TransformPoint(Vector2.op_Implicit(((Rect)(ref rect)).center))).y;
					componentInParent.StopMovement();
					float verticalNormalizedPosition = componentInParent.verticalNormalizedPosition;
					rect = val.rect;
					componentInParent.verticalNormalizedPosition = Mathf.Clamp01(verticalNormalizedPosition + (y - ((Rect)(ref rect)).center.y) / num);
				}
			}
		}

		private static TMP_InputField CreateField(InventoryGui gui)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			RectTransform container = gui.m_container;
			GameObject val = new GameObject("Deep Chest Search", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.SetActive(false);
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent((Transform)(object)container, false);
			Vector2 anchorMin = (val2.anchorMax = Vector2.zero);
			val2.anchorMin = anchorMin;
			val2.pivot = new Vector2(0f, 1f);
			val2.anchoredPosition = new Vector2(8f, -5f);
			val2.sizeDelta = new Vector2(160f, 27f);
			Image component = val.GetComponent<Image>();
			((Graphic)component).color = new Color(0.08f, 0.07f, 0.06f, 0.95f);
			RectTransform val3 = (RectTransform)new GameObject("Text Area", new Type[2]
			{
				typeof(RectTransform),
				typeof(RectMask2D)
			}).transform;
			((Transform)val3).SetParent((Transform)(object)val2, false);
			val3.anchorMin = Vector2.zero;
			val3.anchorMax = Vector2.one;
			val3.offsetMin = new Vector2(7f, 1f);
			val3.offsetMax = new Vector2(-7f, -1f);
			TMP_InputField obj = val.AddComponent<TMP_InputField>();
			((Selectable)obj).targetGraphic = (Graphic)(object)component;
			obj.textViewport = val3;
			obj.textComponent = (TMP_Text)(object)MakeText("Text", val3, gui.m_containerName.font);
			TextMeshProUGUI val4 = MakeText("Placeholder", val3, gui.m_containerName.font);
			((TMP_Text)val4).text = "Find item";
			((Graphic)val4).color = new Color(0.86f, 0.8f, 0.68f, 0.68f);
			obj.placeholder = (Graphic)(object)val4;
			obj.characterLimit = 80;
			obj.lineType = (LineType)0;
			((UnityEvent<string>)(object)obj.onValueChanged).AddListener((UnityAction<string>)SetQuery);
			return obj;
		}

		private static TextMeshProUGUI MakeText(string name, RectTransform parent, TMP_FontAsset font)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_0027: 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_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)
			//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_004a: 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_0050: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
			val.SetActive(false);
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent((Transform)(object)parent, false);
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			Vector2 offsetMin = (val2.offsetMax = Vector2.zero);
			val2.offsetMin = offsetMin;
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj).font = font;
			((TMP_Text)obj).fontSize = 16f;
			((TMP_Text)obj).alignment = (TextAlignmentOptions)4097;
			((Graphic)obj).raycastTarget = false;
			((TMP_Text)obj).richText = false;
			val.SetActive(true);
			return obj;
		}

		internal static void Dispose()
		{
			if (Object.op_Implicit((Object)(object)field))
			{
				Object.Destroy((Object)(object)((Component)field).gameObject);
			}
			field = null;
			openChest = null;
			SetQuery(string.Empty);
		}
	}
	internal sealed class StorageMasterBridge
	{
		private sealed class Claim
		{
			internal Action<bool> Callback;

			internal float Expires;

			internal bool Granted;
		}

		private static StorageMasterBridge instance;

		private readonly Dictionary<Container, Claim> claims = new Dictionary<Container, Claim>();

		private readonly ConditionalWeakTable<Container, Claim> cancelledClaims = new ConditionalWeakTable<Container, Claim>();

		private readonly List<Container> checking = new List<Container>();

		private readonly FieldInfo cards;

		private readonly FieldInfo cardChest;

		private readonly FieldInfo cardClaimed;

		private readonly Action close;

		private readonly Action<Container> forget;

		internal StorageMasterBridge(Assembly assembly, Harmony harmony, ManualLogSource log)
		{
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Expected O, but got Unknown
			Harmony harmony2 = harmony;
			base..ctor();
			Type type = assembly.GetType("StorageMaster.ChestAccess");
			Type type2 = assembly.GetType("StorageMaster.UI.StorageWindow");
			Type type3 = type2?.GetNestedType("Card", BindingFlags.NonPublic);
			if (type == null || type2 == null || type3 == null)
			{
				throw new InvalidOperationException("This version of Storage Master has an unsupported storage API.");
			}
			cards = AccessTools.Field(type2, "_cards");
			cardChest = AccessTools.Field(type3, "Chest");
			cardClaimed = AccessTools.Field(type3, "Claimed");
			close = AccessTools.MethodDelegate<Action>(AccessTools.Method(type2, "Close", (Type[])null, (Type[])null), (object)null, true);
			forget = AccessTools.MethodDelegate<Action<Container>>(AccessTools.Method(type, "Forget", (Type[])null, (Type[])null), (object)null, true);
			if (cards == null || cardChest == null || cardClaimed == null)
			{
				throw new InvalidOperationException("Could not identify Storage Master's inventory cards.");
			}
			instance = this;
			Patch(type, "Request", "Request");
			Patch(type, "Forget", "Forget");
			string[] array = new string[7] { "Update", "OnSelected", "TakeAll", "GatherInto", "TidyUp", "SortAll", "QuickStackHere" };
			foreach (string method in array)
			{
				Patch(type2, method, "CheckWindowOwnership");
			}
			harmony2.Patch((MethodBase)AccessTools.Method(typeof(Container), "RPC_StackResponse", (Type[])null, (Type[])null), new HarmonyMethod(typeof(StorageMasterBridge), "DiscardCancelledResponse", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log.LogInfo((object)"Installed Storage Master ownership checks for sorting and bulk transfers.");
			void Patch(Type type4, string text, string patch)
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Expected O, but got Unknown
				MethodInfo methodInfo = ((type4 == null) ? null : AccessTools.Method(type4, text, (Type[])null, (Type[])null));
				if (methodInfo == null)
				{
					throw new MissingMethodException(type4?.FullName, text);
				}
				HarmonyMethod val = new HarmonyMethod(typeof(StorageMasterBridge), patch, (Type[])null);
				harmony2.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool Request(Container __0, ref Action<bool> __1)
		{
			if (!Object.op_Implicit((Object)(object)__0) || instance.claims.ContainsKey(__0))
			{
				__1(obj: false);
				return false;
			}
			Claim claim = new Claim
			{
				Callback = __1,
				Expires = Time.unscaledTime + 3f
			};
			instance.claims.Add(__0, claim);
			Container container = __0;
			__1 = delegate(bool granted)
			{
				if (granted)
				{
					claim.Granted = true;
				}
				else if (instance.claims.Remove(container))
				{
					claim.Callback(obj: false);
				}
			};
			return true;
		}

		internal void Update()
		{
			checking.Clear();
			foreach (Container key in claims.Keys)
			{
				checking.Add(key);
			}
			foreach (Container item in checking)
			{
				if (claims.TryGetValue(item, out var value))
				{
					if (value.Granted && DeepChestPlugin.Owns(item) && Object.op_Implicit((Object)(object)Player.m_localPlayer))
					{
						claims.Remove(item);
						DeepChestPlugin.Refresh(item);
						value.Callback(obj: true);
					}
					else if (!Object.op_Implicit((Object)(object)item) || Time.unscaledTime >= value.Expires)
					{
						forget(item);
						value.Callback(obj: false);
					}
				}
			}
		}

		internal void GetClaimedChests(List<Container> result)
		{
			result.Clear();
			if (!(cards.GetValue(null) is IList list))
			{
				return;
			}
			foreach (object item in list)
			{
				if ((bool)cardClaimed.GetValue(item))
				{
					object? value = cardChest.GetValue(item);
					Container val = (Container)((value is Container) ? value : null);
					if (val != null && Object.op_Implicit((Object)(object)val))
					{
						result.Add(val);
					}
				}
			}
		}

		private static void Forget(Container __0)
		{
			if (instance.claims.TryGetValue(__0, out var value) && instance.claims.Remove(__0) && !value.Granted)
			{
				instance.cancelledClaims.Remove(__0);
				instance.cancelledClaims.Add(__0, value);
			}
		}

		private static bool DiscardCancelledResponse(Container __instance)
		{
			if (instance.cancelledClaims.Remove(__instance))
			{
				return instance.claims.ContainsKey(__instance);
			}
			return true;
		}

		private static bool CheckWindowOwnership()
		{
			if (!(instance.cards.GetValue(null) is IList list))
			{
				return true;
			}
			foreach (object item in list)
			{
				if (!(bool)instance.cardClaimed.GetValue(item))
				{
					continue;
				}
				object? value = instance.cardChest.GetValue(item);
				Container val = (Container)((value is Container) ? value : null);
				if (val == null || !DeepChestPlugin.Owns(val))
				{
					instance.close();
					if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
					{
						((Character)Player.m_localPlayer).Message((MessageType)2, "Storage access changed. Reopen Storage Master to continue", 0, (Sprite)null, false);
					}
					return false;
				}
			}
			return true;
		}
	}
	internal sealed class StorageMasterTransfer
	{
		private delegate RectTransform MakeScrollList(Transform parent, string name, out ScrollRect scroll, float spacing, int padding);

		private static readonly (TransferGroup group, string label)[] Actions = new(TransferGroup, string)[8]
		{
			(TransferGroup.All, "Move all"),
			(TransferGroup.Food, "Food & ingredients"),
			(TransferGroup.Gear, "Weapons & armor"),
			(TransferGroup.Metals, "Metals"),
			(TransferGroup.Materials, "Materials"),
			(TransferGroup.Tools, "Tools"),
			(TransferGroup.Trophies, "Trophies"),
			(TransferGroup.Other, "Other")
		};

		private static StorageMasterTransfer instance;

		private static readonly Color SelectedColor = new Color(1f, 0.65f, 0.25f);

		private readonly StorageMasterBridge bridge;

		private readonly ManualLogSource log;

		private readonly FieldInfo windowRoot;

		private readonly FieldInfo heldItem;

		private readonly ConfigEntry<float> range;

		private readonly Func<Container, Player, long, float, bool> hasAccess;

		private readonly Func<Container, bool> isSkipped;

		private readonly Func<Container, string> chestLabel;

		private readonly Func<Player, ItemData, bool> canMoveFromInventory;

		private readonly Func<Transform, string, RectTransform> rect;

		private readonly Func<Transform, string, Image> panel;

		private readonly Func<Transform, string, UnityAction, float, float, bool, Button> button;

		private readonly Func<Transform, string, float, Color?, TextAlignmentOptions, bool, string, TextMeshProUGUI> text;

		private readonly MakeScrollList scrollList;

		private readonly Action<Transform> clear;

		private readonly List<Container> available = new List<Container>();

		private readonly List<Container> shown = new List<Container>();

		private readonly List<(Container chest, bool from, TMP_Text label)> rows = new List<(Container, bool, TMP_Text)>();

		private readonly List<Button> actionButtons = new List<Button>();

		private GameObject root;

		private Button openButton;

		private RectTransform overlay;

		private ScrollRect sources;

		private ScrollRect destinations;

		private TMP_Text status;

		private Container source;

		private Container destination;

		private bool fromInventory;

		private TransferCategories categories;

		private float nextRefresh;

		internal StorageMasterTransfer(Assembly storageMaster, StorageMasterBridge bridge, Harmony harmony, ManualLogSource log)
		{
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Expected O, but got Unknown
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Expected O, but got Unknown
			this.bridge = bridge;
			this.log = log;
			Type type = storageMaster.GetType("StorageMaster.UI.StorageWindow", throwOnError: true);
			Type type2 = storageMaster.GetType("StorageMaster.ChestAccess", throwOnError: true);
			Type type3 = storageMaster.GetType("StorageMaster.UI.UIKit", throwOnError: true);
			windowRoot = AccessTools.Field(type, "_root") ?? throw new MissingFieldException(type.FullName, "_root");
			heldItem = AccessTools.Field(type, "_heldItem") ?? throw new MissingFieldException(type.FullName, "_heldItem");
			range = (ConfigEntry<float>)AccessTools.Field(storageMaster.GetType("StorageMaster.Plugin", throwOnError: true), "StorageRange").GetValue(null);
			hasAccess = Bind<Func<Container, Player, long, float, bool>>(type2, "Usable");
			chestLabel = Bind<Func<Container, string>>(type2, "GetLabel");
			isSkipped = Bind<Func<Container, bool>>(storageMaster.GetType("StorageMaster.Exclusions", throwOnError: true), "IsExcluded");
			canMoveFromInventory = Bind<Func<Player, ItemData, bool>>(storageMaster.GetType("StorageMaster.QuickStack", throwOnError: true), "CanMove");
			rect = Bind<Func<Transform, string, RectTransform>>(type3, "Rect");
			panel = Bind<Func<Transform, string, Image>>(type3, "DarkPanel");
			button = Bind<Func<Transform, string, UnityAction, float, float, bool, Button>>(type3, "Button");
			text = Bind<Func<Transform, string, float, Color?, TextAlignmentOptions, bool, string, TextMeshProUGUI>>(type3, "Text");
			scrollList = Bind<MakeScrollList>(type3, "ScrollList");
			clear = Bind<Action<Transform>>(type3, "Clear");
			instance = this;
			harmony.Patch((MethodBase)AccessTools.Method(type, "Build", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(StorageMasterTransfer), "WindowBuilt", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(type, "Close", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(StorageMasterTransfer), "WindowClosed", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log.LogInfo((object)"Installed the Storage Master transfer panel.");
		}

		private static T Bind<T>(Type type, string method) where T : Delegate
		{
			return AccessTools.MethodDelegate<T>(AccessTools.Method(type, method, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, method), (object)null, true);
		}

		private static void WindowBuilt()
		{
			instance.Attach();
		}

		private static void WindowClosed()
		{
			instance.Hide();
		}

		private void Attach()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			ClearUi();
			root = (GameObject)windowRoot.GetValue(null);
			Transform val = (Object.op_Implicit((Object)(object)root) ? root.transform.Find("window") : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				log.LogWarning((object)"Could not place Transfer in the Storage Master window.");
				return;
			}
			openButton = button(val, "Transfer", new UnityAction(Show), 138f, 36f, arg6: false);
			Place((RectTransform)((Component)openButton).transform, 24f, 22f, 138f, 36f);
		}

		private void Show()
		{
			if (heldItem.GetValue(null) != null)
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "Put down the held item before transferring.", 0, (Sprite)null, false);
				}
				return;
			}
			if (!Object.op_Implicit((Object)(object)overlay))
			{
				BuildPanel();
			}
			((Transform)overlay).SetAsLastSibling();
			((Component)overlay).gameObject.SetActive(true);
			RefreshChests(force: true);
		}

		private void BuildPanel()
		{
			//IL_0027: 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_004d: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Expected O, but got Unknown
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Expected O, but got Unknown
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Expected O, but got Unknown
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Expected O, but got Unknown
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Expected O, but got Unknown
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0364: Expected O, but got Unknown
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03de: Expected O, but got Unknown
			overlay = rect(root.transform, "DeepChestTransfer");
			overlay.anchorMin = Vector2.zero;
			overlay.anchorMax = Vector2.one;
			RectTransform obj = overlay;
			Vector2 offsetMin = (overlay.offsetMax = Vector2.zero);
			obj.offsetMin = offsetMin;
			((Graphic)((Component)overlay).gameObject.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0.72f);
			RectTransform rectTransform = ((Graphic)panel((Transform)(object)overlay, "Transfer items")).rectTransform;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(0.5f, 0.5f);
			rectTransform.pivot = val;
			offsetMin = (rectTransform.anchorMax = val);
			rectTransform.anchorMin = offsetMin;
			rectTransform.anchoredPosition = Vector2.zero;
			rectTransform.sizeDelta = new Vector2(760f, 470f);
			Place(((TMP_Text)text((Transform)(object)rectTransform, "Transfer items", 32f, SelectedColor, (TextAlignmentOptions)4097, arg6: true, "title")).rectTransform, 20f, 12f, 530f, 40f);
			Place((RectTransform)((Component)button((Transform)(object)rectTransform, "Done", new UnityAction(Hide), 94f, 34f, arg6: false)).transform, 646f, 15f, 94f, 34f);
			Place(((TMP_Text)text((Transform)(object)rectTransform, "From", 23f, null, (TextAlignmentOptions)4097, arg6: false, "from")).rectTransform, 20f, 60f, 350f, 27f);
			Place(((TMP_Text)text((Transform)(object)rectTransform, "To", 23f, null, (TextAlignmentOptions)4097, arg6: false, "to")).rectTransform, 390f, 60f, 350f, 27f);
			scrollList((Transform)(object)rectTransform, "sources", out sources, 4f, 2);
			scrollList((Transform)(object)rectTransform, "destinations", out destinations, 4f, 2);
			Place((RectTransform)((Component)sources).transform, 20f, 92f, 350f, 226f);
			Place((RectTransform)((Component)destinations).transform, 390f, 92f, 350f, 226f);
			ScrollRect obj2 = sources;
			float scrollSensitivity = (destinations.scrollSensitivity = 36f);
			obj2.scrollSensitivity = scrollSensitivity;
			for (int i = 0; i < Actions.Length; i++)
			{
				(TransferGroup, string) tuple = Actions[i];
				TransferGroup group = tuple.Item1;
				string item = tuple.Item2;
				Button val3 = button((Transform)(object)rectTransform, item, (UnityAction)delegate
				{
					Move(group);
				}, 174f, 39f, arg6: false);
				Place((RectTransform)((Component)val3).transform, 20f + (float)(i % 4) * 182f, 326f + (float)(i / 4) * 46f, 174f, 39f);
				actionButtons.Add(val3);
			}
			status = (TMP_Text)(object)text((Transform)(object)rectTransform, "", 18f, null, (TextAlignmentOptions)4097, arg6: false, "status");
			Place((RectTransform)status.transform, 20f, 419f, 720f, 32f);
		}

		internal void Update()
		{
			if (Object.op_Implicit((Object)(object)overlay) && ((Component)overlay).gameObject.activeInHierarchy && Time.unscaledTime >= nextRefresh)
			{
				RefreshChests();
			}
		}

		private void RefreshChests(bool force = false)
		{
			nextRefresh = Time.unscaledTime + 0.25f;
			bridge.GetClaimedChests(available);
			Player player = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)Game.instance) || ((Character)player).IsDead() || ((Character)player).IsTeleporting())
			{
				available.Clear();
			}
			else
			{
				long playerId = Game.instance.GetPlayerProfile().GetPlayerID();
				available.RemoveAll((Container chest) => !DeepChestPlugin.Owns(chest) || !chest.IsInUse() || StorageMasterChestFilter.IsLegacyChest(chest) || isSkipped(chest) || !hasAccess(chest, player, playerId, range.Value));
			}
			if (!force && shown.SequenceEqual(available))
			{
				return;
			}
			if (!available.Contains(source))
			{
				source = null;
			}
			if (!available.Contains(destination))
			{
				destination = null;
			}
			shown.Clear();
			shown.AddRange(available);
			rows.Clear();
			clear((Transform)(object)sources.content);
			clear((Transform)(object)destinations.content);
			AddRow(null, from: true);
			foreach (Container item in shown)
			{
				AddRow(item, from: true);
				AddRow(item, from: false);
			}
			if (force)
			{
				sources.verticalNormalizedPosition = 1f;
				destinations.verticalNormalizedPosition = 1f;
			}
			UpdateSelection();
		}

		private void AddRow(Container chest, bool from)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			RectTransform arg = (from ? sources.content : destinations.content);
			Button obj = button((Transform)(object)arg, "", (UnityAction)delegate
			{
				Select(chest, from);
			}, 330f, 37f, arg6: false);
			((Component)obj).gameObject.AddComponent<LayoutElement>().preferredHeight = 37f;
			TMP_Text componentInChildren = ((Component)obj).GetComponentInChildren<TMP_Text>();
			componentInChildren.richText = false;
			rows.Add((chest, from, componentInChildren));
		}

		private void Select(Container chest, bool from)
		{
			if (from)
			{
				source = chest;
				fromInventory = chest == null;
			}
			else
			{
				destination = chest;
			}
			UpdateSelection();
		}

		private void UpdateSelection()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			foreach (var row in rows)
			{
				Container item = row.chest;
				bool item2 = row.from;
				TMP_Text item3 = row.label;
				bool flag = (item2 ? (Object.op_Implicit((Object)(object)item) ? ((Object)(object)item == (Object)(object)source) : fromInventory) : ((Object)(object)item == (Object)(object)destination));
				((Graphic)item3).color = (flag ? SelectedColor : Color.white);
				item3.text = (flag ? "> " : "") + (Object.op_Implicit((Object)(object)item) ? Describe(item) : "Your inventory");
			}
			bool flag2 = Object.op_Implicit((Object)(object)destination) && (fromInventory || (Object.op_Implicit((Object)(object)source) && (Object)(object)source != (Object)(object)destination));
			foreach (Button actionButton in actionButtons)
			{
				((Selectable)actionButton).interactable = flag2;
			}
			status.text = (flag2 ? "" : ((shown.Count == 0) ? "No available chests in range." : "Choose a source and a different destination."));
		}

		private string Describe(Container chest)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			string text = chestLabel(chest);
			if (string.IsNullOrWhiteSpace(text))
			{
				text = Localization.instance.Localize(chest.m_name);
			}
			float num = Vector3.Distance(((Component)Player.m_localPlayer).transform.position, ((Component)chest).transform.position);
			Inventory inventory = chest.GetInventory();
			return $"{text}   {num:0.#} m   {inventory.NrOfItems()}/{inventory.GetWidth() * inventory.GetHeight()} slots";
		}

		private void Move(TransferGroup group)
		{
			if (!Object.op_Implicit((Object)(object)overlay) || !((Component)overlay).gameObject.activeInHierarchy || heldItem.GetValue(null) != null)
			{
				return;
			}
			RefreshChests();
			Player player = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)destination) || !available.Contains(destination) || (!fromInventory && (!Object.op_Implicit((Object)(object)source) || (Object)(object)source == (Object)(object)destination || !available.Contains(source))))
			{
				status.text = "Choose two available inventories before moving items.";
				return;
			}
			if (group != TransferGroup.All && categories == null)
			{
				categories = new TransferCategories(ObjectDB.instance, ZNetScene.instance);
			}
			var (num, num2) = ChestTransfer.Move(fromInventory ? ((Humanoid)player).GetInventory() : source.GetInventory(), destination.GetInventory(), (ItemData item) => (!fromInventory || canMoveFromInventory(player, item)) && (group == TransferGroup.All || categories.GroupOf(item) == group));
			UpdateSelection();
			if (num2 > 0)
			{
				status.text = $"Moved {num:N0}. {num2:N0} stayed in the source because they did not fit.";
			}
			else
			{
				status.text = ((num > 0) ? string.Format("Moved {0:N0} {1}.", num, (num == 1) ? "item" : "items") : "No matching items in the source.");
			}
		}

		private void Hide()
		{
			if (Object.op_Implicit((Object)(object)overlay))
			{
				((Component)overlay).gameObject.SetActive(false);
			}
			source = (destination = null);
			fromInventory = false;
			categories = null;
		}

		private void ClearUi()
		{
			Hide();
			if (Object.op_Implicit((Object)(object)overlay))
			{
				Object.Destroy((Object)(object)((Component)overlay).gameObject);
			}
			if (Object.op_Implicit((Object)(object)openButton))
			{
				Object.Destroy((Object)(object)((Component)openButton).gameObject);
			}
			overlay = null;
			openButton = null;
			actionButtons.Clear();
			rows.Clear();
		}

		internal void Dispose()
		{
			ClearUi();
			instance = null;
		}

		private static void Place(RectTransform transform, float x, float y, float width, float height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(0f, 1f);
			transform.pivot = val;
			Vector2 anchorMin = (transform.anchorMax = val);
			transform.anchorMin = anchorMin;
			transform.anchoredPosition = new Vector2(x, 0f - y);
			transform.sizeDelta = new Vector2(width, height);
		}
	}
	internal static class StorageMasterChestFilter
	{
		internal const string StorageMasterId = "charmingbeaver.valheim.storagemaster";

		internal const string StorageGuardId = "local.valheim.storageguard";

		private static Predicate<Container> blocked;

		internal static bool IsLegacyChest(Container chest)
		{
			if (Object.op_Implicit((Object)(object)chest))
			{
				return Utils.GetPrefabName(((Object)chest).name) == "bottomless_chest";
			}
			return false;
		}

		internal static void Install(Assembly assembly, Harmony harmony, Predicate<Container> blockedChest)
		{
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Expected O, but got Unknown
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			Type type = assembly.GetType("StorageMaster.ChestAccess");
			Type type2 = assembly.GetType("StorageMaster.Sorter");
			MethodInfo methodInfo = type?.GetMethod("Usable", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[4]
			{
				typeof(Container),
				typeof(Player),
				typeof(long),
				typeof(float)
			}, null);
			MethodInfo methodInfo2 = type?.GetMethod("Request", new Type[2]
			{
				typeof(Container),
				typeof(Action<bool>)
			});
			MethodInfo methodInfo3 = type2?.GetMethod("SortContainer", new Type[2]
			{
				typeof(Container),
				typeof(bool)
			});
			if (methodInfo == null || methodInfo2 == null || methodInfo3 == null)
			{
				throw new InvalidOperationException("Storage Master's chest access and sorting methods could not be identified.");
			}
			blocked = blockedChest;
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(StorageMasterChestFilter), "Usable", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(StorageMasterChestFilter), "Request", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(StorageMasterChestFilter), "CanSort", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void Usable(Container __0, ref bool __result)
		{
			__result &= !blocked(__0);
		}

		private static bool Request(Container __0, Action<bool> __1)
		{
			if (!blocked(__0))
			{
				return true;
			}
			__1(obj: false);
			return false;
		}

		private static bool CanSort(Container __0)
		{
			return !blocked(__0);
		}
	}
}