Decompiled source of MoonSortPlus v1.0.2

MoonSortPlus.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using LethalLevelLoader;
using Microsoft.CodeAnalysis;

[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("MoonSortPlus")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MoonSortPlus")]
[assembly: AssemblyTitle("MoonSortPlus")]
[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 MoonSortPlus
{
	[BepInPlugin("local.moonsortplus", "MoonSortPlus", "1.0.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private const int GradeColumn = 36;

		private static FieldInfo sortTypeField;

		private static FieldInfo splitCountField;

		private static readonly Regex MoonLine = new Regex("^\\s*(?:[*\\->•]+|\\d+[.)]|\\[\\d+\\])\\s+(\\S.*)$");

		private static readonly Regex Header = new Regex("^\\s*-- (SAFE|[FEDCBAS]|OTHER) --\\s*$");

		private void Awake()
		{
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Expected O, but got Unknown
			string[] array = new string[11]
			{
				"Safe", "D", "C", "B-", "B", "A", "S", "S+", "S++", "S+++",
				"???"
			};
			for (int i = 1; i < array.Length; i++)
			{
				if (GradeRank(array[i - 1]) >= GradeRank(array[i]))
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("MoonSortPlus grade order broken at " + array[i - 1] + " / " + array[i]));
				}
			}
			if (BandName(Band("C-")) != "C" || BandName(Band("S+++")) != "S" || BandName(Band("Safe")) != "SAFE")
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"MoonSortPlus grade grouping broken");
			}
			string[] array2 = new string[6] { "* Vow (Stormy)", "- Vow", "> Vow", "1. Vow", "[2] Vow", "  • Vow  C  $0" };
			foreach (string text in array2)
			{
				if (MoonLine.Match(text).Groups[1].Value.Split(' ')[0] != "Vow")
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("MoonSortPlus line parsing broken for '" + text + "'"));
				}
			}
			if (!Header.IsMatch("  -- C --") || MoonLine.IsMatch("To route the autopilot"))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"MoonSortPlus heading/line detection broken");
			}
			Type type = AccessTools.TypeByName("LethalLevelLoader.Settings");
			sortTypeField = AccessTools.Field(type, "levelPreviewSortType");
			splitCountField = AccessTools.Field(type, "moonsCatalogueSplitCount");
			MethodInfo methodInfo = AccessTools.Method(typeof(Terminal), "TextPostProcess", (Type[])null, (Type[])null);
			if (methodInfo == null || sortTypeField == null || splitCountField == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"LethalLevelLoader internals changed; MoonSortPlus is inactive.");
				return;
			}
			new Harmony("local.moonsortplus").Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "TextPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				if (value.Metadata.Name == "ShowMoonPriceLLL")
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"ShowMoonPriceLLL also adds columns to the moons list; disable it, MoonSortPlus already shows grade and price.");
				}
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoonSortPlus active: danger grade, then price.");
		}

		private static void TextPostfix(ref string __result)
		{
			try
			{
				if (__result == null || __result.IndexOf("exomoons catalogue", StringComparison.OrdinalIgnoreCase) < 0)
				{
					return;
				}
				Dictionary<string, ExtendedLevel> dictionary = new Dictionary<string, ExtendedLevel>();
				foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
				{
					dictionary[Letters(extendedLevel.NumberlessPlanetName)] = extendedLevel;
				}
				List<string> list = new List<string>(__result.Split('\n'));
				list.RemoveAll((string l) => Header.IsMatch(l));
				List<(ExtendedLevel, string)> list2 = new List<(ExtendedLevel, string)>();
				int num = -1;
				int num2 = -1;
				for (int num3 = 0; num3 < list.Count; num3++)
				{
					string text = list[num3].TrimEnd('\r');
					Match match = MoonLine.Match(text);
					if (!match.Success)
					{
						continue;
					}
					string text2 = match.Groups[1].Value;
					string[] array = new string[5] { " (", "  ", " -", " |", " [" };
					foreach (string value in array)
					{
						int num5 = text2.IndexOf(value, StringComparison.Ordinal);
						if (num5 >= 0)
						{
							text2 = text2.Substring(0, num5);
						}
					}
					if (dictionary.TryGetValue(Letters(text2), out var value2))
					{
						if (!text.Contains("$"))
						{
							text = text.TrimEnd().PadRight(Math.Max(36, text.TrimEnd().Length + 2)) + (value2.SelectableLevel.riskLevel ?? "").PadRight(6) + "$" + value2.RoutePrice;
						}
						list2.Add((value2, text));
						list[num3] = text;
						if (num < 0)
						{
							num = num3;
						}
						num2 = num3;
					}
				}
				if (list2.Count > 0 && sortTypeField.GetValue(null)?.ToString() != "None")
				{
					list2.Sort(((ExtendedLevel level, string line) a, (ExtendedLevel level, string line) b) => Compare(a.level, b.level));
					List<string> list3 = new List<string>();
					int num6 = -1;
					int num7 = 0;
					int num8 = Math.Max(1, (int)splitCountField.GetValue(null));
					foreach (var item in list2)
					{
						int num9 = Band(item.Item1.SelectableLevel.riskLevel);
						if (num9 != num6)
						{
							if (list3.Count > 0)
							{
								list3.Add("");
							}
							list3.Add("  -- " + BandName(num9) + " --");
							num6 = num9;
							num7 = 0;
						}
						else if (num7 % num8 == 0)
						{
							list3.Add("");
						}
						list3.Add(item.Item2);
						num7++;
					}
					list.RemoveRange(num, num2 - num + 1);
					list.InsertRange(num, list3);
				}
				__result = string.Join("\n", list);
			}
			catch (Exception)
			{
			}
		}

		private static string Letters(string s)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = s ?? "";
			foreach (char c in text)
			{
				if (char.IsLetter(c))
				{
					stringBuilder.Append(char.ToLowerInvariant(c));
				}
			}
			return stringBuilder.ToString();
		}

		internal static int Compare(ExtendedLevel a, ExtendedLevel b)
		{
			int num = GradeRank(a.SelectableLevel.riskLevel).CompareTo(GradeRank(b.SelectableLevel.riskLevel));
			if (num != 0)
			{
				return num;
			}
			num = a.RoutePrice.CompareTo(b.RoutePrice);
			if (num == 0)
			{
				return string.Compare(a.NumberlessPlanetName, b.NumberlessPlanetName, StringComparison.OrdinalIgnoreCase);
			}
			return num;
		}

		private static int Band(string grade)
		{
			return GradeRank(grade) switch
			{
				1000 => 99, 
				0 => 0, 
				_ => "FEDCBAS".IndexOf(grade.Trim().ToUpperInvariant()[0]) + 1, 
			};
		}

		private static string BandName(int band)
		{
			switch (band)
			{
			default:
				return "OTHER";
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				return "FEDCBAS"[band - 1].ToString();
			case 0:
				return "SAFE";
			}
		}

		internal static int GradeRank(string grade)
		{
			if (string.IsNullOrWhiteSpace(grade))
			{
				return 1000;
			}
			string text = grade.Trim().ToUpperInvariant();
			if (text.StartsWith("SAFE"))
			{
				return 0;
			}
			int num = "FEDCBAS".IndexOf(text[0]);
			if (num < 0)
			{
				return 1000;
			}
			int num2 = 0;
			int num3 = 0;
			string text2 = text;
			for (int i = 0; i < text2.Length; i++)
			{
				switch (text2[i])
				{
				case '+':
					num2++;
					break;
				case '-':
					num3++;
					break;
				}
			}
			return 10 + num * 10 + num2 - num3;
		}
	}
}