Decompiled source of UI Scaling v0.1.1

BepInEx/plugins/GraveyardOrbit.UIScaling/GraveyardOrbit.UIScaling.dll

Decompiled an hour 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.Logging;
using GraveyardOrbit.UI;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.UIElements;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.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 GraveyardOrbit.UIScaling
{
	internal static class ModTreeLegendLayoutPatch
	{
		[HarmonyPatch(typeof(ModTreeScreen), "MakeLegend")]
		internal static class MakeLegendPatch
		{
			private static void Postfix(VisualElement __result)
			{
				//IL_0017: 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_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: 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_009c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00db: Unknown result type (might be due to invalid IL or missing references)
				if (__result == null || UiScale.Factor <= 1.01f)
				{
					return;
				}
				__result.style.alignSelf = StyleEnum<Align>.op_Implicit((Align)4);
				__result.style.width = StyleLength.op_Implicit(Length.Percent(100f));
				foreach (VisualElement item in __result.Children())
				{
					if (item is Label)
					{
						continue;
					}
					item.style.width = StyleLength.op_Implicit(Length.Percent(100f));
					foreach (VisualElement item2 in item.Children())
					{
						Label val = (Label)(object)((item2 is Label) ? item2 : null);
						if (val != null)
						{
							((VisualElement)val).style.whiteSpace = StyleEnum<WhiteSpace>.op_Implicit((WhiteSpace)0);
							((VisualElement)val).style.flexShrink = StyleFloat.op_Implicit(1f);
							((VisualElement)val).style.minWidth = StyleLength.op_Implicit(0f);
							((VisualElement)val).style.paddingRight = StyleLength.op_Implicit(0f);
						}
					}
				}
			}
		}
	}
	internal static class ShipyardScalePatches
	{
		private static readonly FieldInfo RootField = typeof(ShipyardAccretionScreen).GetField("_root", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly MethodInfo PostfixMethod = typeof(ShipyardScalePatches).GetMethod("AfterRender", BindingFlags.Static | BindingFlags.NonPublic);

		internal static void Apply(Harmony harmony)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			try
			{
				if (RootField == null || PostfixMethod == null)
				{
					ManualLogSource log = UIScalingPlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)"Shipyard scaling hooks skipped: screen layout changed");
					}
					return;
				}
				int num = 0;
				MethodInfo[] methods = typeof(ShipyardAccretionScreen).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (!methodInfo.Name.StartsWith("Render", StringComparison.Ordinal) || methodInfo.IsAbstract || methodInfo.ContainsGenericParameters)
					{
						continue;
					}
					try
					{
						harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(PostfixMethod), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						num++;
					}
					catch (Exception ex)
					{
						ManualLogSource log2 = UIScalingPlugin.Log;
						if (log2 != null)
						{
							log2.LogWarning((object)("Could not hook shipyard " + methodInfo.Name + ": " + ex.Message));
						}
					}
				}
				ManualLogSource log3 = UIScalingPlugin.Log;
				if (log3 != null)
				{
					log3.LogInfo((object)("Shipyard rebuild rescale hooks: " + num + " render methods"));
				}
			}
			catch (Exception ex2)
			{
				ManualLogSource log4 = UIScalingPlugin.Log;
				if (log4 != null)
				{
					log4.LogWarning((object)("Shipyard scaling hooks failed: " + ex2));
				}
			}
		}

		private static void AfterRender(ShipyardAccretionScreen __instance)
		{
			try
			{
				object? obj = RootField?.GetValue(__instance);
				VisualElement val = (VisualElement)((obj is VisualElement) ? obj : null);
				if (val != null && val.panel != null)
				{
					UiScale.ApplyTree(val);
					UiScale.RequestApply();
				}
			}
			catch
			{
			}
		}
	}
	internal static class SorterPopoverLayoutPatch
	{
		[HarmonyPatch(typeof(RefineryScreen), "OpenSocket")]
		internal static class OpenSocketPatch
		{
			private static void Postfix(RefineryScreen __instance, Machine m)
			{
				//IL_0004: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Invalid comparison between Unknown and I4
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0095: 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)
				//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
				if (m == null || (int)m.kind != 2 || UiScale.Factor <= 1.01f)
				{
					return;
				}
				VisualElement popover = __instance.Popover;
				if (popover == null)
				{
					return;
				}
				VisualElement val = UQueryExtensions.Q<VisualElement>(popover, (string)null, "rl-pop__head");
				if (val == null)
				{
					return;
				}
				Label val2 = UQueryExtensions.Q<Label>(val, (string)null, "rl-pop__sub");
				if (val2 != null && ((VisualElement)val2).parent == val)
				{
					int num = popover.IndexOf(val);
					((VisualElement)val2).RemoveFromHierarchy();
					if (num >= 0)
					{
						popover.Insert(num + 1, (VisualElement)(object)val2);
					}
					else
					{
						popover.Add((VisualElement)(object)val2);
					}
					((VisualElement)val2).style.marginLeft = StyleLength.op_Implicit(0f);
					((VisualElement)val2).style.marginTop = StyleLength.op_Implicit(4f);
					((VisualElement)val2).style.marginBottom = StyleLength.op_Implicit(10f);
					((VisualElement)val2).style.whiteSpace = StyleEnum<WhiteSpace>.op_Implicit((WhiteSpace)0);
				}
			}
		}
	}
	internal static class TopHudLayoutPatch
	{
		[HarmonyPatch(typeof(TopHudController), "Bind")]
		internal static class BindPatch
		{
			private static void Postfix(TopHudController __instance)
			{
				//IL_0035: 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_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					VisualElement value = Traverse.Create((object)__instance).Field("_root").GetValue<VisualElement>();
					if (value != null)
					{
						Label val = UQueryExtensions.Q<Label>(value, "money", (string)null);
						if (val != null)
						{
							((VisualElement)val).style.unityTextAlign = StyleEnum<TextAnchor>.op_Implicit((TextAnchor)3);
							((VisualElement)val).style.paddingTop = StyleLength.op_Implicit(0f);
							((VisualElement)val).style.paddingBottom = StyleLength.op_Implicit(0f);
						}
						VisualElement val2 = UQueryExtensions.Q<VisualElement>(value, "meta-wrap", (string)null);
						if (val2 != null)
						{
							val2.style.paddingRight = StyleLength.op_Implicit(18f);
							val2.style.marginRight = StyleLength.op_Implicit(6f);
						}
					}
				}
				catch
				{
				}
			}
		}
	}
	internal static class UiScale
	{
		private sealed class FontBase
		{
			internal float Size;

			internal float AppliedFactor = 1f;
		}

		internal static readonly int[] Presets = new int[4] { 100, 125, 150, 200 };

		private const string PrefKey = "go_settings_ui_scale";

		private const int DefaultPercent = 100;

		private static readonly ConditionalWeakTable<TextElement, FontBase> TextBases = new ConditionalWeakTable<TextElement, FontBase>();

		private static readonly ConditionalWeakTable<Text, FontBase> UguiTextBases = new ConditionalWeakTable<Text, FontBase>();

		internal static bool PendingApply;

		internal static int Current { get; private set; } = 100;

		internal static float Factor => (float)Current / 100f;

		internal static int Index
		{
			get
			{
				for (int i = 0; i < Presets.Length; i++)
				{
					if (Presets[i] == Current)
					{
						return i;
					}
				}
				return 0;
			}
		}

		internal static void RequestApply()
		{
			if (!Mathf.Approximately(Factor, 1f))
			{
				PendingApply = true;
			}
		}

		internal static void ApplyTree(VisualElement root)
		{
			if (root != null)
			{
				ScaleTree(root, Factor);
			}
		}

		internal static void Load()
		{
			int num = PlayerPrefs.GetInt("go_settings_ui_scale", 100);
			if (!IsPreset(num))
			{
				num = 100;
			}
			Current = num;
		}

		internal static void Set(int percent)
		{
			if (!IsPreset(percent))
			{
				percent = 100;
			}
			if (Current != percent)
			{
				Current = percent;
				PlayerPrefs.SetInt("go_settings_ui_scale", percent);
				PlayerPrefs.Save();
				ApplyAll();
			}
		}

		private static bool IsPreset(int value)
		{
			for (int i = 0; i < Presets.Length; i++)
			{
				if (Presets[i] == value)
				{
					return true;
				}
			}
			return false;
		}

		internal static void ApplyAll()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			float factor = Factor;
			UIDocument[] array = Resources.FindObjectsOfTypeAll<UIDocument>();
			foreach (UIDocument obj in array)
			{
				VisualElement val = ((obj != null) ? obj.rootVisualElement : null);
				if (val != null)
				{
					ScaleTree(val, factor);
				}
			}
			Text[] array2 = Resources.FindObjectsOfTypeAll<Text>();
			foreach (Text val2 in array2)
			{
				if (!((Object)(object)val2 == (Object)null))
				{
					Scene scene = ((Component)val2).gameObject.scene;
					if (((Scene)(ref scene)).IsValid())
					{
						ScaleText(val2, factor);
					}
				}
			}
		}

		private static void ScaleTree(VisualElement element, float factor)
		{
			TextElement val = (TextElement)(object)((element is TextElement) ? element : null);
			if (val != null)
			{
				ScaleTextElement(val, factor);
			}
			foreach (VisualElement item in element.Children())
			{
				ScaleTree(item, factor);
			}
		}

		private static void ScaleTextElement(TextElement element, float factor)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			float current = ((VisualElement)element).resolvedStyle.fontSize;
			if (!(current <= 0.01f))
			{
				FontBase value = TextBases.GetValue(element, (TextElement <p0>) => new FontBase
				{
					Size = current
				});
				if (Mathf.Abs(current - value.Size * value.AppliedFactor) > 0.51f)
				{
					value.Size = current / Mathf.Max(0.01f, value.AppliedFactor);
				}
				float num = (IsFixedSizeCard((VisualElement)(object)element) ? 1f : factor);
				if (((VisualElement)element).ClassListContains("top-hud__title"))
				{
					num = Mathf.Min(num, 1.25f);
				}
				((VisualElement)element).style.fontSize = StyleLength.op_Implicit(value.Size * num);
				value.AppliedFactor = num;
			}
		}

		private static bool IsFixedSizeCard(VisualElement element)
		{
			for (VisualElement val = element; val != null; val = val.parent)
			{
				if (val.ClassListContains("term-door"))
				{
					return true;
				}
				if (val.name != null && val.name.StartsWith("tray-") && val.name != "tray-price")
				{
					return true;
				}
			}
			return false;
		}

		private static void ScaleText(Text text, float factor)
		{
			int current = text.fontSize;
			if (current > 0)
			{
				FontBase value = UguiTextBases.GetValue(text, (Text <p0>) => new FontBase
				{
					Size = current
				});
				if (Mathf.Abs((float)current - value.Size * value.AppliedFactor) > 0.51f)
				{
					value.Size = (float)current / Mathf.Max(0.01f, value.AppliedFactor);
				}
				text.fontSize = Mathf.Max(1, Mathf.RoundToInt(value.Size * factor));
				value.AppliedFactor = factor;
			}
		}
	}
	internal static class UIScalePatches
	{
		[HarmonyPatch(typeof(GameSettings), "ApplyAll")]
		internal static class ApplySettingsPatch
		{
			private static void Postfix()
			{
				UiScale.ApplyAll();
			}
		}

		[HarmonyPatch(typeof(SettingsModal), "Open", new Type[]
		{
			typeof(VisualElement),
			typeof(Action),
			typeof(Action)
		})]
		internal static class SettingsUiScaleRowPatch
		{
			private static void Postfix(VisualElement __result)
			{
				AddUiScaleRow(__result);
			}
		}

		private static void AddUiScaleRow(VisualElement modal)
		{
			if (modal == null || UQueryExtensions.Q(modal, "ui-scale-row", (string)null) != null)
			{
				return;
			}
			try
			{
				Label val = FindLabel(modal, Loc.T("settings.display.resolution", "Resolution"));
				if (val == null)
				{
					return;
				}
				VisualElement parent = ((VisualElement)val).parent;
				VisualElement val2 = ((parent != null) ? parent.parent : null);
				if (val2 == null)
				{
					return;
				}
				MethodInfo method = typeof(SettingsModal).GetMethod("MakeRow", BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo method2 = typeof(SettingsModal).GetMethod("Dropdown", BindingFlags.Static | BindingFlags.NonPublic);
				if (method == null || method2 == null)
				{
					return;
				}
				object obj = method.Invoke(null, new object[5]
				{
					val2,
					Loc.T("settings.display.text_size", "Text Size"),
					66f,
					false,
					false
				});
				object? obj2 = obj?.GetType().GetField("root")?.GetValue(obj);
				VisualElement val3 = (VisualElement)((obj2 is VisualElement) ? obj2 : null);
				if (val3 == null)
				{
					return;
				}
				val3.name = "ui-scale-row";
				int num = val2.IndexOf(parent);
				if (num >= 0)
				{
					val2.Insert(num + 1, val3);
				}
				Func<string[]> func = delegate
				{
					List<string> list = new List<string>();
					for (int i = 0; i < UiScale.Presets.Length; i++)
					{
						int num2 = UiScale.Presets[i];
						list.Add((num2 == 200) ? "200% (EXPERIMENTAL)" : (num2 + "%"));
					}
					return list.ToArray();
				};
				method2.Invoke(null, new object[5]
				{
					obj,
					modal,
					func,
					(Func<int>)(() => UiScale.Index),
					(Action<int>)delegate(int i)
					{
						UiScale.Set(UiScale.Presets[Mathf.Clamp(i, 0, UiScale.Presets.Length - 1)]);
					}
				});
			}
			catch (Exception ex)
			{
				ManualLogSource log = UIScalingPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not add Text Size setting: " + ex));
				}
			}
		}

		private static Label FindLabel(VisualElement root, string text)
		{
			foreach (VisualElement item in root.Children())
			{
				Label val = (Label)(object)((item is Label) ? item : null);
				if (val != null && ((TextElement)val).text == text)
				{
					return val;
				}
				Label val2 = FindLabel(item, text);
				if (val2 != null)
				{
					return val2;
				}
			}
			return null;
		}
	}
	[BepInPlugin("agentbox.graveyardorbit.uiscaling", "Graveyard Orbit UI Scaling", "0.1.1")]
	public sealed class UIScalingPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "agentbox.graveyardorbit.uiscaling";

		public const string PluginName = "Graveyard Orbit UI Scaling";

		public const string PluginVersion = "0.1.1";

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private float _nextScan;

		private void Awake()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			UiScale.Load();
			_harmony = new Harmony("agentbox.graveyardorbit.uiscaling");
			try
			{
				_harmony.PatchAll(typeof(UIScalingPlugin).Assembly);
				ShipyardScalePatches.Apply(_harmony);
				Log.LogInfo((object)"UI Scaling loaded:");
				Log.LogInfo((object)"  Display settings: Text Size 100 / 125 / 150 / 200%");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("UI Scaling patch failure: " + ex));
			}
		}

		private void Update()
		{
			if (UiScale.PendingApply)
			{
				UiScale.PendingApply = false;
				UiScale.ApplyAll();
			}
			float unscaledTime = Time.unscaledTime;
			if (!(unscaledTime < _nextScan))
			{
				_nextScan = unscaledTime + 0.5f;
				if (!Mathf.Approximately(UiScale.Factor, 1f))
				{
					UiScale.ApplyAll();
				}
			}
		}

		private void OnDestroy()
		{
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
		}
	}
}