Decompiled source of ChestListWeight v1.1.1

ChestListWeight.dll

Decompiled a day ago
using System;
using System.Diagnostics;
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 Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ChestListWeight")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1")]
[assembly: AssemblyProduct("ChestListWeight")]
[assembly: AssemblyTitle("ChestListWeight")]
[assembly: AssemblyVersion("1.1.1.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 ChestListWeight
{
	[BepInPlugin("qua8ion.valheim.chestlistweight", "ChestListWeight", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class ChestListWeightPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "qua8ion.valheim.chestlistweight";

		public const string PluginName = "ChestListWeight";

		public const string PluginVersion = "1.1.1";

		internal const string TargetGuid = "ModdedWolf.Chest_List";

		private const string TargetType = "Chest_List.UI.ChestListOverlay";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> ShowWeight;

		internal static ConfigEntry<int> Decimals;

		internal static ConfigEntry<float> IconSize;

		internal static ConfigEntry<string> IconSpriteName;

		private void Awake()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_01b3: 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)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Expected O, but got Unknown
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ShowWeight = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowWeight", true, "Show the total weight of the contents on its own line in the Chest List panel.");
			Decimals = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Decimals", 0, new ConfigDescription("Digits after the decimal point in the weight. The game itself rounds weight up to a whole number.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 2), Array.Empty<object>()));
			IconSize = ((BaseUnityPlugin)this).Config.Bind<float>("General", "IconSize", 24f, new ConfigDescription("Height of the weight icon in pixels.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(12f, 48f), Array.Empty<object>()));
			IconSpriteName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "IconSpriteName", "", "Leave empty to take the icon from the game's own inventory panel. Set a sprite name to use another one.");
			if (!Chainloader.PluginInfos.TryGetValue("ModdedWolf.Chest_List", out var value) || (Object)(object)value.Instance == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Chest List is not loaded, nothing to extend");
				return;
			}
			Type type = ((object)value.Instance).GetType().Assembly.GetType("Chest_List.UI.ChestListOverlay");
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "RefreshContents", new Type[2]
			{
				typeof(Container),
				typeof(Inventory)
			}, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(type, "ApplyPanelSize", new Type[2]
			{
				typeof(float),
				typeof(float)
			}, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("RefreshContents or ApplyPanelSize not found in Chest List " + value.Metadata.Version?.ToString() + ", nothing patched"));
				return;
			}
			WeightLine.Overlay = type;
			Harmony val = new Harmony("qua8ion.valheim.chestlistweight");
			val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(RefreshPatch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(PanelSizePatch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Weight line added to the Chest List panel");
		}
	}
	internal static class WeightLine
	{
		internal const string LineName = "Qua8ionWeightLine";

		private const float TitleBlockHeight = 38f;

		internal static Type Overlay;

		private static Sprite icon;

		private static bool iconSearched;

		internal static float Height => Mathf.Max(20f, ChestListWeightPlugin.IconSize.Value + 4f);

		internal static bool Enabled
		{
			get
			{
				if (ChestListWeightPlugin.ShowWeight != null)
				{
					return ChestListWeightPlugin.ShowWeight.Value;
				}
				return false;
			}
		}

		private static Sprite FindIcon()
		{
			if (iconSearched && (Object)(object)icon != (Object)null)
			{
				return icon;
			}
			iconSearched = true;
			string value = ChestListWeightPlugin.IconSpriteName.Value;
			if (!string.IsNullOrEmpty(value))
			{
				Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
				foreach (Sprite val in array)
				{
					if ((Object)(object)val != (Object)null && ((Object)val).name == value)
					{
						return icon = val;
					}
				}
				ChestListWeightPlugin.Log.LogWarning((object)("Sprite '" + value + "' not found, falling back to the game's own icon"));
			}
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance != (Object)null)
			{
				TMP_Text[] array2 = (TMP_Text[])(object)new TMP_Text[2] { instance.m_containerWeight, instance.m_weight };
				foreach (TMP_Text val2 in array2)
				{
					Transform val3 = (((Object)(object)val2 == (Object)null) ? null : val2.transform.parent);
					if ((Object)(object)val3 == (Object)null)
					{
						continue;
					}
					Transform val4 = val3.Find("weight_icon");
					Image val5 = (((Object)(object)val4 == (Object)null) ? null : ((Component)val4).GetComponent<Image>());
					if ((Object)(object)val5 == (Object)null)
					{
						Image[] componentsInChildren = ((Component)val3).GetComponentsInChildren<Image>(true);
						foreach (Image val6 in componentsInChildren)
						{
							if ((Object)(object)val6 != (Object)null && (Object)(object)((Component)val6).transform != (Object)(object)val3 && ((Object)val6).name.IndexOf("icon", StringComparison.OrdinalIgnoreCase) >= 0)
							{
								val5 = val6;
								break;
							}
						}
					}
					if ((Object)(object)val5 != (Object)null && (Object)(object)val5.sprite != (Object)null)
					{
						ChestListWeightPlugin.Log.LogInfo((object)("Weight icon: sprite '" + ((Object)val5.sprite).name + "' from " + ((Object)val3).name + "/" + ((Object)val5).name));
						return icon = val5.sprite;
					}
				}
			}
			return null;
		}

		internal static void Refresh(object overlayInstance, Container container)
		{
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			Traverse obj = Traverse.Create(overlayInstance);
			object value = obj.Field("_content").GetValue();
			RectTransform val = (RectTransform)((value is RectTransform) ? value : null);
			object value2 = obj.Field("_listArea").GetValue();
			RectTransform val2 = (RectTransform)((value2 is RectTransform) ? value2 : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Transform val3 = ((Transform)val).Find("Qua8ionWeightLine");
			if (!Enabled)
			{
				if ((Object)(object)val3 != (Object)null)
				{
					((Component)val3).gameObject.SetActive(false);
				}
				return;
			}
			float num = 0f;
			try
			{
				Inventory val4 = (((Object)(object)container == (Object)null) ? null : container.GetInventory());
				if (val4 == null)
				{
					return;
				}
				num = val4.GetTotalWeight();
			}
			catch (Exception ex)
			{
				ChestListWeightPlugin.Log.LogWarning((object)("Could not read the container weight: " + ex.Message));
				return;
			}
			GameObject val5 = (((Object)(object)val3 != (Object)null) ? ((Component)val3).gameObject : Build(val));
			if ((Object)(object)val5 == (Object)null)
			{
				return;
			}
			val5.SetActive(true);
			if ((Object)(object)val2 != (Object)null)
			{
				val2.offsetMax = new Vector2(0f, 0f - (38f + Height));
			}
			Image componentInChildren = val5.GetComponentInChildren<Image>(true);
			TextMeshProUGUI componentInChildren2 = val5.GetComponentInChildren<TextMeshProUGUI>(true);
			Sprite val6 = FindIcon();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.sprite = val6;
				((Component)componentInChildren).gameObject.SetActive((Object)(object)val6 != (Object)null);
				LayoutElement component = ((Component)componentInChildren).GetComponent<LayoutElement>();
				if ((Object)(object)component != (Object)null)
				{
					component.preferredWidth = ChestListWeightPlugin.IconSize.Value;
					component.preferredHeight = ChestListWeightPlugin.IconSize.Value;
				}
			}
			if ((Object)(object)componentInChildren2 != (Object)null)
			{
				string text = ((ChestListWeightPlugin.Decimals.Value == 0) ? Mathf.CeilToInt(num).ToString() : num.ToString("F" + ChestListWeightPlugin.Decimals.Value));
				if ((Object)(object)val6 == (Object)null && Localization.instance != null)
				{
					text = Localization.instance.Localize("$item_weight") + ": " + text;
				}
				((TMP_Text)componentInChildren2).text = text;
			}
		}

		private static GameObject Build(RectTransform content)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0038: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Qua8ionWeightLine", new Type[1] { typeof(RectTransform) });
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)content, false);
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(1f, 1f);
			component.pivot = new Vector2(0.5f, 1f);
			component.anchoredPosition = new Vector2(0f, -38f);
			component.sizeDelta = new Vector2(0f, Height);
			HorizontalLayoutGroup obj = val.AddComponent<HorizontalLayoutGroup>();
			((LayoutGroup)obj).childAlignment = (TextAnchor)4;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj).spacing = 6f;
			GameObject val2 = new GameObject("Icon", new Type[1] { typeof(RectTransform) });
			val2.transform.SetParent((Transform)(object)component, false);
			Image obj2 = val2.AddComponent<Image>();
			obj2.preserveAspect = true;
			((Graphic)obj2).raycastTarget = false;
			LayoutElement obj3 = val2.AddComponent<LayoutElement>();
			obj3.preferredWidth = ChestListWeightPlugin.IconSize.Value;
			obj3.preferredHeight = ChestListWeightPlugin.IconSize.Value;
			TextMeshProUGUI val3 = CreateLabel(component);
			if ((Object)(object)val3 == (Object)null)
			{
				Object.Destroy((Object)(object)val);
				return null;
			}
			((Component)val3).gameObject.SetActive(true);
			((TMP_Text)val3).alignment = (TextAlignmentOptions)4097;
			((Graphic)val3).raycastTarget = false;
			((TMP_Text)val3).textWrappingMode = (TextWrappingModes)0;
			ContentSizeFitter obj4 = ((Component)val3).gameObject.AddComponent<ContentSizeFitter>();
			obj4.horizontalFit = (FitMode)2;
			obj4.verticalFit = (FitMode)2;
			return val;
		}

		private static TextMeshProUGUI CreateLabel(RectTransform parent)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			MethodInfo methodInfo = AccessTools.DeclaredMethod(Overlay, "CreateGameTmp", new Type[3]
			{
				typeof(string),
				typeof(Transform),
				typeof(bool)
			}, (Type[])null);
			if (methodInfo != null)
			{
				object? obj = methodInfo.Invoke(null, new object[3] { "Weight", parent, false });
				return (TextMeshProUGUI)((obj is TextMeshProUGUI) ? obj : null);
			}
			GameObject val = new GameObject("Weight", new Type[1] { typeof(RectTransform) });
			val.transform.SetParent((Transform)(object)parent, false);
			return val.AddComponent<TextMeshProUGUI>();
		}
	}
	[HarmonyPatch]
	internal static class RefreshPatch
	{
		public static void Postfix(object __instance, Container container)
		{
			try
			{
				WeightLine.Refresh(__instance, container);
			}
			catch (Exception ex)
			{
				ChestListWeightPlugin.Log.LogWarning((object)("Weight line failed: " + ex));
			}
		}
	}
	[HarmonyPatch]
	internal static class PanelSizePatch
	{
		public static void Postfix(object __instance)
		{
			//IL_002e: 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_0049: Unknown result type (might be due to invalid IL or missing references)
			if (WeightLine.Enabled)
			{
				object value = Traverse.Create(__instance).Field("_panel").GetValue();
				RectTransform val = (RectTransform)((value is RectTransform) ? value : null);
				if ((Object)(object)val != (Object)null)
				{
					val.sizeDelta = new Vector2(val.sizeDelta.x, val.sizeDelta.y + WeightLine.Height);
				}
			}
		}
	}
}