Decompiled source of SubtextRun v1.0.2

plugins/SubtextRun.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[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 SubtextRun
{
	[BepInPlugin("subtext.run", "SubtextRun", "1.0.0")]
	public class Plugin : BasePlugin
	{
		public const string GUID = "subtext.run";

		public const string NAME = "SubtextRun";

		public const string VERSION = "1.0.0";

		internal static ManualLogSource L;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<string> LabelText;

		internal static ConfigEntry<string> MatchText;

		internal static ConfigEntry<string> LabelColor;

		internal static ConfigEntry<float> FontSize;

		internal static ConfigEntry<float> LineGap;

		internal static ConfigEntry<float> OffsetX;

		internal static ConfigEntry<float> OffsetY;

		public override void Load()
		{
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Expected O, but got Unknown
			L = ((BasePlugin)this).Log;
			Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", false, "Set to true to show the extra line. Disabled by default.");
			LabelText = ((BasePlugin)this).Config.Bind<string>("General", "Text", "Subtext-Run 0.4.8", "Text shown on the new line below the MODDED label.");
			MatchText = ((BasePlugin)this).Config.Bind<string>("General", "FindLabelContaining", "MODDED", "The new line is added below any on-screen text that contains this word (case-insensitive).");
			LabelColor = ((BasePlugin)this).Config.Bind<string>("General", "Color", "", "Optional hex color such as #FF8C00. Empty = keep the original label's color.");
			FontSize = ((BasePlugin)this).Config.Bind<float>("General", "FontSize", 0f, "Font size for the new line. 0 = same size as the original label.");
			LineGap = ((BasePlugin)this).Config.Bind<float>("Layout", "LineGap", 1f, "Spacing below the original label, as a multiple of that label's height.");
			OffsetX = ((BasePlugin)this).Config.Bind<float>("Layout", "OffsetX", 0f, "Extra horizontal shift (the label's local units).");
			OffsetY = ((BasePlugin)this).Config.Bind<float>("Layout", "OffsetY", 0f, "Extra vertical shift (positive = up, negative = down).");
			((BasePlugin)this).AddComponent<LabelRuntime>();
			ManualLogSource l = L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(8, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("SubtextRun");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.0.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded");
			}
			l.LogInfo(val);
		}
	}
	internal class LabelRuntime : MonoBehaviour
	{
		private float _next;

		public LabelRuntime(IntPtr ptr)
			: base(ptr)
		{
		}

		private void Update()
		{
			if (!(Time.unscaledTime < _next))
			{
				Labeler.Tick();
				_next = Time.unscaledTime + Labeler.Delay;
			}
		}
	}
	internal static class Labeler
	{
		private const string Suffix = "_SubtextRun";

		private static readonly Dictionary<int, TMP_Text> Clones = new Dictionary<int, TMP_Text>();

		private static bool _failedOnce;

		private const int InLevelState = 10;

		private static int _lastState = -1;

		private static int _misses;

		public static float Delay = 2f;

		private static PropertyInfo _stateProp;

		private static int _stateSearches;

		public static void Tick()
		{
			Delay = 2f;
			try
			{
				if (!Plugin.Enabled.Value)
				{
					RemoveAll();
					return;
				}
				Prune();
				int num = ReadState();
				if (num != _lastState)
				{
					_lastState = num;
					_misses = 0;
				}
				if (num == 10)
				{
					return;
				}
				if (Clones.Count > 0)
				{
					string value = Plugin.LabelText.Value;
					{
						foreach (KeyValuePair<int, TMP_Text> clone in Clones)
						{
							if ((Object)(object)clone.Value != (Object)null && clone.Value.text != value)
							{
								clone.Value.text = value;
							}
						}
						return;
					}
				}
				Visit<TextMeshProUGUI>((IEnumerable<TextMeshProUGUI>)Object.FindObjectsOfType<TextMeshProUGUI>());
				Visit<TextMeshPro>((IEnumerable<TextMeshPro>)Object.FindObjectsOfType<TextMeshPro>());
				if (Clones.Count > 0)
				{
					_misses = 0;
					return;
				}
				_misses++;
				Delay = Math.Min(1.5f * (float)(1 << Math.Min(_misses, 5)), 45f);
			}
			catch (Exception ex)
			{
				Delay = 10f;
				if (!_failedOnce)
				{
					_failedOnce = true;
					Plugin.L.LogError((object)("Scan failed (further errors hidden): " + ex));
				}
			}
		}

		private static int ReadState()
		{
			try
			{
				if (_stateProp == null && _stateSearches < 30)
				{
					_stateSearches++;
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					foreach (Assembly assembly in assemblies)
					{
						Type type = null;
						try
						{
							type = assembly.GetType("GameStateManager", throwOnError: false);
						}
						catch
						{
						}
						if (!(type == null))
						{
							PropertyInfo property = type.GetProperty("CurrentStateName", BindingFlags.Static | BindingFlags.Public);
							if (!(property == null))
							{
								_stateProp = property;
								Plugin.L.LogInfo((object)("Game state source found: " + assembly.GetName().Name));
								break;
							}
						}
					}
					if (_stateProp == null && _stateSearches == 30)
					{
						Plugin.L.LogWarning((object)"GameStateManager not found; falling back to timed scanning.");
					}
				}
				if (_stateProp == null)
				{
					return -1;
				}
				return Convert.ToInt32(_stateProp.GetValue(null));
			}
			catch
			{
				return -1;
			}
		}

		private static void RemoveAll()
		{
			if (Clones.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<int, TMP_Text> clone in Clones)
			{
				if ((Object)(object)clone.Value != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)clone.Value).gameObject);
				}
			}
			Clones.Clear();
		}

		private static void Prune()
		{
			List<int> list = null;
			foreach (KeyValuePair<int, TMP_Text> clone in Clones)
			{
				if ((Object)(object)clone.Value == (Object)null)
				{
					if (list == null)
					{
						list = new List<int>();
					}
					list.Add(clone.Key);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (int item in list)
			{
				Clones.Remove(item);
			}
		}

		private static void Visit<T>(IEnumerable<T> texts) where T : TMP_Text
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			string value = Plugin.MatchText.Value;
			if (string.IsNullOrEmpty(value))
			{
				return;
			}
			foreach (T text2 in texts)
			{
				TMP_Text val = (TMP_Text)(object)text2;
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				GameObject gameObject = ((Component)val).gameObject;
				Scene scene = gameObject.scene;
				if (!((Scene)(ref scene)).IsValid() || !gameObject.activeInHierarchy || ((Object)gameObject).name.EndsWith("_SubtextRun"))
				{
					continue;
				}
				string text = val.text;
				if (string.IsNullOrEmpty(text) || text.IndexOf(value, StringComparison.OrdinalIgnoreCase) < 0)
				{
					continue;
				}
				int instanceID = ((Object)val).GetInstanceID();
				if (Clones.TryGetValue(instanceID, out var value2) && (Object)(object)value2 != (Object)null)
				{
					if (value2.text != Plugin.LabelText.Value)
					{
						value2.text = Plugin.LabelText.Value;
					}
					continue;
				}
				TMP_Text val2 = Attach(val);
				if ((Object)(object)val2 != (Object)null)
				{
					Clones[instanceID] = val2;
				}
			}
		}

		private static TMP_Text Attach(TMP_Text src)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)src).gameObject;
			GameObject val = Object.Instantiate<GameObject>(gameObject, gameObject.transform.parent, false);
			((Object)val).name = ((Object)gameObject).name + "_SubtextRun";
			TMP_Text component = val.GetComponent<TMP_Text>();
			if ((Object)(object)component == (Object)null)
			{
				Object.Destroy((Object)(object)val);
				return null;
			}
			component.text = Plugin.LabelText.Value;
			string value = Plugin.LabelColor.Value;
			Color color = default(Color);
			if (!string.IsNullOrWhiteSpace(value) && ColorUtility.TryParseHtmlString(value.Trim(), ref color))
			{
				((Graphic)component).color = color;
			}
			if (Plugin.FontSize.Value > 0f)
			{
				component.fontSize = Plugin.FontSize.Value;
			}
			float num = src.preferredHeight;
			if (num < 0.01f)
			{
				num = src.fontSize * 1.2f;
			}
			float num2 = num * Plugin.LineGap.Value;
			Vector3 localPosition = gameObject.transform.localPosition;
			val.transform.localPosition = new Vector3(localPosition.x + Plugin.OffsetX.Value, localPosition.y - num2 + Plugin.OffsetY.Value, localPosition.z);
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(42, 7, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Added '");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(Plugin.LabelText.Value);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("' under ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(PathOf(gameObject.transform));
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((object)src).GetType().Name);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", localPos=(");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(localPosition.x, "0.##");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(localPosition.y, "0.##");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(localPosition.z, "0.##");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("), height=");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(num, "0.##");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("]");
			}
			l.LogInfo(val2);
			return component;
		}

		private static string PathOf(Transform t)
		{
			string text = ((Object)t).name;
			Transform parent = t.parent;
			while ((Object)(object)parent != (Object)null)
			{
				text = ((Object)parent).name + "/" + text;
				parent = parent.parent;
			}
			return text;
		}
	}
}