Decompiled source of Buller Company v1.0.18

plugins\LethalUtilitys.TerminalTweaks\LethalUtilitys.TerminalTweaks.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 LethalUtilitys.TerminalTweaks
{
	internal static class LethalConfigIconFixer
	{
		private const string BundlePackageName = "Buller_Company";

		private const string TerminalTweaksGuid = "bullerwilliam.lethalutilitys.terminaltweaks";

		private static readonly Dictionary<string, Sprite> SpriteCache = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase);

		private static bool _patched;

		internal static void TryPatch(Harmony harmony)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			if (_patched)
			{
				return;
			}
			Type type = AccessTools.TypeByName("LethalConfig.Mods.Mod");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "TryResolveIconAndDesc", (Type[])null, (Type[])null));
			if (methodInfo == null)
			{
				TerminalTweaksPlugin.Instance.LogSource.LogDebug((object)"LethalConfig was not found; skipping icon fixer.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(LethalConfigIconFixer), "TryResolveIconAndDescPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Type type2 = AccessTools.TypeByName("LethalConfig.MonoBehaviours.ModList");
			MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.Method(type2, "BuildModList", (Type[])null, (Type[])null));
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(LethalConfigIconFixer), "BuildModListPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			_patched = true;
			TerminalTweaksPlugin.Instance.LogSource.LogInfo((object)"Patched LethalConfig to use bundled mods' own icons.");
		}

		private static void TryResolveIconAndDescPostfix(object __instance)
		{
			TryFixModIcon(__instance);
		}

		private static void BuildModListPrefix()
		{
			TryFixAllKnownModIcons();
		}

		private static void TryFixAllKnownModIcons()
		{
			try
			{
				if (!((AccessTools.TypeByName("LethalConfig.LethalConfigManager")?.GetProperty("Mods", BindingFlags.Static | BindingFlags.NonPublic))?.GetValue(null, null) is IDictionary dictionary))
				{
					return;
				}
				foreach (object value in dictionary.Values)
				{
					TryFixModIcon(value);
				}
			}
			catch (Exception ex)
			{
				TerminalTweaksPlugin.Instance.LogSource.LogWarning((object)("Failed to refresh LethalConfig mod icons: " + ex.Message));
			}
		}

		private static void TryFixModIcon(object mod)
		{
			try
			{
				object modInfo = GetModInfo(mod);
				if (modInfo == null)
				{
					return;
				}
				string stringProperty = GetStringProperty(modInfo, "Guid");
				if (string.IsNullOrWhiteSpace(stringProperty))
				{
					return;
				}
				string text = stringProperty;
				if (!Chainloader.PluginInfos.TryGetValue(text, out var value))
				{
					return;
				}
				string text2 = FindBestIconPath(value.Location, text);
				if (text2 != null)
				{
					Sprite val = LoadSprite(text2);
					if (!((Object)(object)val == (Object)null))
					{
						SetProperty(modInfo, "Icon", val);
					}
				}
			}
			catch (Exception ex)
			{
				TerminalTweaksPlugin.Instance.LogSource.LogDebug((object)("Could not fix one LethalConfig icon: " + ex.Message));
			}
		}

		private static object? GetModInfo(object mod)
		{
			return mod.GetType().GetField("ModInfo", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(mod);
		}

		private static string? GetStringProperty(object? instance, string propertyName)
		{
			return instance?.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(instance, null) as string;
		}

		private static void SetProperty(object instance, string propertyName, object value)
		{
			instance.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.SetValue(instance, value, null);
		}

		private static string? FindBestIconPath(string pluginLocation, string pluginGuid)
		{
			string text = Path.GetDirectoryName(Path.GetFullPath(pluginLocation));
			while (!string.IsNullOrEmpty(text))
			{
				string text2 = Path.Combine(text, "icon.png");
				string manifestPath = Path.Combine(text, "manifest.json");
				if (File.Exists(text2) && ShouldUseMetadataDirectory(manifestPath, pluginGuid))
				{
					return text2;
				}
				DirectoryInfo parent = Directory.GetParent(text);
				if (parent == null || string.Equals(parent.Name, "plugins", StringComparison.OrdinalIgnoreCase))
				{
					break;
				}
				text = parent.FullName;
			}
			return null;
		}

		private static bool ShouldUseMetadataDirectory(string manifestPath, string pluginGuid)
		{
			if (string.Equals(pluginGuid, "bullerwilliam.lethalutilitys.terminaltweaks", StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
			if (!File.Exists(manifestPath))
			{
				return true;
			}
			return !ManifestHasPackageName(manifestPath, "Buller_Company");
		}

		private static bool ManifestHasPackageName(string manifestPath, string packageName)
		{
			try
			{
				string input = File.ReadAllText(manifestPath);
				string text = Regex.Escape(packageName);
				return Regex.IsMatch(input, "\"name\"\\s*:\\s*\"" + text + "\"", RegexOptions.IgnoreCase);
			}
			catch
			{
				return false;
			}
		}

		private static Sprite? LoadSprite(string iconPath)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if (SpriteCache.TryGetValue(iconPath, out Sprite value))
			{
				return value;
			}
			Texture2D val = new Texture2D(256, 256);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(iconPath), true))
			{
				Object.Destroy((Object)(object)val);
				return null;
			}
			Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
			SpriteCache[iconPath] = val2;
			return val2;
		}
	}
	internal static class MainMenuLogoOverride
	{
		private const string MoreCompanyGuid = "me.swipez.melonloader.morecompany";

		private const string LogoFileName = "main-menu-logo.png";

		private static Texture2D? _logoTexture;

		private static Sprite? _logoSprite;

		private static bool _patched;

		internal static void TryPatch(Harmony harmony)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			if (!_patched)
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					HarmonyMethod val = new HarmonyMethod(typeof(MainMenuLogoOverride), "MenuManagerAwakePostfix", (Type[])null);
					val.priority = 0;
					val.after = new string[1] { "me.swipez.melonloader.morecompany" };
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				Type type = AccessTools.TypeByName("MoreCompany.MainClass");
				MethodInfo methodInfo2 = ((type == null) ? null : AccessTools.Method(type, "LoadAssets", (Type[])null, (Type[])null));
				if (methodInfo2 != null)
				{
					harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(MainMenuLogoOverride), "MoreCompanyLoadAssetsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				OverrideMoreCompanyMainLogo();
				_patched = true;
				TerminalTweaksPlugin.Instance.LogSource.LogInfo((object)"Loaded custom main menu logo override.");
			}
		}

		private static void MoreCompanyLoadAssetsPostfix()
		{
			OverrideMoreCompanyMainLogo();
		}

		private static void MenuManagerAwakePostfix(MenuManager __instance)
		{
			if (__instance.isInitScene)
			{
				return;
			}
			try
			{
				ApplyLogoToMenu(__instance);
			}
			catch (Exception ex)
			{
				TerminalTweaksPlugin.Instance.LogSource.LogWarning((object)("Failed to apply custom main menu logo: " + ex.Message));
			}
		}

		private static void OverrideMoreCompanyMainLogo()
		{
			if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany"))
			{
				Texture2D logoTexture = GetLogoTexture();
				(AccessTools.TypeByName("MoreCompany.MainClass")?.GetField("mainLogo", BindingFlags.Static | BindingFlags.Public))?.SetValue(null, logoTexture);
			}
		}

		private static void ApplyLogoToMenu(MenuManager menuManager)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			Sprite logoSprite = GetLogoSprite();
			Transform parent = ((Component)menuManager).transform.parent;
			GameObject val = ((parent != null) ? ((Component)parent).gameObject : null);
			if (!((Object)(object)val == (Object)null))
			{
				SetImageSprite(val.transform.Find("MenuContainer/MainButtons/HeaderImage"), logoSprite);
				Transform val2 = val.transform.Find("MenuContainer/LoadingScreen");
				if ((Object)(object)val2 != (Object)null)
				{
					val2.localScale = new Vector3(1.02f, 1.06f, 1.02f);
					SetImageSprite(val2.Find("Image"), logoSprite);
				}
			}
		}

		private static void SetImageSprite(Transform imageTransform, Sprite sprite)
		{
			if (!((Object)(object)imageTransform == (Object)null))
			{
				Image component = ((Component)imageTransform).GetComponent<Image>();
				if ((Object)(object)component != (Object)null)
				{
					component.sprite = sprite;
					component.preserveAspect = true;
				}
			}
		}

		private static Sprite GetLogoSprite()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_logoSprite != (Object)null)
			{
				return _logoSprite;
			}
			Texture2D logoTexture = GetLogoTexture();
			_logoSprite = Sprite.Create(logoTexture, new Rect(0f, 0f, (float)((Texture)logoTexture).width, (float)((Texture)logoTexture).height), new Vector2(0.5f, 0.5f));
			return _logoSprite;
		}

		private static Texture2D GetLogoTexture()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			if ((Object)(object)_logoTexture != (Object)null)
			{
				return _logoTexture;
			}
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "main-menu-logo.png");
			if (!File.Exists(text))
			{
				throw new FileNotFoundException("Custom main menu logo was not found.", text);
			}
			Texture2D val = new Texture2D(2, 2);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(text), false))
			{
				Object.Destroy((Object)(object)val);
				throw new InvalidDataException("Custom main menu logo could not be loaded as a PNG.");
			}
			_logoTexture = val;
			return _logoTexture;
		}
	}
	[BepInPlugin("bullerwilliam.lethalutilitys.terminaltweaks", "Buller Company Terminal Tweaks", "1.0.17")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class TerminalTweaksPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "bullerwilliam.lethalutilitys.terminaltweaks";

		public const string PluginName = "Buller Company Terminal Tweaks";

		public const string PluginVersion = "1.0.17";

		private Harmony? _harmony;

		internal static TerminalTweaksPlugin Instance { get; private set; }

		internal ConfigEntry<int> MaxInputLength { get; private set; }

		internal ConfigEntry<int> HistorySize { get; private set; }

		internal ManualLogSource LogSource => ((BaseUnityPlugin)this).Logger;

		private void Awake()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			Instance = this;
			MaxInputLength = ((BaseUnityPlugin)this).Config.Bind<int>("Terminal", "MaxInputLength", 200, "Maximum number of characters allowed in terminal input.");
			HistorySize = ((BaseUnityPlugin)this).Config.Bind<int>("Terminal", "CommandHistorySize", 25, "How many submitted terminal commands are kept in history.");
			_harmony = new Harmony("bullerwilliam.lethalutilitys.terminaltweaks");
			_harmony.PatchAll(typeof(TerminalPatches));
			LethalConfigIconFixer.TryPatch(_harmony);
			MainMenuLogoOverride.TryPatch(_harmony);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded terminal tweaks with history, aliases, extended input length, and LethalConfig icon fixes.");
		}
	}
	internal static class TerminalPatches
	{
		private sealed class HistoryState
		{
			public List<string> Entries { get; } = new List<string> { string.Empty };

			public int Index { get; set; }
		}

		private static readonly FieldInfo ModifyingTextField = typeof(Terminal).GetField("modifyingText", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly Dictionary<Terminal, HistoryState> HistoryByTerminal = new Dictionary<Terminal, HistoryState>();

		private static readonly Dictionary<string, string> Aliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "BeginUsingTerminal")]
		private static void BeginUsingTerminalPostfix(Terminal __instance)
		{
			ApplyInputLimit(__instance);
			EnsureHistory(__instance).Index = 0;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "LoadNewNode")]
		private static void LoadNewNodePostfix(Terminal __instance)
		{
			ApplyInputLimit(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Terminal), "OnSubmit")]
		private static void OnSubmitPrefix(Terminal __instance, out string __state)
		{
			__state = GetCurrentInput(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "OnSubmit")]
		private static void OnSubmitPostfix(Terminal __instance, string __state)
		{
			if (__instance.terminalInUse && !string.IsNullOrWhiteSpace(__state))
			{
				HistoryState historyState = EnsureHistory(__instance);
				historyState.Index = 0;
				historyState.Entries[0] = string.Empty;
				if (historyState.Entries.Count <= 1 || !string.Equals(historyState.Entries[1], __state, StringComparison.Ordinal))
				{
					historyState.Entries.Insert(1, __state);
				}
				int num = Math.Max(1, TerminalTweaksPlugin.Instance.HistorySize.Value);
				while (historyState.Entries.Count > num + 1)
				{
					historyState.Entries.RemoveAt(historyState.Entries.Count - 1);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "Update")]
		private static void UpdatePostfix(Terminal __instance)
		{
			if (__instance.terminalInUse && Keyboard.current != null)
			{
				if (((ButtonControl)Keyboard.current.upArrowKey).wasPressedThisFrame)
				{
					NavigateHistory(__instance, moveOlder: true);
				}
				else if (((ButtonControl)Keyboard.current.downArrowKey).wasPressedThisFrame)
				{
					NavigateHistory(__instance, moveOlder: false);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
		private static bool ParsePlayerSentencePrefix(Terminal __instance, ref TerminalNode __result)
		{
			string text = GetCurrentInput(__instance).Trim();
			if (string.IsNullOrWhiteSpace(text))
			{
				return true;
			}
			LoadAliasesFromTerminalAliasesConfig();
			string[] array = text.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			if (array.Length == 0)
			{
				return true;
			}
			if (string.Equals(array[0], "alias", StringComparison.OrdinalIgnoreCase))
			{
				__result = HandleAliasCommand(array);
				return false;
			}
			if (string.Equals(array[0], "removealias", StringComparison.OrdinalIgnoreCase))
			{
				__result = HandleRemoveAliasCommand(array);
				return false;
			}
			if (!Aliases.TryGetValue(array[0], out string value))
			{
				return true;
			}
			string text2 = ((text.Length > array[0].Length) ? text.Substring(array[0].Length).TrimStart(Array.Empty<char>()) : string.Empty);
			string text3 = (string.IsNullOrWhiteSpace(text2) ? PreserveCase(array[0], value) : (PreserveCase(array[0], value) + " " + text2));
			SetCurrentInput(__instance, text3);
			TerminalTweaksPlugin.Instance.LogSource.LogDebug((object)("Expanded alias '" + text + "' to '" + text3 + "'."));
			return true;
		}

		private static void ApplyInputLimit(Terminal terminal)
		{
			int num = Math.Max(40, TerminalTweaksPlugin.Instance.MaxInputLength.Value);
			terminal.screenText.characterLimit = num + (terminal.currentText?.Length ?? 0);
			if ((Object)(object)terminal.currentNode != (Object)null)
			{
				terminal.currentNode.maxCharactersToType = num;
			}
			string currentInput = GetCurrentInput(terminal);
			if (currentInput.Length > num)
			{
				SetCurrentInput(terminal, currentInput.Substring(0, num));
			}
		}

		private static void NavigateHistory(Terminal terminal, bool moveOlder)
		{
			HistoryState historyState = EnsureHistory(terminal);
			if (moveOlder)
			{
				if (historyState.Index == 0)
				{
					historyState.Entries[0] = GetCurrentInput(terminal);
				}
				if (historyState.Index < historyState.Entries.Count - 1)
				{
					historyState.Index++;
					SetCurrentInput(terminal, historyState.Entries[historyState.Index]);
				}
			}
			else if (historyState.Index > 0)
			{
				historyState.Index--;
				SetCurrentInput(terminal, historyState.Entries[historyState.Index]);
			}
		}

		private static HistoryState EnsureHistory(Terminal terminal)
		{
			if (!HistoryByTerminal.TryGetValue(terminal, out HistoryState value))
			{
				value = new HistoryState();
				HistoryByTerminal[terminal] = value;
			}
			return value;
		}

		private static string GetCurrentInput(Terminal terminal)
		{
			TMP_InputField screenText = terminal.screenText;
			string text = ((screenText != null) ? screenText.text : null) ?? string.Empty;
			if (terminal.textAdded > 0 && text.Length >= terminal.textAdded)
			{
				return text.Substring(text.Length - terminal.textAdded, terminal.textAdded);
			}
			string text2 = terminal.currentText ?? string.Empty;
			if (text.StartsWith(text2, StringComparison.Ordinal) && text.Length > text2.Length)
			{
				return text.Substring(text2.Length);
			}
			return string.Empty;
		}

		private static void SetCurrentInput(Terminal terminal, string input)
		{
			TMP_InputField screenText = terminal.screenText;
			if (!((Object)(object)screenText == (Object)null))
			{
				string text = screenText.text ?? string.Empty;
				int num = Math.Max(0, text.Length - Math.Max(0, terminal.textAdded));
				string text2 = ((text.Length >= num) ? text.Substring(0, num) : string.Empty);
				string text3 = input;
				int num2 = Math.Max(40, TerminalTweaksPlugin.Instance.MaxInputLength.Value);
				if (text3.Length > num2)
				{
					text3 = text3.Substring(0, num2);
				}
				bool modifyingText = GetModifyingText(terminal);
				SetModifyingText(terminal, value: true);
				screenText.text = text2 + text3;
				terminal.textAdded = text3.Length;
				terminal.currentText = screenText.text;
				SetModifyingText(terminal, modifyingText);
				screenText.caretPosition = screenText.text.Length;
				screenText.stringPosition = screenText.text.Length;
				screenText.ActivateInputField();
				((Selectable)screenText).Select();
			}
		}

		private static TerminalNode HandleAliasCommand(string[] parts)
		{
			if (parts.Length == 1)
			{
				if (Aliases.Count == 0)
				{
					return CreateNode("No aliases defined.\n\nUse 'alias [name] [command]' to create one.\n\n");
				}
				string text = "Defined aliases:\n\n";
				foreach (KeyValuePair<string, string> alias in Aliases)
				{
					text = text + "  " + alias.Key + " = " + alias.Value + "\n";
				}
				return CreateNode(text + "\n");
			}
			if (parts.Length == 2)
			{
				return CreateNode("Usage: alias [name] [command]\n\nExample: alias company route the company building\n\n");
			}
			string text2 = parts[1];
			string text3 = string.Join(" ", parts, 2, parts.Length - 2);
			if (string.IsNullOrWhiteSpace(text2) || string.IsNullOrWhiteSpace(text3))
			{
				return CreateNode("Failed to add alias.\n\n");
			}
			Aliases[text2] = text3;
			SaveAliasesToTerminalAliasesConfig();
			return CreateNode("Alias '" + text2 + "' set to '" + text3 + "'\n\n");
		}

		private static TerminalNode HandleRemoveAliasCommand(string[] parts)
		{
			if (parts.Length < 2)
			{
				return CreateNode("Usage: removealias [name]\n\n");
			}
			string text = parts[1];
			if (Aliases.Remove(text))
			{
				SaveAliasesToTerminalAliasesConfig();
				return CreateNode("Alias '" + text + "' removed.\n\n");
			}
			return CreateNode("Alias '" + text + "' not found.\n\n");
		}

		private static TerminalNode CreateNode(string text)
		{
			TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>();
			obj.displayText = text;
			obj.clearPreviousText = true;
			return obj;
		}

		private static string GetAliasFilePath()
		{
			return Path.Combine(Paths.ConfigPath, "TerminalAliases.cfg");
		}

		private static void SaveAliasesToTerminalAliasesConfig()
		{
			string aliasFilePath = GetAliasFilePath();
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, string> alias in Aliases)
			{
				list.Add(alias.Key.ToLowerInvariant() + "=" + alias.Value);
			}
			Directory.CreateDirectory(Paths.ConfigPath);
			File.WriteAllLines(aliasFilePath, list);
		}

		private static void LoadAliasesFromTerminalAliasesConfig()
		{
			string aliasFilePath = GetAliasFilePath();
			if (!File.Exists(aliasFilePath))
			{
				return;
			}
			string[] array = File.ReadAllLines(aliasFilePath);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (string.IsNullOrEmpty(text) || text.StartsWith("#", StringComparison.Ordinal))
				{
					continue;
				}
				int num = text.IndexOf('=');
				if (num > 0 && num < text.Length - 1)
				{
					string text2 = text.Substring(0, num).Trim();
					string value = text.Substring(num + 1).Trim();
					if (!string.IsNullOrEmpty(text2) && !string.IsNullOrEmpty(value))
					{
						Aliases[text2] = value;
					}
				}
			}
		}

		private static string PreserveCase(string originalAlias, string expandedInput)
		{
			if (string.IsNullOrEmpty(originalAlias) || string.IsNullOrEmpty(expandedInput))
			{
				return expandedInput;
			}
			if (string.Equals(originalAlias, originalAlias.ToUpperInvariant(), StringComparison.Ordinal))
			{
				return expandedInput.ToUpperInvariant();
			}
			if (char.IsUpper(originalAlias[0]))
			{
				return char.ToUpperInvariant(expandedInput[0]) + expandedInput.Substring(1);
			}
			return expandedInput;
		}

		private static bool GetModifyingText(Terminal terminal)
		{
			if (ModifyingTextField != null)
			{
				return (bool)ModifyingTextField.GetValue(terminal);
			}
			return false;
		}

		private static void SetModifyingText(Terminal terminal, bool value)
		{
			ModifyingTextField?.SetValue(terminal, value);
		}
	}
}