// Consolidated decompiled source — SunkenlandModding-UnityExplorer v4.8.2 // Generated by Hexium's decompiled-source browser. Best-effort concatenation of every type in this // version's manifest — decompiler output isn't guaranteed to compile as-is. using System; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Tomlet.Exceptions; using System.Text.RegularExpressions; using Tomlet.Attributes; using Tomlet.Models; using System.Globalization; using System.IO; using System.Collections; using System.Xml; using HarmonyLib; using UnityEngine.Events; using UnityEngine.UI; using UnityEngine; using UniverseLib.Utility; using System.Diagnostics; using UniverseLib.Runtime; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; using UniverseLib.Runtime.Mono; using UniverseLib.Config; using UniverseLib.Input; using UniverseLib.UI; using UniverseLib.UI.Panels; using UniverseLib.UI.Models; using UniverseLib.UI.Widgets; using UniverseLib.UI.Widgets.ScrollView; using UniverseLib.UI.ObjectPool; using System.Collections.Specialized; using UnityExplorer.UI; using UniverseLib; using UnityExplorer.Config; using UnityExplorer.ObjectExplorer; using UnityExplorer.Runtime; using UnityExplorer.UI.Panels; using UnityExplorer.CacheObject; using UnityExplorer.Inspectors; using BepInEx; using BepInEx.Logging; using UnityExplorer.Loader.BIE; using UnityExplorer.CSConsole; using UnityExplorer.UI.Widgets; using UnityExplorer.UI.Widgets.AutoComplete; using UniverseLib.UI.Widgets.ButtonList; using UnityExplorer.CacheObject.IValues; using UnityExplorer.Hooks; using UnityExplorer.Inspectors.MouseInspectors; using UnityExplorer.CacheObject.Views; using Mono.CSharp.IL2CPP; using BepInEx.Configuration; using System.Reflection.Emit; using Mono.CSharp; using UnityExplorer.CSConsole.Lexers; using Tomlet; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Diagnostics.SymbolStore; using Mono.CompilerServices.SymbolWriter; using System.Linq.Expressions; using System.Security; using System.Security.Permissions; using Mono.CSharp.Nullable; using Mono.CSharp.Linq; using System.CodeDom.Compiler; using Mono.CSharp.yydebug; using Mono.CSharp.yyParser; using System.Threading; using MonoMod.RuntimeDetour; // ---- Tomlet.dll :: Microsoft.CodeAnalysis.EmbeddedAttribute ---- namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } // ---- Tomlet.dll :: System.Runtime.CompilerServices.NullableAttribute ---- namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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; } } } // ---- Tomlet.dll :: System.Runtime.CompilerServices.NullableContextAttribute ---- namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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; } } } // ---- Tomlet.dll :: Tomlet.Extensions ---- namespace Tomlet { internal static class Extensions { private static readonly HashSet IllegalChars = new HashSet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127 }; internal static bool IsWhitespace(this int val) { if (!val.IsNewline()) { return char.IsWhiteSpace((char)val); } return false; } internal static bool IsEquals(this int val) { return val == 61; } internal static bool IsSingleQuote(this int val) { return val == 39; } internal static bool IsDoubleQuote(this int val) { return val == 34; } internal static bool IsHashSign(this int val) { return val == 35; } internal static bool IsNewline(this int val) { if (val != 13) { return val == 10; } return true; } internal static bool IsDigit(this int val) { return char.IsDigit((char)val); } internal static bool IsComma(this int val) { return val == 44; } internal static bool IsPeriod(this int val) { return val == 46; } internal static bool IsEndOfArrayChar(this int val) { return val == 93; } internal static bool IsEndOfInlineObjectChar(this int val) { return val == 125; } internal static bool IsHexDigit(this char c) { if (IsDigit(c)) { return true; } char c2 = char.ToUpperInvariant(c); if (c2 >= 'A') { return c2 <= 'F'; } return false; } internal static bool TryPeek(this TomletStringReader reader, out int nextChar) { nextChar = reader.Peek(); return nextChar != -1; } internal static int SkipWhitespace(this TomletStringReader reader) { return reader.ReadWhile((int c) => c.IsWhitespace()).Length; } internal static void SkipPotentialCarriageReturn(this TomletStringReader reader) { if (reader.TryPeek(out var nextChar) && nextChar == 13) { reader.Read(); } } internal static void SkipAnyComment(this TomletStringReader reader) { if (reader.TryPeek(out var nextChar) && nextChar.IsHashSign()) { reader.ReadWhile((int commentChar) => !commentChar.IsNewline()); } } internal static int SkipAnyNewlineOrWhitespace(this TomletStringReader reader) { return reader.ReadWhile((int c) => c.IsNewline() || c.IsWhitespace()).Count((char c) => c == '\n'); } internal static int SkipAnyCommentNewlineWhitespaceEtc(this TomletStringReader reader) { int num = 0; int nextChar; while (reader.TryPeek(out nextChar) && (nextChar.IsHashSign() || nextChar.IsNewline() || nextChar.IsWhitespace())) { if (nextChar.IsHashSign()) { reader.SkipAnyComment(); } num += reader.SkipAnyNewlineOrWhitespace(); } return num; } internal static int SkipAnyNewline(this TomletStringReader reader) { return reader.ReadWhile((int c) => c.IsNewline()).Count((char c) => c == '\n'); } internal static char[] ReadChars(this TomletStringReader reader, int count) { char[] array = new char[count]; reader.ReadBlock(array, 0, count); return array; } internal static string ReadWhile(this TomletStringReader reader, Predicate predicate) { StringBuilder stringBuilder = new StringBuilder(); int nextChar; while (reader.TryPeek(out nextChar) && predicate(nextChar)) { stringBuilder.Append((char)reader.Read()); } return stringBuilder.ToString(); } internal static bool ExpectAndConsume(this TomletStringReader reader, char expectWhat) { if (!reader.TryPeek(out var nextChar)) { return false; } if (nextChar == expectWhat) { reader.Read(); return true; } return false; } public static void Deconstruct(this KeyValuePair pair, out TKey one, out TValue two) { one = pair.Key; two = pair.Value; } public static bool IsNullOrWhiteSpace(this string s) { if (!string.IsNullOrEmpty(s)) { return string.IsNullOrEmpty(s.Trim()); } return true; } internal static T? GetCustomAttribute(this MemberInfo info) where T : Attribute { return (from a in info.GetCustomAttributes(inherit: false) where a is T select a).Cast().FirstOrDefault(); } internal static void EnsureLegalChar(this int c, int currentLineNum) { if (IllegalChars.Contains(c)) { throw new TomlUnescapedUnicodeControlCharException(currentLineNum, c); } } } } // ---- Tomlet.dll :: Tomlet.TomlCompositeDeserializer ---- namespace Tomlet { internal static class TomlCompositeDeserializer { public static TomlSerializationMethods.Deserialize For(Type type) { TomlSerializationMethods.Deserialize deserialize; if (type.IsEnum) { TomlSerializationMethods.Deserialize stringDeserializer = TomlSerializationMethods.GetDeserializer(typeof(string)); deserialize = delegate(TomlValue value) { string text = (string)stringDeserializer(value); try { return Enum.Parse(type, text, ignoreCase: true); } catch (Exception) { throw new TomlEnumParseException(text, type); } }; } else { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fields = fields.Where((FieldInfo f) => !f.IsNotSerialized).ToArray(); if (fields.Length == 0) { return delegate { try { return Activator.CreateInstance(type); } catch (MissingMethodException) { throw new TomlInstantiationException(type); } }; } deserialize = delegate(TomlValue value) { if (!(value is TomlTable tomlTable)) { throw new TomlTypeMismatchException(typeof(TomlTable), value.GetType(), type); } object obj; try { obj = Activator.CreateInstance(type); } catch (MissingMethodException) { throw new TomlInstantiationException(type); } FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { try { string text = fieldInfo.Name; Match match = Regex.Match(fieldInfo.Name, "<(.*)>k__BackingField"); if (match.Success) { text = match.Groups[1].Value; } string name1 = text; PropertyInfo propertyInfo = type.GetProperties().FirstOrDefault((PropertyInfo p) => p.Name == name1); text = (((object)propertyInfo == null) ? null : propertyInfo.GetCustomAttribute()?.GetMappedString()) ?? text; if (tomlTable.ContainsKey(text)) { TomlValue value2 = tomlTable.GetValue(text); object value3 = TomlSerializationMethods.GetDeserializer(fieldInfo.FieldType)(value2); fieldInfo.SetValue(obj, value3); } } catch (TomlTypeMismatchException cause) { throw new TomlFieldTypeMismatchException(type, fieldInfo, cause); } } return obj; }; } TomlSerializationMethods.Register(type, null, deserialize); return deserialize; } } } // ---- Tomlet.dll :: Tomlet.TomlCompositeSerializer ---- namespace Tomlet { internal static class TomlCompositeSerializer { public static TomlSerializationMethods.Serialize For(Type type) { TomlSerializationMethods.Serialize serialize; if (type.IsEnum) { TomlSerializationMethods.Serialize stringSerializer = TomlSerializationMethods.GetSerializer(typeof(string)); serialize = (object? o) => stringSerializer(Enum.GetName(type, o) ?? throw new ArgumentException($"Tomlet: Cannot serialize {o} as an enum of type {type} because the enum type does not declare a name for that value")); } else { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var fieldAttribs = fields.ToDictionary((FieldInfo f) => f, (FieldInfo f) => new { inline = f.GetCustomAttribute(), preceding = f.GetCustomAttribute() }); PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var propAttribs = props.ToDictionary((PropertyInfo p) => p, (PropertyInfo p) => new { inline = p.GetCustomAttribute(), preceding = p.GetCustomAttribute() }); bool isForcedNoInline = type.GetCustomAttribute() != null; fields = fields.Where((FieldInfo f) => !f.IsNotSerialized).ToArray(); if (fields.Length == 0) { return (object? _) => new TomlTable(); } serialize = delegate(object? instance) { if (instance == null) { throw new ArgumentNullException("instance", "Object being serialized is null. TOML does not support null values."); } TomlTable tomlTable = new TomlTable { ForceNoInline = isForcedNoInline }; FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { object value = fieldInfo.GetValue(instance); if (value != null) { TomlValue tomlValue = TomlSerializationMethods.GetSerializer(fieldInfo.FieldType)(value); string name = fieldInfo.Name; var anon = fieldAttribs[fieldInfo]; Match match = Regex.Match(fieldInfo.Name, "<(.*)>k__BackingField"); if (match.Success) { name = match.Groups[1].Value; PropertyInfo key = props.First((PropertyInfo p) => p.Name == name); anon = propAttribs[key]; } string name2 = name; PropertyInfo propertyInfo = type.GetProperties().FirstOrDefault((PropertyInfo p) => p.Name == name2); name = (((object)propertyInfo == null) ? null : propertyInfo.GetCustomAttribute()?.GetMappedString()) ?? name; if (!tomlTable.ContainsKey(name)) { tomlValue.Comments.InlineComment = anon.inline?.Comment; tomlValue.Comments.PrecedingComment = anon.preceding?.Comment; tomlTable.PutValue(name, tomlValue); } } } return tomlTable; }; } TomlSerializationMethods.Register(type, serialize, null); return serialize; } } } // ---- Tomlet.dll :: Tomlet.TomlDateTimeUtils ---- namespace Tomlet { internal static class TomlDateTimeUtils { private static readonly Regex DateTimeRegex = new Regex("^(?:(\\d+)-(0[1-9]|1[012])-(0[1-9]|[12]\\d|3[01]))?([\\sTt])?(?:([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d|60)(\\.\\d+)?((?:[Zz])|(?:[\\+|\\-](?:[01]\\d|2[0-3])(?::[0-6][0-9])?(?::[0-6][0-9])?))?)?$", RegexOptions.Compiled); internal static TomlValue? ParseDateString(string input, int lineNumber) { Match match = DateTimeRegex.Match(input); bool flag = !match.Groups[1].Value.IsNullOrWhiteSpace(); bool flag2 = !string.IsNullOrEmpty(match.Groups[4].Value); bool flag3 = !match.Groups[5].Value.IsNullOrWhiteSpace(); bool flag4 = !match.Groups[9].Value.IsNullOrWhiteSpace(); if (flag && flag3 && !flag2) { throw new TomlDateTimeMissingSeparatorException(lineNumber); } if (flag2 && (!flag3 || !flag)) { throw new TomlDateTimeUnnecessarySeparatorException(lineNumber); } if (flag4 && (!flag3 || !flag)) { throw new TimeOffsetOnTomlDateOrTimeException(lineNumber, match.Groups[9].Value); } if (!flag) { return TomlLocalTime.Parse(input); } if (!flag3) { return TomlLocalDate.Parse(input); } if (!flag4) { return TomlLocalDateTime.Parse(input); } return TomlOffsetDateTime.Parse(input); } } } // ---- Tomlet.dll :: Tomlet.TomletMain ---- namespace Tomlet { public static class TomletMain { [NoCoverage] public static void RegisterMapper(TomlSerializationMethods.Serialize? serializer, TomlSerializationMethods.Deserialize? deserializer) { TomlSerializationMethods.Register(serializer, deserializer); } public static T To(string tomlString) { return To(new TomlParser().Parse(tomlString)); } public static T To(TomlValue value) { return (T)To(typeof(T), value); } public static object To(Type what, TomlValue value) { return TomlSerializationMethods.GetDeserializer(what)(value); } public static TomlValue ValueFrom(T t) { if (t == null) { throw new ArgumentNullException("t"); } return ValueFrom(t.GetType(), t); } public static TomlValue ValueFrom(Type type, object t) { return TomlSerializationMethods.GetSerializer(type)(t); } public static TomlDocument DocumentFrom(T t) { if (t == null) { throw new ArgumentNullException("t"); } return DocumentFrom(t.GetType(), t); } public static TomlDocument DocumentFrom(Type type, object t) { TomlValue tomlValue = ValueFrom(type, t); if (!(tomlValue is TomlDocument result)) { if (tomlValue is TomlTable tomlTable) { return new TomlDocument(tomlTable); } throw new TomlPrimitiveToDocumentException(type); } return result; } public static string TomlStringFrom(T t) { return DocumentFrom(t).SerializedValue; } public static string TomlStringFrom(Type type, object t) { return DocumentFrom(type, t).SerializedValue; } } } // ---- Tomlet.dll :: Tomlet.TomletStringReader ---- namespace Tomlet { public class TomletStringReader : IDisposable { private string? _s; private int _pos; private int _length; public TomletStringReader(string s) { _s = s; _length = s.Length; } public void Backtrack(int amount) { if (_pos < amount) { throw new Exception("Cannot backtrack past the beginning of the string"); } _pos -= amount; } public void Dispose() { _s = null; _pos = 0; _length = 0; } public int Peek() { if (_pos != _length) { return _s[_pos]; } return -1; } public int Read() { if (_pos != _length) { return _s[_pos++]; } return -1; } public int Read(char[] buffer, int index, int count) { int num = _length - _pos; if (num <= 0) { return num; } if (num > count) { num = count; } _s.CopyTo(_pos, buffer, index, num); _pos += num; return num; } public int ReadBlock(char[] buffer, int index, int count) { int num = 0; int num2; do { num += (num2 = Read(buffer, index + num, count - num)); } while (num2 > 0 && num < count); return num; } } } // ---- Tomlet.dll :: Tomlet.TomlKeyUtils ---- namespace Tomlet { internal static class TomlKeyUtils { internal static void GetTopLevelAndSubKeys(string key, out string ourKeyName, out string restOfKey) { bool flag = (key.StartsWith("\"") && key.EndsWith("\"")) || (key.StartsWith("'") && key.EndsWith("'")); bool flag2 = !flag && (key.StartsWith("\"") || key.StartsWith("'")); if (!key.Contains(".") || flag) { ourKeyName = key; restOfKey = ""; return; } if (!flag2) { string[] array = key.Split(new char[1] { '.' }); ourKeyName = array[0]; } else { ourKeyName = key; string text = ourKeyName.Substring(1); if (ourKeyName.Contains("\"")) { ourKeyName = ourKeyName.Substring(0, 2 + text.IndexOf("\"", StringComparison.Ordinal)); } else { ourKeyName = ourKeyName.Substring(0, 2 + text.IndexOf("'", StringComparison.Ordinal)); } } restOfKey = key.Substring(ourKeyName.Length + 1); ourKeyName = ourKeyName.Trim(); } } } // ---- Tomlet.dll :: Tomlet.TomlNumberStyle ---- namespace Tomlet { internal static class TomlNumberStyle { internal static NumberStyles FloatingPoint = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent; internal static NumberStyles Integer = NumberStyles.AllowLeadingSign | NumberStyles.AllowThousands; } } // ---- Tomlet.dll :: Tomlet.TomlNumberUtils ---- namespace Tomlet { public static class TomlNumberUtils { public static long? GetLongValue(string input) { bool flag = input.StartsWith("0o"); bool flag2 = input.StartsWith("0x"); bool flag3 = input.StartsWith("0b"); if (flag3 || flag2 || flag) { input = input.Substring(2); } if (input.Contains("__") || input.Any((char c) => c != '_' && c != '-' && c != '+' && !char.IsDigit(c) && (c < 'a' || c > 'f'))) { return null; } if (input.First() == '_') { return null; } if (input.Last() == '_') { return null; } input = input.Replace("_", ""); try { if (flag3) { return Convert.ToInt64(input, 2); } if (flag) { return Convert.ToInt64(input, 8); } if (flag2) { return Convert.ToInt64(input, 16); } return Convert.ToInt64(input, 10); } catch (Exception) { return null; } } public static double? GetDoubleValue(string input) { string text = input.Substring(1); if (input == "nan" || input == "inf" || text == "nan" || text == "inf") { if (input == "nan" || text == "nan") { return double.NaN; } if (input == "inf") { return double.PositiveInfinity; } if (text == "inf") { return input.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity; } } if (input.Contains("__") || input.Any((char c) => c != '_' && c != '-' && c != '+' && c != 'e' && c != '.' && !char.IsDigit(c))) { return null; } if (input.First() == '_') { return null; } if (input.Last() == '_') { return null; } input = input.Replace("_", ""); if (input.Contains("e")) { string[] array = input.Split(new char[1] { 'e' }); if (array.Length != 2) { return null; } if (array[0].EndsWith(".")) { return null; } } if (double.TryParse(input, TomlNumberStyle.FloatingPoint, CultureInfo.InvariantCulture, out var result)) { return result; } return null; } } } // ---- Tomlet.dll :: Tomlet.TomlParser ---- namespace Tomlet { public class TomlParser { private static readonly char[] TrueChars = new char[4] { 't', 'r', 'u', 'e' }; private static readonly char[] FalseChars = new char[5] { 'f', 'a', 'l', 's', 'e' }; private int _lineNumber = 1; private string[] _tableNames = new string[0]; private TomlTable? _currentTable; [NoCoverage] public static TomlDocument ParseFile(string filePath) { string input = File.ReadAllText(filePath); return new TomlParser().Parse(input); } public TomlDocument Parse(string input) { try { TomlDocument tomlDocument = new TomlDocument(); using TomletStringReader tomletStringReader = new TomletStringReader(input); string text = null; int nextChar; while (tomletStringReader.TryPeek(out nextChar)) { _lineNumber += tomletStringReader.SkipAnyNewlineOrWhitespace(); text = ReadAnyPotentialMultilineComment(tomletStringReader); if (!tomletStringReader.TryPeek(out var nextChar2)) { break; } if (nextChar2 == 91) { tomletStringReader.Read(); if (!tomletStringReader.TryPeek(out var nextChar3)) { throw new TomlEndOfFileException(_lineNumber); } TomlValue tomlValue = ((nextChar3 == 91) ? ((TomlValue)ReadTableArrayStatement(tomletStringReader, tomlDocument)) : ((TomlValue)ReadTableStatement(tomletStringReader, tomlDocument))); tomlValue.Comments.PrecedingComment = text; continue; } ReadKeyValuePair(tomletStringReader, out string key, out TomlValue value); value.Comments.PrecedingComment = text; text = null; if (_currentTable != null) { _currentTable.ParserPutValue(key, value, _lineNumber); } else { tomlDocument.ParserPutValue(key, value, _lineNumber); } tomletStringReader.SkipWhitespace(); tomletStringReader.SkipPotentialCarriageReturn(); if (!tomletStringReader.ExpectAndConsume('\n') && tomletStringReader.TryPeek(out var nextChar4)) { throw new TomlMissingNewlineException(_lineNumber, (char)nextChar4); } _lineNumber++; } tomlDocument.TrailingComment = text; return tomlDocument; } catch (Exception ex) when (!(ex is TomlException)) { throw new TomlInternalException(_lineNumber, ex); } } private void ReadKeyValuePair(TomletStringReader reader, out string key, out TomlValue value) { key = ReadKey(reader); reader.SkipWhitespace(); if (!reader.ExpectAndConsume('=')) { if (reader.TryPeek(out var nextChar)) { throw new TomlMissingEqualsException(_lineNumber, (char)nextChar); } throw new TomlEndOfFileException(_lineNumber); } reader.SkipWhitespace(); value = ReadValue(reader); } private string ReadKey(TomletStringReader reader) { reader.SkipWhitespace(); if (!reader.TryPeek(out var nextChar)) { return ""; } if (nextChar.IsEquals()) { throw new NoTomlKeyException(_lineNumber); } reader.SkipWhitespace(); string text; if (nextChar.IsDoubleQuote()) { reader.Read(); if (reader.TryPeek(out var nextChar2) && nextChar2.IsDoubleQuote()) { reader.Read(); if (reader.TryPeek(out var nextChar3) && nextChar3.IsDoubleQuote()) { throw new TomlTripleQuotedKeyException(_lineNumber); } return string.Empty; } text = "\"" + ReadSingleLineBasicString(reader, consumeClosingQuote: false).StringValue + "\""; if (!reader.ExpectAndConsume('"')) { throw new UnterminatedTomlKeyException(_lineNumber); } } else if (nextChar.IsSingleQuote()) { reader.Read(); text = "'" + ReadSingleLineLiteralString(reader, consumeClosingQuote: false).StringValue + "'"; if (!reader.ExpectAndConsume('\'')) { throw new UnterminatedTomlKeyException(_lineNumber); } } else { text = ReadKeyInternal(reader, (int keyChar) => keyChar.IsEquals() || keyChar.IsHashSign()); } return text.Replace("\\n", "\n").Replace("\\t", "\t"); } private string ReadKeyInternal(TomletStringReader reader, Func charSignalsEndOfKey) { List list = new List(); int nextChar; while (reader.TryPeek(out nextChar)) { if (charSignalsEndOfKey(nextChar)) { return string.Join(".", list.ToArray()); } if (nextChar.IsPeriod()) { throw new TomlDoubleDottedKeyException(_lineNumber); } StringBuilder stringBuilder = new StringBuilder(); while (reader.TryPeek(out nextChar)) { nextChar.EnsureLegalChar(_lineNumber); int num = reader.SkipWhitespace(); reader.TryPeek(out var nextChar2); if (nextChar2.IsPeriod()) { list.Add(stringBuilder.ToString()); reader.ExpectAndConsume('.'); reader.SkipWhitespace(); break; } if (num > 0 && charSignalsEndOfKey(nextChar2)) { list.Add(stringBuilder.ToString()); break; } reader.Backtrack(num); if (charSignalsEndOfKey(nextChar)) { list.Add(stringBuilder.ToString()); break; } if (num > 0) { throw new TomlWhitespaceInKeyException(_lineNumber); } stringBuilder.Append((char)reader.Read()); } } throw new TomlEndOfFileException(_lineNumber); } private TomlValue ReadValue(TomletStringReader reader) { if (!reader.TryPeek(out var nextChar)) { throw new TomlEndOfFileException(_lineNumber); } TomlValue tomlValue; switch (nextChar) { case 91: tomlValue = ReadArray(reader); break; case 123: tomlValue = ReadInlineTable(reader); break; case 34: case 39: { int num = reader.Read(); if (reader.Peek() != num) { tomlValue = (num.IsSingleQuote() ? ReadSingleLineLiteralString(reader) : ReadSingleLineBasicString(reader)); break; } reader.Read(); int num2 = reader.Peek(); if (num2 == num) { reader.Read(); tomlValue = (num.IsSingleQuote() ? ReadMultiLineLiteralString(reader) : ReadMultiLineBasicString(reader)); break; } if (num2.IsWhitespace() || num2.IsNewline() || num2.IsHashSign() || num2.IsComma() || num2.IsEndOfArrayChar() || num2 == -1) { tomlValue = TomlString.Empty; break; } throw new TomlStringException(_lineNumber); } case 43: case 45: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 105: case 110: { string text = reader.ReadWhile((int valueChar) => !valueChar.IsEquals() && !valueChar.IsNewline() && !valueChar.IsHashSign() && !valueChar.IsComma() && !valueChar.IsEndOfArrayChar() && !valueChar.IsEndOfInlineObjectChar()).ToLowerInvariant().Trim(); tomlValue = ((!Enumerable.Contains(text, ':') && !Enumerable.Contains(text, 't') && !Enumerable.Contains(text, ' ') && !Enumerable.Contains(text, 'z')) ? ((!Enumerable.Contains(text, '.') && (!Enumerable.Contains(text, 'e') || text.StartsWith("0x")) && !Enumerable.Contains(text, 'n') && !Enumerable.Contains(text, 'i')) ? (TomlLong.Parse(text) ?? TomlDateTimeUtils.ParseDateString(text, _lineNumber) ?? throw new InvalidTomlNumberException(_lineNumber, text)) : (TomlDouble.Parse(text) ?? TomlDateTimeUtils.ParseDateString(text, _lineNumber) ?? throw new InvalidTomlNumberException(_lineNumber, text))) : (TomlDateTimeUtils.ParseDateString(text, _lineNumber) ?? throw new InvalidTomlDateTimeException(_lineNumber, text))); break; } case 116: { char[] second2 = reader.ReadChars(4); if (!Enumerable.SequenceEqual(TrueChars, second2)) { throw new TomlInvalidValueException(_lineNumber, (char)nextChar); } tomlValue = TomlBoolean.True; break; } case 102: { char[] second = reader.ReadChars(5); if (!Enumerable.SequenceEqual(FalseChars, second)) { throw new TomlInvalidValueException(_lineNumber, (char)nextChar); } tomlValue = TomlBoolean.False; break; } default: throw new TomlInvalidValueException(_lineNumber, (char)nextChar); } reader.SkipWhitespace(); tomlValue.Comments.InlineComment = ReadAnyPotentialInlineComment(reader); return tomlValue; } private TomlValue ReadSingleLineBasicString(TomletStringReader reader, bool consumeClosingQuote = true) { StringBuilder stringBuilder = new StringBuilder(); bool flag = false; bool fourDigitUnicodeMode = false; bool eightDigitUnicodeMode = false; StringBuilder stringBuilder2 = new StringBuilder(); int nextChar; while (reader.TryPeek(out nextChar)) { nextChar.EnsureLegalChar(_lineNumber); if (nextChar == 34 && !flag) { break; } reader.Read(); if (nextChar == 92 && !flag) { flag = true; } else if (flag) { flag = false; char? c = HandleEscapedChar(nextChar, out fourDigitUnicodeMode, out eightDigitUnicodeMode); if (c.HasValue) { stringBuilder.Append(c.Value); } } else if (fourDigitUnicodeMode || eightDigitUnicodeMode) { stringBuilder2.Append((char)nextChar); if ((fourDigitUnicodeMode && stringBuilder2.Length == 4) || (eightDigitUnicodeMode && stringBuilder2.Length == 8)) { string unicodeString = stringBuilder2.ToString(); stringBuilder.Append(DecipherUnicodeEscapeSequence(unicodeString, fourDigitUnicodeMode)); fourDigitUnicodeMode = false; eightDigitUnicodeMode = false; stringBuilder2 = new StringBuilder(); } } else { if (nextChar.IsNewline()) { throw new UnterminatedTomlStringException(_lineNumber); } stringBuilder.Append((char)nextChar); } } if (consumeClosingQuote && !reader.ExpectAndConsume('"')) { throw new UnterminatedTomlStringException(_lineNumber); } return new TomlString(stringBuilder.ToString()); } private string DecipherUnicodeEscapeSequence(string unicodeString, bool fourDigitMode) { if (unicodeString.Any((char c) => !c.IsHexDigit())) { throw new InvalidTomlEscapeException(_lineNumber, $"\\{(fourDigitMode ? 'u' : 'U')}{unicodeString}"); } if (fourDigitMode) { return ((char)short.Parse(unicodeString, NumberStyles.HexNumber)).ToString(); } return char.ConvertFromUtf32(int.Parse(unicodeString, NumberStyles.HexNumber)); } private char? HandleEscapedChar(int escapedChar, out bool fourDigitUnicodeMode, out bool eightDigitUnicodeMode, bool allowNewline = false) { eightDigitUnicodeMode = false; fourDigitUnicodeMode = false; char value; switch (escapedChar) { case 98: value = '\b'; break; case 116: value = '\t'; break; case 110: value = '\n'; break; case 102: value = '\f'; break; case 114: value = '\r'; break; case 34: value = '"'; break; case 92: value = '\\'; break; case 117: fourDigitUnicodeMode = true; return null; case 85: eightDigitUnicodeMode = true; return null; default: if (allowNewline && escapedChar.IsNewline()) { return null; } throw new InvalidTomlEscapeException(_lineNumber, $"\\{escapedChar}"); } return value; } private TomlValue ReadSingleLineLiteralString(TomletStringReader reader, bool consumeClosingQuote = true) { string text = reader.ReadWhile((int valueChar) => !valueChar.IsSingleQuote() && !valueChar.IsNewline()); foreach (int item in ((IEnumerable)text).Select((Func)((char c) => c))) { item.EnsureLegalChar(_lineNumber); } if (!reader.TryPeek(out var nextChar)) { throw new TomlEndOfFileException(_lineNumber); } if (!nextChar.IsSingleQuote()) { throw new UnterminatedTomlStringException(_lineNumber); } if (consumeClosingQuote) { reader.Read(); } return new TomlString(text); } private TomlValue ReadMultiLineLiteralString(TomletStringReader reader) { StringBuilder stringBuilder = new StringBuilder(); _lineNumber += reader.SkipAnyNewline(); int nextChar; while (reader.TryPeek(out nextChar)) { int num = reader.Read(); num.EnsureLegalChar(_lineNumber); if (!num.IsSingleQuote()) { stringBuilder.Append((char)num); if (num == 10) { _lineNumber++; } continue; } if (!reader.TryPeek(out var nextChar2) || !nextChar2.IsSingleQuote()) { stringBuilder.Append('\''); continue; } reader.Read(); if (!reader.TryPeek(out var nextChar3) || !nextChar3.IsSingleQuote()) { stringBuilder.Append('\''); stringBuilder.Append('\''); continue; } reader.Read(); if (!reader.TryPeek(out var nextChar4) || !nextChar4.IsSingleQuote()) { break; } reader.Read(); stringBuilder.Append('\''); if (!reader.TryPeek(out var nextChar5) || !nextChar5.IsSingleQuote()) { break; } reader.Read(); stringBuilder.Append('\''); if (!reader.TryPeek(out var nextChar6) || !nextChar6.IsSingleQuote()) { break; } throw new TripleQuoteInTomlMultilineLiteralException(_lineNumber); } return new TomlString(stringBuilder.ToString()); } private TomlValue ReadMultiLineBasicString(TomletStringReader reader) { StringBuilder stringBuilder = new StringBuilder(); bool flag = false; bool fourDigitUnicodeMode = false; bool eightDigitUnicodeMode = false; StringBuilder stringBuilder2 = new StringBuilder(); _lineNumber += reader.SkipAnyNewline(); int nextChar; while (reader.TryPeek(out nextChar)) { int num = reader.Read(); num.EnsureLegalChar(_lineNumber); if (num == 92 && !flag) { flag = true; continue; } if (flag) { flag = false; char? c = HandleEscapedChar(num, out fourDigitUnicodeMode, out eightDigitUnicodeMode, allowNewline: true); if (c.HasValue) { stringBuilder.Append(c.Value); } else if (num.IsNewline()) { if (num == 13 && !reader.ExpectAndConsume('\n')) { throw new Exception($"Found a CR without an LF on line {_lineNumber}"); } _lineNumber++; reader.SkipAnyNewlineOrWhitespace(); } continue; } if (fourDigitUnicodeMode || eightDigitUnicodeMode) { stringBuilder2.Append((char)num); if ((fourDigitUnicodeMode && stringBuilder2.Length == 4) || (eightDigitUnicodeMode && stringBuilder2.Length == 8)) { string unicodeString = stringBuilder2.ToString(); stringBuilder.Append(DecipherUnicodeEscapeSequence(unicodeString, fourDigitUnicodeMode)); fourDigitUnicodeMode = false; eightDigitUnicodeMode = false; stringBuilder2 = new StringBuilder(); } continue; } if (!num.IsDoubleQuote()) { if (num == 10) { _lineNumber++; } stringBuilder.Append((char)num); continue; } if (!reader.TryPeek(out var nextChar2) || !nextChar2.IsDoubleQuote()) { stringBuilder.Append('"'); continue; } reader.Read(); if (!reader.TryPeek(out var nextChar3) || !nextChar3.IsDoubleQuote()) { stringBuilder.Append('"'); stringBuilder.Append('"'); continue; } reader.Read(); if (!reader.TryPeek(out var nextChar4) || !nextChar4.IsDoubleQuote()) { break; } reader.Read(); stringBuilder.Append('"'); if (!reader.TryPeek(out var nextChar5) || !nextChar5.IsDoubleQuote()) { break; } reader.Read(); stringBuilder.Append('"'); if (!reader.TryPeek(out var nextChar6) || !nextChar6.IsDoubleQuote()) { break; } throw new TripleQuoteInTomlMultilineSimpleStringException(_lineNumber); } return new TomlString(stringBuilder.ToString()); } private TomlArray ReadArray(TomletStringReader reader) { if (!reader.ExpectAndConsume('[')) { throw new ArgumentException("Internal Tomlet Bug: ReadArray called and first char is not a ["); } _lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc(); TomlArray tomlArray = new TomlArray(); int nextChar; while (reader.TryPeek(out nextChar)) { _lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc(); if (!reader.TryPeek(out var nextChar2)) { throw new TomlEndOfFileException(_lineNumber); } if (nextChar2.IsEndOfArrayChar()) { break; } tomlArray.ArrayValues.Add(ReadValue(reader)); _lineNumber += reader.SkipAnyNewlineOrWhitespace(); if (!reader.TryPeek(out var nextChar3)) { throw new TomlEndOfFileException(_lineNumber); } if (nextChar3.IsEndOfArrayChar()) { break; } if (!nextChar3.IsComma()) { throw new TomlArraySyntaxException(_lineNumber, (char)nextChar3); } reader.ExpectAndConsume(','); } reader.ExpectAndConsume(']'); return tomlArray; } private TomlTable ReadInlineTable(TomletStringReader reader) { if (!reader.ExpectAndConsume('{')) { throw new ArgumentException("Internal Tomlet Bug: ReadInlineTable called and first char is not a {"); } _lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc(); TomlTable tomlTable = new TomlTable { Defined = true }; int nextChar; while (reader.TryPeek(out nextChar)) { reader.SkipWhitespace(); if (!reader.TryPeek(out var nextChar2)) { throw new TomlEndOfFileException(_lineNumber); } if (nextChar2.IsEndOfInlineObjectChar()) { break; } if (nextChar2.IsNewline()) { throw new NewLineInTomlInlineTableException(_lineNumber); } try { ReadKeyValuePair(reader, out string key, out TomlValue value); tomlTable.ParserPutValue(key, value, _lineNumber); } catch (TomlException ex) when (ex is TomlMissingEqualsException || ex is NoTomlKeyException || ex is TomlWhitespaceInKeyException) { throw new InvalidTomlInlineTableException(_lineNumber, ex); } if (!reader.TryPeek(out var nextChar3)) { throw new TomlEndOfFileException(_lineNumber); } if (!reader.ExpectAndConsume(',')) { reader.SkipWhitespace(); if (!reader.TryPeek(out nextChar3)) { throw new TomlEndOfFileException(_lineNumber); } if (nextChar3.IsEndOfInlineObjectChar()) { break; } throw new TomlInlineTableSeparatorException(_lineNumber, (char)nextChar3); } } reader.ExpectAndConsume('}'); tomlTable.Locked = true; return tomlTable; } private TomlTable ReadTableStatement(TomletStringReader reader, TomlDocument document) { string text = reader.ReadWhile((int c) => !c.IsEndOfArrayChar() && !c.IsNewline()); TomlTable parent = document; string relativeName = text; FindParentAndRelativeKey(ref parent, ref relativeName); TomlTable tomlTable; try { if (parent.ContainsKey(relativeName)) { try { tomlTable = (TomlTable)parent.GetValue(relativeName); if (tomlTable.Defined) { throw new TomlTableRedefinitionException(_lineNumber, text); } } catch (InvalidCastException) { throw new TomlKeyRedefinitionException(_lineNumber, text); } } else { tomlTable = new TomlTable { Defined = true }; parent.ParserPutValue(relativeName, tomlTable, _lineNumber); } } catch (TomlContainsDottedKeyNonTableException ex2) { throw new TomlDottedKeyParserException(_lineNumber, ex2.Key); } if (!reader.TryPeek(out var _)) { throw new TomlEndOfFileException(_lineNumber); } if (!reader.ExpectAndConsume(']')) { throw new UnterminatedTomlTableNameException(_lineNumber); } reader.SkipWhitespace(); tomlTable.Comments.InlineComment = ReadAnyPotentialInlineComment(reader); reader.SkipPotentialCarriageReturn(); if (!reader.TryPeek(out var nextChar2)) { throw new TomlEndOfFileException(_lineNumber); } if (!nextChar2.IsNewline()) { throw new TomlMissingNewlineException(_lineNumber, (char)nextChar2); } _currentTable = tomlTable; _tableNames = text.Split(new char[1] { '.' }); return tomlTable; } private TomlArray ReadTableArrayStatement(TomletStringReader reader, TomlDocument document) { if (!reader.ExpectAndConsume('[')) { throw new ArgumentException("Internal Tomlet Bug: ReadTableArrayStatement called and first char is not a ["); } string text = reader.ReadWhile((int c) => !c.IsEndOfArrayChar() && !c.IsNewline()); if (!reader.ExpectAndConsume(']') || !reader.ExpectAndConsume(']')) { throw new UnterminatedTomlTableArrayException(_lineNumber); } TomlTable parent = document; string relativeName = text; FindParentAndRelativeKey(ref parent, ref relativeName); if (parent == document && Enumerable.Contains(relativeName, '.')) { throw new MissingIntermediateInTomlTableArraySpecException(_lineNumber, relativeName); } TomlArray tomlArray2; if (parent.ContainsKey(relativeName)) { if (!(parent.GetValue(relativeName) is TomlArray tomlArray)) { throw new TomlTableArrayAlreadyExistsAsNonArrayException(_lineNumber, text); } tomlArray2 = tomlArray; if (!tomlArray2.IsLockedToBeTableArray) { throw new TomlNonTableArrayUsedAsTableArrayException(_lineNumber, text); } } else { tomlArray2 = new TomlArray { IsLockedToBeTableArray = true }; parent.ParserPutValue(relativeName, tomlArray2, _lineNumber); } _currentTable = new TomlTable { Defined = true }; tomlArray2.ArrayValues.Add(_currentTable); _tableNames = text.Split(new char[1] { '.' }); return tomlArray2; } private void FindParentAndRelativeKey(ref TomlTable parent, ref string relativeName) { for (int i = 0; i < _tableNames.Length; i++) { string text = _tableNames[i]; if (!relativeName.StartsWith(text + ".")) { break; } TomlValue value = parent.GetValue(text); if (value is TomlTable tomlTable) { parent = tomlTable; } else { if (!(value is TomlArray source)) { throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), typeof(TomlArray)); } parent = (TomlTable)source.Last(); } relativeName = relativeName.Substring(text.Length + 1); } } private string? ReadAnyPotentialInlineComment(TomletStringReader reader) { if (!reader.ExpectAndConsume('#')) { return null; } string text = reader.ReadWhile((int c) => !c.IsNewline()).Trim(); if (text.Length < 1) { return null; } if (text[0] == ' ') { text = text.Substring(1); } foreach (int item in ((IEnumerable)text).Select((Func)((char c) => c))) { item.EnsureLegalChar(_lineNumber); } return text; } private string? ReadAnyPotentialMultilineComment(TomletStringReader reader) { StringBuilder stringBuilder = new StringBuilder(); while (reader.ExpectAndConsume('#')) { string text = reader.ReadWhile((int c) => !c.IsNewline()); if (text[0] == ' ') { text = text.Substring(1); } foreach (int item in ((IEnumerable)text).Select((Func)((char c) => c))) { item.EnsureLegalChar(_lineNumber); } stringBuilder.Append(text); _lineNumber += reader.SkipAnyNewlineOrWhitespace(); } if (stringBuilder.Length == 0) { return null; } return stringBuilder.ToString(); } } } // ---- Tomlet.dll :: Tomlet.TomlSerializationMethods ---- namespace Tomlet { public static class TomlSerializationMethods { public delegate T Deserialize(TomlValue value); public delegate TomlValue Serialize(T? t); private static readonly Dictionary Deserializers; private static readonly Dictionary Serializers; [NoCoverage] static TomlSerializationMethods() { Deserializers = new Dictionary(); Serializers = new Dictionary(); Register((string? s) => new TomlString(s), (TomlValue value) => (value as TomlString)?.Value ?? value.StringValue); Register(TomlBoolean.ValueOf, (TomlValue value) => ((value as TomlBoolean) ?? throw new TomlTypeMismatchException(typeof(TomlBoolean), value.GetType(), typeof(bool))).Value); Register((byte i) => new TomlLong(i), (TomlValue value) => (byte)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(byte))).Value); Register((sbyte i) => new TomlLong(i), (TomlValue value) => (sbyte)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(sbyte))).Value); Register((ushort i) => new TomlLong(i), (TomlValue value) => (ushort)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(ushort))).Value); Register((short i) => new TomlLong(i), (TomlValue value) => (short)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(short))).Value); Register((uint i) => new TomlLong(i), (TomlValue value) => (uint)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(uint))).Value); Register((int i) => new TomlLong(i), (TomlValue value) => (int)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(int))).Value); Register((ulong l) => new TomlLong((long)l), (TomlValue value) => (ulong)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(ulong))).Value); Register((long l) => new TomlLong(l), (TomlValue value) => ((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(long))).Value); Register((double d) => new TomlDouble(d), (TomlValue value) => (value as TomlDouble)?.Value ?? ((double)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlDouble), value.GetType(), typeof(double))).Value)); Register((float f) => new TomlDouble(f), (TomlValue value) => (float)((value as TomlDouble)?.Value ?? ((double)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlDouble), value.GetType(), typeof(float))).Value))); Register((DateTime dt) => (!(dt.TimeOfDay == TimeSpan.Zero)) ? ((TomlValue)new TomlLocalDateTime(dt)) : ((TomlValue)new TomlLocalDate(dt)), (TomlValue value) => ((value as ITomlValueWithDateTime) ?? throw new TomlTypeMismatchException(typeof(ITomlValueWithDateTime), value.GetType(), typeof(DateTime))).Value); Register((DateTimeOffset odt) => new TomlOffsetDateTime(odt), (TomlValue value) => ((value as TomlOffsetDateTime) ?? throw new TomlTypeMismatchException(typeof(TomlOffsetDateTime), value.GetType(), typeof(DateTimeOffset))).Value); Register((TimeSpan lt) => new TomlLocalTime(lt), (TomlValue value) => ((value as TomlLocalTime) ?? throw new TomlTypeMismatchException(typeof(TomlLocalTime), value.GetType(), typeof(TimeSpan))).Value); } internal static Serialize GetSerializer(Type t) { if (Serializers.TryGetValue(t, out Delegate value)) { return (Serialize)value; } if (t.IsArray || (t.Namespace == "System.Collections.Generic" && t.Name == "List`1")) { Serialize serialize = GenericEnumerableSerializer(); Serializers[t] = serialize; return serialize; } return TomlCompositeSerializer.For(t); } internal static Deserialize GetDeserializer(Type t) { if (Deserializers.TryGetValue(t, out Delegate value)) { return (Deserialize)value; } if (t.IsArray) { Deserialize deserialize = ArrayDeserializerFor(t.GetElementType()); Deserializers[t] = deserialize; return deserialize; } if (t.Namespace == "System.Collections.Generic" && t.Name == "List`1") { Deserialize deserialize2 = ListDeserializerFor(t.GetGenericArguments()[0]); Deserializers[t] = deserialize2; return deserialize2; } return TomlCompositeDeserializer.For(t); } private static Serialize GenericEnumerableSerializer() { return delegate(object? o) { IEnumerable obj = (o as IEnumerable) ?? throw new Exception("How did ArraySerializer end up getting a non-array?"); TomlArray tomlArray = new TomlArray(); foreach (object item in obj) { tomlArray.Add(item); } return tomlArray; }; } private static Deserialize ArrayDeserializerFor(Type elementType) { return delegate(TomlValue value) { if (!(value is TomlArray tomlArray)) { throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), elementType.MakeArrayType()); } Array array = Array.CreateInstance(elementType, tomlArray.Count); Deserialize deserializer = GetDeserializer(elementType); for (int i = 0; i < tomlArray.ArrayValues.Count; i++) { TomlValue value2 = tomlArray.ArrayValues[i]; array.SetValue(deserializer(value2), i); } return array; }; } private static Deserialize ListDeserializerFor(Type elementType) { Type listType = typeof(List<>).MakeGenericType(elementType); MethodInfo relevantAddMethod = listType.GetMethod("Add"); return delegate(TomlValue value) { TomlArray obj = (value as TomlArray) ?? throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), listType); object obj2 = Activator.CreateInstance(listType); Deserialize deserializer = GetDeserializer(elementType); foreach (TomlValue arrayValue in obj.ArrayValues) { relevantAddMethod.Invoke(obj2, new object[1] { deserializer(arrayValue) }); } return obj2; }; } internal static void Register(Serialize? serializer, Deserialize? deserializer) { if (serializer != null) { RegisterSerializer(serializer); RegisterDictionarySerializer(serializer); } if (deserializer != null) { RegisterDeserializer(deserializer); RegisterDictionaryDeserializer(deserializer); } } internal static void Register(Type t, Serialize? serializer, Deserialize? deserializer) { if (serializer != null) { RegisterSerializer(serializer); } if (deserializer != null) { RegisterDeserializer(deserializer); } } private static void RegisterDeserializer(Deserialize deserializer) { Deserializers[typeof(T)] = new Deserialize(BoxedDeserializer); object BoxedDeserializer(TomlValue value) { T val = deserializer(value); if (val == null) { throw new Exception("TOML Deserializer returned null for type T"); } return val; } } private static void RegisterSerializer(Serialize serializer) { Serializers[typeof(T)] = new Serialize(ObjectAcceptingSerializer); TomlValue ObjectAcceptingSerializer(object value) { return serializer((T)value); } } private static void RegisterDictionarySerializer(Serialize serializer) { RegisterSerializer(delegate(Dictionary? dict) { TomlTable tomlTable = new TomlTable(); if (dict == null) { return tomlTable; } List list = dict.Keys.ToList(); List list2 = dict.Values.Select(serializer.Invoke).ToList(); for (int i = 0; i < list.Count; i++) { tomlTable.PutValue(list[i], list2[i], quote: true); } return tomlTable; }); } private static void RegisterDictionaryDeserializer(Deserialize deserializer) { RegisterDeserializer((TomlValue value) => ((value as TomlTable) ?? throw new TomlTypeMismatchException(typeof(TomlTable), value.GetType(), typeof(Dictionary))).Entries.Select, KeyValuePair>((KeyValuePair kvp) => new KeyValuePair(kvp.Key, deserializer(kvp.Value))).ToDictionary((KeyValuePair kvp) => kvp.Key, (KeyValuePair kvp) => kvp.Value)); } } } // ---- Tomlet.dll :: Tomlet.TomlUtils ---- namespace Tomlet { internal static class TomlUtils { public static string EscapeStringValue(string key) { return key.Replace("\\", "\\\\").Replace("\n", "\\n").Replace("\r", ""); } public static string AddCorrectQuotes(string key) { if (key.Contains("'") && key.Contains("\"")) { throw new InvalidTomlKeyException(key); } if (key.Contains("\"")) { return "'" + key + "'"; } return "\"" + key + "\""; } } } // ---- Tomlet.dll :: Tomlet.Models.TomlArray ---- namespace Tomlet.Models { public class TomlArray : TomlValue, IEnumerable, IEnumerable { public readonly List ArrayValues = new List(); internal bool IsLockedToBeTableArray; public override string StringValue => $"Toml Array ({ArrayValues.Count} values)"; public bool IsTableArray { get { if (!IsLockedToBeTableArray) { return ArrayValues.All((TomlValue t) => t is TomlTable); } return true; } } public bool CanBeSerializedInline { get { if (IsTableArray) { if (ArrayValues.All((TomlValue o) => o is TomlTable tomlTable && tomlTable.ShouldBeSerializedInline)) { return ArrayValues.Count <= 5; } return false; } return true; } } public bool IsSimpleArray { get { if (!IsLockedToBeTableArray) { return !ArrayValues.Any((TomlValue o) => o is TomlArray || o is TomlTable || !o.Comments.ThereAreNoComments); } return false; } } public TomlValue this[int index] => ArrayValues[index]; public int Count => ArrayValues.Count; public override string SerializedValue => SerializeInline(!IsSimpleArray); public void Add(T t) where T : new() { TomlValue item = ((t is TomlValue tomlValue) ? tomlValue : TomletMain.ValueFrom(t)); ArrayValues.Add(item); } public string SerializeInline(bool multiline) { if (!CanBeSerializedInline) { throw new Exception("Complex Toml Tables cannot be serialized into a TomlArray if the TomlArray is not a Table Array. This means that the TOML array cannot contain anything other than tables. If you are manually accessing SerializedValue on the TomlArray, you should probably be calling SerializeTableArray here. (Check the CanBeSerializedInline property and call that method if it is false)"); } StringBuilder stringBuilder = new StringBuilder("["); char value = (multiline ? '\n' : ' '); using (IEnumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { TomlValue current = enumerator.Current; stringBuilder.Append(value); if (current.Comments.PrecedingComment != null) { stringBuilder.Append(current.Comments.FormatPrecedingComment(1)).Append('\n'); } if (multiline) { stringBuilder.Append('\t'); } stringBuilder.Append(current.SerializedValue); stringBuilder.Append(','); if (current.Comments.InlineComment != null) { stringBuilder.Append(" # ").Append(current.Comments.InlineComment); } } } stringBuilder.Append(value); stringBuilder.Append(']'); return stringBuilder.ToString(); } public string SerializeTableArray(string key) { if (!IsTableArray) { throw new Exception("Cannot serialize normal arrays using this method. Use the normal TomlValue.SerializedValue property."); } StringBuilder stringBuilder = new StringBuilder(); if (base.Comments.InlineComment != null) { throw new Exception("Sorry, but inline comments aren't supported on table-arrays themselves. See https://github.com/SamboyCoding/Tomlet/blob/master/docs/InlineCommentsOnTableArrays.md for my rationale on this."); } bool flag = true; using (IEnumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { TomlValue current = enumerator.Current; if (!(current is TomlTable tomlTable)) { throw new Exception($"Toml Table-Array contains non-table entry? Value is {current}"); } if (current.Comments.PrecedingComment != null) { if (flag && base.Comments.PrecedingComment != null) { stringBuilder.Append('\n'); } stringBuilder.Append(current.Comments.FormatPrecedingComment()).Append('\n'); } flag = false; stringBuilder.Append("[[").Append(key).Append("]]"); if (current.Comments.InlineComment != null) { stringBuilder.Append(" # ").Append(current.Comments.InlineComment); } stringBuilder.Append('\n'); stringBuilder.Append(tomlTable.SerializeNonInlineTable(key, includeHeader: false)).Append('\n'); } } return stringBuilder.ToString(); } public IEnumerator GetEnumerator() { return ArrayValues.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ArrayValues.GetEnumerator(); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlBoolean ---- namespace Tomlet.Models { public class TomlBoolean : TomlValue { private bool _value; public static TomlBoolean True => new TomlBoolean(value: true); public static TomlBoolean False => new TomlBoolean(value: false); public bool Value => _value; public override string StringValue { get { if (!Value) { return bool.FalseString.ToLowerInvariant(); } return bool.TrueString.ToLowerInvariant(); } } public override string SerializedValue => StringValue; private TomlBoolean(bool value) { _value = value; } public static TomlBoolean ValueOf(bool b) { if (!b) { return False; } return True; } } } // ---- Tomlet.dll :: Tomlet.Models.TomlCommentData ---- namespace Tomlet.Models { public class TomlCommentData { private string? _inlineComment; public string? PrecedingComment { get; set; } public string? InlineComment { get { return _inlineComment; } set { if (value == null) { _inlineComment = null; return; } if (value.Contains("\n") || value.Contains("\r")) { throw new TomlNewlineInInlineCommentException(); } _inlineComment = value; } } public bool ThereAreNoComments { get { if (InlineComment == null) { return PrecedingComment == null; } return false; } } internal string FormatPrecedingComment(int indentCount = 0) { if (PrecedingComment == null) { throw new Exception("Preceding comment is null"); } StringBuilder stringBuilder = new StringBuilder(); string[] array = PrecedingComment.Split(new char[1] { '\n' }); bool flag = true; string[] array2 = array; foreach (string value in array2) { if (!flag) { stringBuilder.Append('\n'); } flag = false; string value2 = new string('\t', indentCount); stringBuilder.Append(value2).Append("# ").Append(value); } return stringBuilder.ToString(); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlDocument ---- namespace Tomlet.Models { public class TomlDocument : TomlTable { public string? TrailingComment { get; set; } public override string SerializedValue => SerializeDocument(); public override string StringValue => $"Toml root document ({Entries.Count} entries)"; public static TomlDocument CreateEmpty() { return new TomlDocument(); } internal TomlDocument() { } internal TomlDocument(TomlTable from) { foreach (string key in from.Keys) { PutValue(key, from.GetValue(key)); } } private string SerializeDocument() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(SerializeNonInlineTable(null, includeHeader: false)); if (TrailingComment != null) { TomlCommentData tomlCommentData = new TomlCommentData { PrecedingComment = TrailingComment }; stringBuilder.Append('\n'); stringBuilder.Append(tomlCommentData.FormatPrecedingComment()); } return stringBuilder.ToString(); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlDouble ---- namespace Tomlet.Models { public class TomlDouble : TomlValue { private double _value; public bool HasDecimal => Value != (double)(int)Value; public double Value => _value; public bool IsNaN => double.IsNaN(Value); public bool IsInfinity => double.IsInfinity(Value); public override string StringValue { get { if (this != null) { if (IsInfinity) { return double.IsPositiveInfinity(Value) ? "inf" : "-inf"; } if (IsNaN) { return "nan"; } if (HasDecimal) { return Value.ToString(CultureInfo.InvariantCulture); } } return $"{Value:F1}"; } } public override string SerializedValue => StringValue; public TomlDouble(double value) { _value = value; } internal static TomlDouble? Parse(string valueInToml) { double? doubleValue = TomlNumberUtils.GetDoubleValue(valueInToml); if (!doubleValue.HasValue) { return null; } return new TomlDouble(doubleValue.Value); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlLocalDate ---- namespace Tomlet.Models { public class TomlLocalDate : TomlValue, ITomlValueWithDateTime { private readonly DateTime _value; public DateTime Value => _value; public override string StringValue => XmlConvert.ToString(Value, XmlDateTimeSerializationMode.Unspecified); public override string SerializedValue => StringValue; public TomlLocalDate(DateTime value) { _value = value; } public static TomlLocalDate? Parse(string input) { if (!DateTime.TryParse(input, out var result)) { return null; } return new TomlLocalDate(result); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlLocalDateTime ---- namespace Tomlet.Models { public class TomlLocalDateTime : TomlValue, ITomlValueWithDateTime { private readonly DateTime _value; public DateTime Value => _value; public override string StringValue => XmlConvert.ToString(Value, XmlDateTimeSerializationMode.Unspecified); public override string SerializedValue => StringValue; public TomlLocalDateTime(DateTime value) { _value = value; } public static TomlLocalDateTime? Parse(string input) { if (!DateTime.TryParse(input, out var result)) { return null; } return new TomlLocalDateTime(result); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlLocalTime ---- namespace Tomlet.Models { public class TomlLocalTime : TomlValue { private readonly TimeSpan _value; public TimeSpan Value => _value; public override string StringValue => Value.ToString(); public override string SerializedValue => StringValue; public TomlLocalTime(TimeSpan value) { _value = value; } public static TomlLocalTime? Parse(string input) { if (!TimeSpan.TryParse(input, out var result)) { return null; } return new TomlLocalTime(result); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlLong ---- namespace Tomlet.Models { public class TomlLong : TomlValue { private long _value; public long Value => _value; public override string StringValue => Value.ToString(); public override string SerializedValue => StringValue; public TomlLong(long value) { _value = value; } internal static TomlLong? Parse(string valueInToml) { long? longValue = TomlNumberUtils.GetLongValue(valueInToml); if (!longValue.HasValue) { return null; } return new TomlLong(longValue.Value); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlOffsetDateTime ---- namespace Tomlet.Models { public class TomlOffsetDateTime : TomlValue { private readonly DateTimeOffset _value; public DateTimeOffset Value => _value; public override string StringValue => Value.ToString("O"); public override string SerializedValue => StringValue; public TomlOffsetDateTime(DateTimeOffset value) { _value = value; } public static TomlOffsetDateTime? Parse(string input) { if (!DateTimeOffset.TryParse(input, out var result)) { return null; } return new TomlOffsetDateTime(result); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlString ---- namespace Tomlet.Models { public class TomlString : TomlValue { private readonly string _value; public static TomlString Empty => new TomlString(""); public string Value => _value; public override string StringValue => Value; public override string SerializedValue { get { if (Value.Contains("'") && !Value.Contains("\"")) { return "\"" + TomlUtils.EscapeStringValue(Value) + "\""; } if (Value.Contains("\"") && !Value.Contains("'") && !Value.Contains("\n")) { return "'" + Value + "'"; } if (Value.Contains("\"") && !Value.Contains("'")) { return "'''\n" + Value + "'''"; } return "\"" + TomlUtils.EscapeStringValue(Value) + "\""; } } public TomlString(string? value) { _value = value ?? throw new ArgumentNullException("value", "TomlString's value cannot be null"); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlTable ---- namespace Tomlet.Models { public class TomlTable : TomlValue { public readonly Dictionary Entries = new Dictionary(); internal bool Locked; internal bool Defined; public bool ForceNoInline { get; set; } public override string StringValue => $"Table ({Entries.Count} entries)"; public HashSet Keys => new HashSet(Entries.Keys); public bool ShouldBeSerializedInline { get { if (!ForceNoInline && Entries.Count < 4) { return Entries.All>((KeyValuePair e) => !e.Key.Contains(" ") && e.Value.Comments.ThereAreNoComments && ((!(e.Value is TomlArray tomlArray)) ? (!(e.Value is TomlTable)) : tomlArray.IsSimpleArray)); } return false; } } public override string SerializedValue { get { if (!ShouldBeSerializedInline) { throw new Exception("Cannot use SerializeValue to serialize non-inline tables. Use SerializeNonInlineTable(keyName)."); } StringBuilder stringBuilder = new StringBuilder("{ "); stringBuilder.Append(string.Join(", ", Entries.Select, string>((KeyValuePair o) => o.Key + " = " + o.Value.SerializedValue).ToArray())); stringBuilder.Append(" }"); return stringBuilder.ToString(); } } public string SerializeNonInlineTable(string? keyName, bool includeHeader = true) { StringBuilder stringBuilder = new StringBuilder(); if (includeHeader) { stringBuilder.Append('[').Append(keyName).Append("]"); if (base.Comments.InlineComment != null) { stringBuilder.Append(" # ").Append(base.Comments.InlineComment); } stringBuilder.Append('\n'); } string one; TomlValue two; foreach (KeyValuePair entry in Entries) { Extensions.Deconstruct(entry, out one, out two); string subKey = one; TomlValue tomlValue = two; if (tomlValue is TomlTable tomlTable) { if (!tomlTable.ShouldBeSerializedInline) { goto IL_00a4; } } else if (tomlValue is TomlArray { CanBeSerializedInline: false }) { goto IL_00a4; } bool flag = false; goto IL_00ac; IL_00a4: flag = true; goto IL_00ac; IL_00ac: if (!flag) { WriteValueToStringBuilder(keyName, subKey, stringBuilder); } } foreach (KeyValuePair entry2 in Entries) { Extensions.Deconstruct(entry2, out one, out two); string subKey2 = one; if (two is TomlTable { ShouldBeSerializedInline: false }) { WriteValueToStringBuilder(keyName, subKey2, stringBuilder); } } foreach (KeyValuePair entry3 in Entries) { Extensions.Deconstruct(entry3, out one, out two); string subKey3 = one; if (two is TomlArray { CanBeSerializedInline: false }) { WriteValueToStringBuilder(keyName, subKey3, stringBuilder); } } return stringBuilder.ToString(); } private void WriteValueToStringBuilder(string? keyName, string subKey, StringBuilder builder) { TomlValue value = GetValue(subKey); subKey = EscapeKeyIfNeeded(subKey); if (keyName != null) { keyName = EscapeKeyIfNeeded(keyName); } string text = ((keyName == null) ? subKey : (keyName + "." + subKey)); if (value.Comments.PrecedingComment != null) { builder.Append(value.Comments.FormatPrecedingComment()).Append('\n'); } if (value is TomlArray tomlArray) { if (!tomlArray.CanBeSerializedInline) { builder.Append(tomlArray.SerializeTableArray(text)); return; } TomlArray tomlArray2 = tomlArray; builder.Append(subKey).Append(" = ").Append(tomlArray2.SerializedValue); } else if (value is TomlTable tomlTable) { if (!tomlTable.ShouldBeSerializedInline) { TomlTable tomlTable2 = tomlTable; builder.Append(tomlTable2.SerializeNonInlineTable(text)).Append('\n'); return; } builder.Append(subKey).Append(" = ").Append(tomlTable.SerializedValue); } else { builder.Append(subKey).Append(" = ").Append(value.SerializedValue); } if (value.Comments.InlineComment != null) { builder.Append(" # ").Append(value.Comments.InlineComment); } builder.Append('\n'); } private string EscapeKeyIfNeeded(string key) { bool flag = false; if (key.StartsWith("\"") && key.EndsWith("\"") && key.Count((char c) => c == '"') == 2) { return key; } if (key.StartsWith("'") && key.EndsWith("'") && key.Count((char c) => c == '\'') == 2) { return key; } if (key.Contains("\"") || key.Contains("'")) { key = TomlUtils.AddCorrectQuotes(key); flag = true; } string text = TomlUtils.EscapeStringValue(key); if (text.Contains(" ") || (text.Contains("\\") && !flag)) { text = TomlUtils.AddCorrectQuotes(text); } return text; } internal void ParserPutValue(string key, TomlValue value, int lineNumber) { if (Locked) { throw new TomlTableLockedException(lineNumber, key); } InternalPutValue(key, value, lineNumber, callParserForm: true); } public void PutValue(string key, TomlValue value, bool quote = false) { if (key == null) { throw new ArgumentNullException("key"); } if (value == null) { throw new ArgumentNullException("value"); } if (quote) { key = TomlUtils.AddCorrectQuotes(key); } InternalPutValue(key, value, null, callParserForm: false); } public void Put(string key, T t, bool quote = false) { if (t is TomlValue value) { PutValue(key, value, quote); } else { PutValue(key, TomletMain.ValueFrom(t), quote); } } public string DeQuoteKey(string key) { if ((key.StartsWith("\"") && key.EndsWith("\"")) || (key.StartsWith("'") && key.EndsWith("'"))) { return key.Substring(1, key.Length - 2); } return key; } private void InternalPutValue(string key, TomlValue value, int? lineNumber, bool callParserForm) { key = key.Trim(); TomlKeyUtils.GetTopLevelAndSubKeys(key, out string ourKeyName, out string restOfKey); if (!string.IsNullOrEmpty(restOfKey)) { if (!Entries.TryGetValue(DeQuoteKey(ourKeyName), out TomlValue value2)) { TomlTable tomlTable = new TomlTable(); if (callParserForm) { ParserPutValue(ourKeyName, tomlTable, lineNumber.Value); } else { PutValue(ourKeyName, tomlTable); } if (callParserForm) { tomlTable.ParserPutValue(restOfKey, value, lineNumber.Value); } else { tomlTable.PutValue(restOfKey, value); } return; } if (!(value2 is TomlTable tomlTable2)) { if (lineNumber.HasValue) { throw new TomlDottedKeyParserException(lineNumber.Value, ourKeyName); } throw new TomlDottedKeyException(ourKeyName); } if (callParserForm) { tomlTable2.ParserPutValue(restOfKey, value, lineNumber.Value); } else { tomlTable2.PutValue(restOfKey, value); } } else { key = DeQuoteKey(key); if (Entries.ContainsKey(key) && lineNumber.HasValue) { throw new TomlKeyRedefinitionException(lineNumber.Value, key); } Entries[key] = value; } } public bool ContainsKey(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlKeyUtils.GetTopLevelAndSubKeys(key, out string ourKeyName, out string restOfKey); if (string.IsNullOrEmpty(restOfKey)) { return Entries.ContainsKey(DeQuoteKey(key)); } if (!Entries.TryGetValue(ourKeyName, out TomlValue value)) { return false; } if (value is TomlTable tomlTable) { return tomlTable.ContainsKey(restOfKey); } throw new TomlContainsDottedKeyNonTableException(key); } public TomlValue GetValue(string key) { if (key == null) { throw new ArgumentNullException("key"); } if (!ContainsKey(key)) { throw new TomlNoSuchValueException(key); } TomlKeyUtils.GetTopLevelAndSubKeys(key, out string ourKeyName, out string restOfKey); if (string.IsNullOrEmpty(restOfKey)) { return Entries[DeQuoteKey(key)]; } if (!Entries.TryGetValue(ourKeyName, out TomlValue value)) { throw new TomlNoSuchValueException(key); } if (value is TomlTable tomlTable) { return tomlTable.GetValue(restOfKey); } throw new Exception("Tomlet Internal bug - existing key is not a table in TomlTable GetValue, but we didn't throw in ContainsKey?"); } public string GetString(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key)); return ((value as TomlString) ?? throw new TomlTypeMismatchException(typeof(TomlString), value.GetType(), typeof(string))).Value; } public int GetInteger(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key)); return (int)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(int))).Value; } public long GetLong(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key)); return ((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(int))).Value; } public float GetFloat(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key)); return (float)((value as TomlDouble) ?? throw new TomlTypeMismatchException(typeof(TomlDouble), value.GetType(), typeof(float))).Value; } public bool GetBoolean(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key)); return ((value as TomlBoolean) ?? throw new TomlTypeMismatchException(typeof(TomlBoolean), value.GetType(), typeof(bool))).Value; } public TomlArray GetArray(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key)); return (value as TomlArray) ?? throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), typeof(TomlArray)); } public TomlTable GetSubTable(string key) { if (key == null) { throw new ArgumentNullException("key"); } TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key)); return (value as TomlTable) ?? throw new TomlTypeMismatchException(typeof(TomlTable), value.GetType(), typeof(TomlTable)); } } } // ---- Tomlet.dll :: Tomlet.Models.TomlValue ---- namespace Tomlet.Models { public abstract class TomlValue { public TomlCommentData Comments { get; } = new TomlCommentData(); public abstract string StringValue { get; } public abstract string SerializedValue { get; } } } // ---- Tomlet.dll :: Tomlet.Models.ITomlValueWithDateTime ---- namespace Tomlet.Models { public interface ITomlValueWithDateTime { DateTime Value { get; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.InvalidTomlDateTimeException ---- namespace Tomlet.Exceptions { public class InvalidTomlDateTimeException : TomlExceptionWithLine { private readonly string _inputString; public override string Message => $"Found an invalid TOML date/time string '{_inputString}' on line {LineNumber}"; public InvalidTomlDateTimeException(int lineNumber, string inputString) : base(lineNumber) { _inputString = inputString; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.InvalidTomlEscapeException ---- namespace Tomlet.Exceptions { public class InvalidTomlEscapeException : TomlExceptionWithLine { private readonly string _escapeSequence; public override string Message => $"Found an invalid escape sequence '\\{_escapeSequence}' on line {LineNumber}"; public InvalidTomlEscapeException(int lineNumber, string escapeSequence) : base(lineNumber) { _escapeSequence = escapeSequence; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.InvalidTomlInlineTableException ---- namespace Tomlet.Exceptions { public class InvalidTomlInlineTableException : TomlExceptionWithLine { public override string Message => $"Found an invalid inline TOML table on line {LineNumber}. See further down for cause."; public InvalidTomlInlineTableException(int lineNumber, TomlException cause) : base(lineNumber, cause) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.InvalidTomlKeyException ---- namespace Tomlet.Exceptions { public class InvalidTomlKeyException : TomlException { private readonly string _key; public override string Message => "The string |" + _key + "| (between the two bars) contains at least one of both a double quote and a single quote, so it cannot be used for a TOML key."; public InvalidTomlKeyException(string key) { _key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.InvalidTomlNumberException ---- namespace Tomlet.Exceptions { public class InvalidTomlNumberException : TomlExceptionWithLine { private readonly string _input; public override string Message => $"While reading input line {LineNumber}, found an invalid number literal '{_input}'"; public InvalidTomlNumberException(int lineNumber, string input) : base(lineNumber) { _input = input; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.MissingIntermediateInTomlTableArraySpecException ---- namespace Tomlet.Exceptions { public class MissingIntermediateInTomlTableArraySpecException : TomlExceptionWithLine { private readonly string _missing; public override string Message => $"Missing intermediate definition for {_missing} in table-array specification on line {LineNumber}. This is undefined behavior, and I chose to define it as an error."; public MissingIntermediateInTomlTableArraySpecException(int lineNumber, string missing) : base(lineNumber) { _missing = missing; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.NewLineInTomlInlineTableException ---- namespace Tomlet.Exceptions { public class NewLineInTomlInlineTableException : TomlExceptionWithLine { public override string Message => "Found a new-line character within a TOML inline table. This is not allowed."; public NewLineInTomlInlineTableException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.NoTomlKeyException ---- namespace Tomlet.Exceptions { public class NoTomlKeyException : TomlExceptionWithLine { public override string Message => $"Expected a TOML key on line {LineNumber}, but found an equals sign ('=')."; public NoTomlKeyException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TimeOffsetOnTomlDateOrTimeException ---- namespace Tomlet.Exceptions { public class TimeOffsetOnTomlDateOrTimeException : TomlExceptionWithLine { private readonly string _tzString; public override string Message => $"Found a time offset string {_tzString} in a partial datetime on line {LineNumber}. This is not allowed - either specify both the date and the time, or remove the offset specifier."; public TimeOffsetOnTomlDateOrTimeException(int lineNumber, string tzString) : base(lineNumber) { _tzString = tzString; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlArraySyntaxException ---- namespace Tomlet.Exceptions { public class TomlArraySyntaxException : TomlExceptionWithLine { private readonly char _charFound; public override string Message => $"Expecting ',' or ']' after value in array on line {LineNumber}, found '{_charFound}'"; public TomlArraySyntaxException(int lineNumber, char charFound) : base(lineNumber) { _charFound = charFound; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlContainsDottedKeyNonTableException ---- namespace Tomlet.Exceptions { public class TomlContainsDottedKeyNonTableException : TomlException { internal readonly string Key; public override string Message => "A call was made on a TOML table which attempted to access a sub-key of " + Key + ", but the value it refers to is not a table"; public TomlContainsDottedKeyNonTableException(string key) { Key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlDateTimeMissingSeparatorException ---- namespace Tomlet.Exceptions { public class TomlDateTimeMissingSeparatorException : TomlExceptionWithLine { public override string Message => $"Found a date-time on line {LineNumber} which is missing a separator (T, t, or a space) between the date and time."; public TomlDateTimeMissingSeparatorException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlDateTimeUnnecessarySeparatorException ---- namespace Tomlet.Exceptions { public class TomlDateTimeUnnecessarySeparatorException : TomlExceptionWithLine { public override string Message => $"Found an unnecessary date-time separator (T, t, or a space) in a date or time on line {LineNumber}"; public TomlDateTimeUnnecessarySeparatorException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlDottedKeyException ---- namespace Tomlet.Exceptions { public class TomlDottedKeyException : TomlException { private readonly string _key; public override string Message => "Tried to redefine key " + _key + " as a table (by way of a dotted key) when it's already defined as not being a table."; public TomlDottedKeyException(string key) { _key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlDottedKeyParserException ---- namespace Tomlet.Exceptions { public class TomlDottedKeyParserException : TomlExceptionWithLine { private readonly string _key; public override string Message => $"Tried to redefine key {_key} as a table (by way of a dotted key on line {LineNumber}) when it's already defined as not being a table."; public TomlDottedKeyParserException(int lineNumber, string key) : base(lineNumber) { _key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlDoubleDottedKeyException ---- namespace Tomlet.Exceptions { public class TomlDoubleDottedKeyException : TomlExceptionWithLine { public override string Message => "Found two consecutive dots, or a leading dot, in a key on line " + LineNumber; public TomlDoubleDottedKeyException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlEndOfFileException ---- namespace Tomlet.Exceptions { public class TomlEndOfFileException : TomlExceptionWithLine { public override string Message => $"Found unexpected EOF on line {LineNumber} when parsing TOML file"; public TomlEndOfFileException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlEnumParseException ---- namespace Tomlet.Exceptions { public class TomlEnumParseException : TomlException { private string _valueName; private Type _enumType; public override string Message => $"Could not find enum value by name \"{_valueName}\" in enum class {_enumType} while deserializing."; public TomlEnumParseException(string valueName, Type enumType) { _valueName = valueName; _enumType = enumType; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlException ---- namespace Tomlet.Exceptions { public abstract class TomlException : Exception { protected TomlException() { } protected TomlException(Exception cause) : base("", cause) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlExceptionWithLine ---- namespace Tomlet.Exceptions { public abstract class TomlExceptionWithLine : TomlException { protected int LineNumber; protected TomlExceptionWithLine(int lineNumber) { LineNumber = lineNumber; } protected TomlExceptionWithLine(int lineNumber, Exception cause) : base(cause) { LineNumber = lineNumber; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlFieldTypeMismatchException ---- namespace Tomlet.Exceptions { public class TomlFieldTypeMismatchException : TomlTypeMismatchException { private readonly Type _typeBeingInstantiated; private readonly FieldInfo _fieldBeingDeserialized; public override string Message => $"While deserializing an object of type {_typeBeingInstantiated}, found field {_fieldBeingDeserialized.Name} expecting a type of {ExpectedTypeName}, but value in TOML was of type {ActualTypeName}"; public TomlFieldTypeMismatchException(Type typeBeingInstantiated, FieldInfo fieldBeingDeserialized, TomlTypeMismatchException cause) : base(cause.ExpectedType, cause.ActualType, fieldBeingDeserialized.FieldType) { _typeBeingInstantiated = typeBeingInstantiated; _fieldBeingDeserialized = fieldBeingDeserialized; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlInlineTableSeparatorException ---- namespace Tomlet.Exceptions { public class TomlInlineTableSeparatorException : TomlExceptionWithLine { private readonly char _found; public override string Message => $"Expected '}}' or ',' after key-value pair in TOML inline table, found '{_found}'"; public TomlInlineTableSeparatorException(int lineNumber, char found) : base(lineNumber) { _found = found; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlInstantiationException ---- namespace Tomlet.Exceptions { public class TomlInstantiationException : TomlException { private readonly Type _type; public override string Message => "Could not find a no-argument constructor for type " + _type.FullName; public TomlInstantiationException(Type type) { _type = type; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlInternalException ---- namespace Tomlet.Exceptions { public class TomlInternalException : TomlExceptionWithLine { public override string Message => $"An internal exception occured while parsing line {LineNumber} of the TOML document"; public TomlInternalException(int lineNumber, Exception cause) : base(lineNumber, cause) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlInvalidValueException ---- namespace Tomlet.Exceptions { public class TomlInvalidValueException : TomlExceptionWithLine { private readonly char _found; public override string Message => $"Expected the start of a number, string literal, boolean, array, or table on line {LineNumber}, found '{_found}'"; public TomlInvalidValueException(int lineNumber, char found) : base(lineNumber) { _found = found; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlKeyRedefinitionException ---- namespace Tomlet.Exceptions { public class TomlKeyRedefinitionException : TomlExceptionWithLine { private readonly string _key; public override string Message => $"TOML document attempts to re-define key '{_key}' on line {LineNumber}"; public TomlKeyRedefinitionException(int lineNumber, string key) : base(lineNumber) { _key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlMissingEqualsException ---- namespace Tomlet.Exceptions { public class TomlMissingEqualsException : TomlExceptionWithLine { private readonly char _found; public override string Message => $"Expecting an equals sign ('=') on line {LineNumber}, but found '{_found}'"; public TomlMissingEqualsException(int lineNumber, char found) : base(lineNumber) { _found = found; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlMissingNewlineException ---- namespace Tomlet.Exceptions { public class TomlMissingNewlineException : TomlExceptionWithLine { private readonly char _found; public override string Message => $"Expecting a newline character at the end of a statement on line {LineNumber}, but found an unexpected '{_found}'"; public TomlMissingNewlineException(int lineNumber, char found) : base(lineNumber) { _found = found; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlNewlineInInlineCommentException ---- namespace Tomlet.Exceptions { public class TomlNewlineInInlineCommentException : TomlException { public override string Message => "An attempt was made to set an inline comment which contains a newline. This obviously cannot be done, as inline comments must fit on one line."; } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlNonTableArrayUsedAsTableArrayException ---- namespace Tomlet.Exceptions { public class TomlNonTableArrayUsedAsTableArrayException : TomlExceptionWithLine { private readonly string _arrayName; public override string Message => $"{_arrayName} is used as a table-array on line {LineNumber} when it has previously been defined as a static array. This is not allowed."; public TomlNonTableArrayUsedAsTableArrayException(int lineNumber, string arrayName) : base(lineNumber) { _arrayName = arrayName; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlNoSuchValueException ---- namespace Tomlet.Exceptions { public class TomlNoSuchValueException : TomlException { private readonly string _key; public override string Message => "Attempted to get the value for key " + _key + " but no value is associated with that key"; public TomlNoSuchValueException(string key) { _key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlPrimitiveToDocumentException ---- namespace Tomlet.Exceptions { public class TomlPrimitiveToDocumentException : TomlException { private Type primitiveType; public override string Message => "Tried to create a TOML document from a primitive value of type " + primitiveType.Name + ". Documents can only be created from objects."; public TomlPrimitiveToDocumentException(Type primitiveType) { this.primitiveType = primitiveType; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlStringException ---- namespace Tomlet.Exceptions { public class TomlStringException : TomlExceptionWithLine { public override string Message => $"Found an invalid TOML string on line {LineNumber}"; public TomlStringException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlTableArrayAlreadyExistsAsNonArrayException ---- namespace Tomlet.Exceptions { public class TomlTableArrayAlreadyExistsAsNonArrayException : TomlExceptionWithLine { private readonly string _arrayName; public override string Message => $"{_arrayName} is defined as a table-array (double-bracketed section) on line {LineNumber} but it has previously been used as a non-array type."; public TomlTableArrayAlreadyExistsAsNonArrayException(int lineNumber, string arrayName) : base(lineNumber) { _arrayName = arrayName; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlTableLockedException ---- namespace Tomlet.Exceptions { public class TomlTableLockedException : TomlExceptionWithLine { private readonly string _key; public override string Message => $"TOML table is locked (e.g. defined inline), cannot add or update key {_key} to it on line {LineNumber}"; public TomlTableLockedException(int lineNumber, string key) : base(lineNumber) { _key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlTableRedefinitionException ---- namespace Tomlet.Exceptions { public class TomlTableRedefinitionException : TomlExceptionWithLine { private readonly string _key; public override string Message => $"TOML document attempts to re-define table '{_key}' on line {LineNumber}"; public TomlTableRedefinitionException(int lineNumber, string key) : base(lineNumber) { _key = key; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlTripleQuotedKeyException ---- namespace Tomlet.Exceptions { public class TomlTripleQuotedKeyException : TomlExceptionWithLine { public override string Message => $"Found a triple-quoted key on line {LineNumber}. This is not allowed."; public TomlTripleQuotedKeyException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlTypeMismatchException ---- namespace Tomlet.Exceptions { public class TomlTypeMismatchException : TomlException { protected readonly string ExpectedTypeName; protected readonly string ActualTypeName; protected internal readonly Type ExpectedType; protected internal readonly Type ActualType; private readonly Type _context; public override string Message => $"While trying to convert to type {_context}, a TOML value of type {ExpectedTypeName} was required but a value of type {ActualTypeName} was found"; public TomlTypeMismatchException(Type expected, Type actual, Type context) { ExpectedTypeName = (typeof(TomlValue).IsAssignableFrom(expected) ? expected.Name.Replace("Toml", "") : expected.Name); ActualTypeName = (typeof(TomlValue).IsAssignableFrom(actual) ? actual.Name.Replace("Toml", "") : actual.Name); ExpectedType = expected; ActualType = actual; _context = context; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlUnescapedUnicodeControlCharException ---- namespace Tomlet.Exceptions { public class TomlUnescapedUnicodeControlCharException : TomlExceptionWithLine { private readonly int _theChar; public override string Message => $"Found an unescaped unicode control character U+{_theChar:0000} on line {LineNumber}. Control character other than tab (U+0009) are not allowed in TOML unless they are escaped."; public TomlUnescapedUnicodeControlCharException(int lineNumber, int theChar) : base(lineNumber) { _theChar = theChar; } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TomlWhitespaceInKeyException ---- namespace Tomlet.Exceptions { public class TomlWhitespaceInKeyException : TomlExceptionWithLine { public override string Message => "Found whitespace in an unquoted TOML key at line " + LineNumber; public TomlWhitespaceInKeyException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TripleQuoteInTomlMultilineLiteralException ---- namespace Tomlet.Exceptions { public class TripleQuoteInTomlMultilineLiteralException : TomlExceptionWithLine { public override string Message => $"Found a triple-single-quote (''') inside a multiline string literal on line {LineNumber}. This is not allowed."; public TripleQuoteInTomlMultilineLiteralException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.TripleQuoteInTomlMultilineSimpleStringException ---- namespace Tomlet.Exceptions { public class TripleQuoteInTomlMultilineSimpleStringException : TomlExceptionWithLine { public override string Message => $"Found a triple-double-quote (\"\"\") inside a multiline simple string on line {LineNumber}. This is not allowed."; public TripleQuoteInTomlMultilineSimpleStringException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.UnterminatedTomlKeyException ---- namespace Tomlet.Exceptions { public class UnterminatedTomlKeyException : TomlExceptionWithLine { public override string Message => $"Found an unterminated quoted key on line {LineNumber}"; public UnterminatedTomlKeyException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.UnterminatedTomlStringException ---- namespace Tomlet.Exceptions { public class UnterminatedTomlStringException : TomlExceptionWithLine { public override string Message => $"Found an unterminated TOML string on line {LineNumber}"; public UnterminatedTomlStringException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.UnterminatedTomlTableArrayException ---- namespace Tomlet.Exceptions { public class UnterminatedTomlTableArrayException : TomlExceptionWithLine { public override string Message => $"Found an unterminated table-array (expecting two ]s to close it) on line {LineNumber}"; public UnterminatedTomlTableArrayException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Exceptions.UnterminatedTomlTableNameException ---- namespace Tomlet.Exceptions { public class UnterminatedTomlTableNameException : TomlExceptionWithLine { public override string Message => $"Found an unterminated table name on line {LineNumber}"; public UnterminatedTomlTableNameException(int lineNumber) : base(lineNumber) { } } } // ---- Tomlet.dll :: Tomlet.Attributes.NoCoverageAttribute ---- namespace Tomlet.Attributes { internal class NoCoverageAttribute : Attribute { } } // ---- Tomlet.dll :: Tomlet.Attributes.TomlDoNotInlineObjectAttribute ---- namespace Tomlet.Attributes { [AttributeUsage(AttributeTargets.Class)] public class TomlDoNotInlineObjectAttribute : Attribute { } } // ---- Tomlet.dll :: Tomlet.Attributes.TomlInlineCommentAttribute ---- namespace Tomlet.Attributes { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class TomlInlineCommentAttribute : Attribute { internal string Comment { get; } public TomlInlineCommentAttribute(string comment) { Comment = comment; } } } // ---- Tomlet.dll :: Tomlet.Attributes.TomlPrecedingCommentAttribute ---- namespace Tomlet.Attributes { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class TomlPrecedingCommentAttribute : Attribute { internal string Comment { get; } public TomlPrecedingCommentAttribute(string comment) { Comment = comment; } } } // ---- Tomlet.dll :: Tomlet.Attributes.TomlPropertyAttribute ---- namespace Tomlet.Attributes { [AttributeUsage(AttributeTargets.Property)] public class TomlPropertyAttribute : Attribute { private readonly string _mapFrom; public TomlPropertyAttribute(string mapFrom) { _mapFrom = mapFrom; } public string GetMappedString() { return _mapFrom; } } } // ---- UniverseLib.Mono.dll :: MonoExtensions ---- public static class MonoExtensions { private static PropertyInfo p_childControlHeight = AccessTools.Property(typeof(HorizontalOrVerticalLayoutGroup), "childControlHeight"); private static PropertyInfo p_childControlWidth = AccessTools.Property(typeof(HorizontalOrVerticalLayoutGroup), "childControlWidth"); public static void AddListener(this UnityEvent _event, Action listener) { _event.AddListener(listener.Invoke); } public static void AddListener(this UnityEvent _event, Action listener) { _event.AddListener(listener.Invoke); } public static void RemoveListener(this UnityEvent _event, Action listener) { _event.RemoveListener(listener.Invoke); } public static void RemoveListener(this UnityEvent _event, Action listener) { _event.RemoveListener(listener.Invoke); } public static void Clear(this StringBuilder sb) { sb.Remove(0, sb.Length); } public static void SetChildControlHeight(this HorizontalOrVerticalLayoutGroup group, bool value) { p_childControlHeight?.SetValue(group, value, null); } public static void SetChildControlWidth(this HorizontalOrVerticalLayoutGroup group, bool value) { p_childControlWidth?.SetValue(group, value, null); } } // ---- UniverseLib.Mono.dll :: UniverseLib.ReflectionExtensions ---- namespace UniverseLib { public static class ReflectionExtensions { public static Type GetActualType(this object obj) { return ReflectionUtility.Instance.Internal_GetActualType(obj); } public static object TryCast(this object obj) { return ReflectionUtility.Instance.Internal_TryCast(obj, ReflectionUtility.Instance.Internal_GetActualType(obj)); } public static object TryCast(this object obj, Type castTo) { return ReflectionUtility.Instance.Internal_TryCast(obj, castTo); } public static T TryCast(this object obj) { try { return (T)ReflectionUtility.Instance.Internal_TryCast(obj, typeof(T)); } catch { return default(T); } } [Obsolete("This method is no longer necessary, just use Assembly.GetTypes().", false)] public static IEnumerable TryGetTypes(this Assembly asm) { return asm.GetTypes(); } public static bool ReferenceEqual(this object objA, object objB) { if (objA == objB) { return true; } if (objA is UnityEngine.Object obj && objB is UnityEngine.Object obj2 && (bool)obj && (bool)obj2 && obj.m_CachedPtr == obj2.m_CachedPtr) { return true; } return false; } public static string ReflectionExToString(this Exception e, bool innerMost = true) { if (e == null) { return "The exception was null."; } if (innerMost) { e = e.GetInnerMostException(); } return $"{e.GetType()}: {e.Message}"; } public static Exception GetInnerMostException(this Exception e) { while (e != null && e.InnerException != null) { e = e.InnerException; } return e; } } } // ---- UniverseLib.Mono.dll :: UniverseLib.ReflectionPatches ---- namespace UniverseLib { internal static class ReflectionPatches { internal static void Init() { Universe.Patch(typeof(Assembly), "GetTypes", MethodType.Normal, new Type[0], null, null, AccessTools.Method(typeof(ReflectionPatches), "Finalizer_Assembly_GetTypes")); } public static Exception Finalizer_Assembly_GetTypes(Assembly __instance, Exception __exception, ref Type[] __result) { if (__exception != null) { if (__exception is ReflectionTypeLoadException e) { __result = ReflectionUtility.TryExtractTypesFromException(e); } else { try { __result = __instance.GetExportedTypes(); } catch (ReflectionTypeLoadException e2) { __result = ReflectionUtility.TryExtractTypesFromException(e2); } catch { __result = ArgumentUtility.EmptyTypes; } } } return null; } } } // ---- UniverseLib.Mono.dll :: UniverseLib.ReflectionUtility ---- namespace UniverseLib { public class ReflectionUtility { public static bool Initializing; public const BindingFlags FLAGS = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; public static readonly SortedDictionary AllTypes = new SortedDictionary(StringComparer.OrdinalIgnoreCase); public static readonly List AllNamespaces = new List(); private static readonly HashSet uniqueNamespaces = new HashSet(); private static string[] allTypeNamesArray; private static readonly Dictionary shorthandToType = new Dictionary { { "object", typeof(object) }, { "string", typeof(string) }, { "bool", typeof(bool) }, { "byte", typeof(byte) }, { "sbyte", typeof(sbyte) }, { "char", typeof(char) }, { "decimal", typeof(decimal) }, { "double", typeof(double) }, { "float", typeof(float) }, { "int", typeof(int) }, { "uint", typeof(uint) }, { "long", typeof(long) }, { "ulong", typeof(ulong) }, { "short", typeof(short) }, { "ushort", typeof(ushort) }, { "void", typeof(void) } }; internal static readonly Dictionary baseTypes = new Dictionary(); internal static ReflectionUtility Instance { get; private set; } public static event Action OnTypeLoaded; internal static void Init() { ReflectionPatches.Init(); Instance = new ReflectionUtility(); Instance.Initialize(); } protected virtual void Initialize() { SetupTypeCache(); Initializing = false; } public static string[] GetTypeNameArray() { if (allTypeNamesArray == null || allTypeNamesArray.Length != AllTypes.Count) { allTypeNamesArray = new string[AllTypes.Count]; int num = 0; foreach (string key in AllTypes.Keys) { allTypeNamesArray[num] = key; num++; } } return allTypeNamesArray; } private static void SetupTypeCache() { if (Universe.Context == RuntimeContext.Mono) { ForceLoadManagedAssemblies(); } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly asm in assemblies) { CacheTypes(asm); } AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded; } private static void AssemblyLoaded(object sender, AssemblyLoadEventArgs args) { if ((object)args.LoadedAssembly != null && !(args.LoadedAssembly.GetName().Name == "completions")) { CacheTypes(args.LoadedAssembly); } } private static void ForceLoadManagedAssemblies() { string path = Path.Combine(Application.dataPath, "Managed"); if (!Directory.Exists(path)) { return; } string[] files = Directory.GetFiles(path, "*.dll"); foreach (string path2 in files) { try { Assembly assembly = Assembly.LoadFile(path2); assembly.GetTypes(); } catch { } } } private static void CacheTypes(Assembly asm) { Type[] types = asm.GetTypes(); foreach (Type type in types) { if (!string.IsNullOrEmpty(type.Namespace) && !uniqueNamespaces.Contains(type.Namespace)) { uniqueNamespaces.Add(type.Namespace); int j; for (j = 0; j < AllNamespaces.Count && type.Namespace.CompareTo(AllNamespaces[j]) >= 0; j++) { } AllNamespaces.Insert(j, type.Namespace); } AllTypes[type.FullName] = type; ReflectionUtility.OnTypeLoaded?.Invoke(type); } } public static Type GetTypeByName(string fullName) { return Instance.Internal_GetTypeByName(fullName); } internal virtual Type Internal_GetTypeByName(string fullName) { if (shorthandToType.TryGetValue(fullName, out var value)) { return value; } AllTypes.TryGetValue(fullName, out var value2); return value2; } internal virtual Type Internal_GetActualType(object obj) { return obj?.GetType(); } internal virtual object Internal_TryCast(object obj, Type castTo) { return obj; } public static string ProcessTypeInString(Type type, string theString) { return Instance.Internal_ProcessTypeInString(theString, type); } internal virtual string Internal_ProcessTypeInString(string theString, Type type) { return theString; } public static void FindSingleton(string[] possibleNames, Type type, BindingFlags flags, List instances) { Instance.Internal_FindSingleton(possibleNames, type, flags, instances); } internal virtual void Internal_FindSingleton(string[] possibleNames, Type type, BindingFlags flags, List instances) { foreach (string name in possibleNames) { FieldInfo field = type.GetField(name, flags); if ((object)field != null) { object value = field.GetValue(null); if (value != null) { instances.Add(value); break; } } } } public static Type[] TryExtractTypesFromException(ReflectionTypeLoadException e) { try { return e.Types.Where((Type it) => (object)it != null).ToArray(); } catch { return ArgumentUtility.EmptyTypes; } } public static Type[] GetAllBaseTypes(object obj) { return GetAllBaseTypes(obj?.GetActualType()); } public static Type[] GetAllBaseTypes(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } string assemblyQualifiedName = type.AssemblyQualifiedName; if (baseTypes.TryGetValue(assemblyQualifiedName, out var value)) { return value; } List list = new List(); while ((object)type != null) { list.Add(type); type = type.BaseType; } value = list.ToArray(); baseTypes.Add(assemblyQualifiedName, value); return value; } public static void GetImplementationsOf(Type baseType, Action> onResultsFetched, bool allowAbstract, bool allowGeneric, bool allowEnum) { RuntimeHelper.StartCoroutine(DoGetImplementations(onResultsFetched, baseType, allowAbstract, allowGeneric, allowEnum)); } private static IEnumerator DoGetImplementations(Action> onResultsFetched, Type baseType, bool allowAbstract, bool allowGeneric, bool allowEnum) { List resolvedTypes = new List(); OnTypeLoaded += ourListener; HashSet set = new HashSet(); IEnumerator coro = GetImplementationsAsync(baseType, set, allowAbstract, allowGeneric, allowEnum, DefaultTypesEnumerator()); while (coro.MoveNext()) { yield return null; } OnTypeLoaded -= ourListener; if (resolvedTypes.Count > 0) { coro = GetImplementationsAsync(baseType, set, allowAbstract, allowGeneric, allowEnum, resolvedTypes.GetEnumerator()); while (coro.MoveNext()) { yield return null; } } onResultsFetched(set); void ourListener(Type t) { resolvedTypes.Add(t); } } private static IEnumerator DefaultTypesEnumerator() { string[] names = GetTypeNameArray(); foreach (string name in names) { yield return AllTypes[name]; } } private static IEnumerator GetImplementationsAsync(Type baseType, HashSet set, bool allowAbstract, bool allowGeneric, bool allowEnum, IEnumerator enumerator) { Stopwatch sw = new Stopwatch(); sw.Start(); bool isGenericParam = baseType?.IsGenericParameter ?? false; while (enumerator.MoveNext()) { if (sw.ElapsedMilliseconds > 10) { yield return null; sw.Reset(); sw.Start(); } try { Type type = enumerator.Current; if (set.Contains(type) || (!allowAbstract && type.IsAbstract) || (!allowGeneric && type.IsGenericType) || (!allowEnum && type.IsEnum) || type.FullName.Contains("PrivateImplementationDetails") || type.FullName.Contains("DisplayClass") || Enumerable.Contains(type.FullName, '<')) { continue; } if (!isGenericParam) { if ((object)baseType == null || baseType.IsAssignableFrom(type)) { goto IL_0269; } } else if ((!type.IsClass || !MiscUtility.HasFlag(baseType.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint)) && (!type.IsValueType || !MiscUtility.HasFlag(baseType.GenericParameterAttributes, GenericParameterAttributes.ReferenceTypeConstraint)) && !baseType.GetGenericParameterConstraints().Any((Type it) => !it.IsAssignableFrom(type))) { goto IL_0269; } goto end_IL_009f; IL_0269: set.Add(type); end_IL_009f:; } catch { } } } public static bool IsEnumerable(Type type) { return Instance.Internal_IsEnumerable(type); } protected virtual bool Internal_IsEnumerable(Type type) { return typeof(IEnumerable).IsAssignableFrom(type); } public static bool TryGetEnumerator(object ienumerable, out IEnumerator enumerator) { return Instance.Internal_TryGetEnumerator(ienumerable, out enumerator); } protected virtual bool Internal_TryGetEnumerator(object list, out IEnumerator enumerator) { enumerator = (list as IEnumerable).GetEnumerator(); return true; } public static bool TryGetEntryType(Type enumerableType, out Type type) { return Instance.Internal_TryGetEntryType(enumerableType, out type); } protected virtual bool Internal_TryGetEntryType(Type enumerableType, out Type type) { if (enumerableType.IsArray) { type = enumerableType.GetElementType(); return true; } Type[] interfaces = enumerableType.GetInterfaces(); foreach (Type type2 in interfaces) { if (type2.IsGenericType) { Type genericTypeDefinition = type2.GetGenericTypeDefinition(); if ((object)genericTypeDefinition == typeof(IEnumerable<>) || (object)genericTypeDefinition == typeof(IList<>) || (object)genericTypeDefinition == typeof(ICollection<>)) { type = type2.GetGenericArguments()[0]; return true; } } } type = typeof(object); return false; } public static bool IsDictionary(Type type) { return Instance.Internal_IsDictionary(type); } protected virtual bool Internal_IsDictionary(Type type) { return typeof(IDictionary).IsAssignableFrom(type); } public static bool TryGetDictEnumerator(object dictionary, out IEnumerator dictEnumerator) { return Instance.Internal_TryGetDictEnumerator(dictionary, out dictEnumerator); } protected virtual bool Internal_TryGetDictEnumerator(object dictionary, out IEnumerator dictEnumerator) { dictEnumerator = EnumerateDictionary((IDictionary)dictionary); return true; } private IEnumerator EnumerateDictionary(IDictionary dict) { IDictionaryEnumerator enumerator = dict.GetEnumerator(); while (enumerator.MoveNext()) { yield return new DictionaryEntry(enumerator.Key, enumerator.Value); } } public static bool TryGetEntryTypes(Type dictionaryType, out Type keys, out Type values) { return Instance.Internal_TryGetEntryTypes(dictionaryType, out keys, out values); } protected virtual bool Internal_TryGetEntryTypes(Type dictionaryType, out Type keys, out Type values) { Type[] interfaces = dictionaryType.GetInterfaces(); foreach (Type type in interfaces) { if (type.IsGenericType && (object)type.GetGenericTypeDefinition() == typeof(IDictionary<, >)) { Type[] genericArguments = type.GetGenericArguments(); keys = genericArguments[0]; values = genericArguments[1]; return true; } } keys = typeof(object); values = typeof(object); return false; } } } // ---- UniverseLib.Mono.dll :: UniverseLib.RuntimeHelper ---- namespace UniverseLib { public abstract class RuntimeHelper { internal static RuntimeHelper Instance { get; private set; } internal static void Init() { Instance = new MonoProvider(); Instance.OnInitialize(); } protected internal abstract void OnInitialize(); public static Coroutine StartCoroutine(IEnumerator routine) { return Instance.Internal_StartCoroutine(routine); } protected internal abstract Coroutine Internal_StartCoroutine(IEnumerator routine); public static void StopCoroutine(Coroutine coroutine) { Instance.Internal_StopCoroutine(coroutine); } protected internal abstract void Internal_StopCoroutine(Coroutine coroutine); public static T AddComponent(GameObject obj, Type type) where T : Component { return Instance.Internal_AddComponent(obj, type); } protected internal abstract T Internal_AddComponent(GameObject obj, Type type) where T : Component; public static ScriptableObject CreateScriptable(Type type) { return Instance.Internal_CreateScriptable(type); } protected internal abstract ScriptableObject Internal_CreateScriptable(Type type); public static string LayerToName(int layer) { return Instance.Internal_LayerToName(layer); } protected internal abstract string Internal_LayerToName(int layer); public static T[] FindObjectsOfTypeAll() where T : UnityEngine.Object { return Instance.Internal_FindObjectsOfTypeAll(); } public static UnityEngine.Object[] FindObjectsOfTypeAll(Type type) { return Instance.Internal_FindObjectsOfTypeAll(type); } protected internal abstract T[] Internal_FindObjectsOfTypeAll() where T : UnityEngine.Object; protected internal abstract UnityEngine.Object[] Internal_FindObjectsOfTypeAll(Type type); public static void GraphicRaycast(GraphicRaycaster raycaster, PointerEventData data, List list) { Instance.Internal_GraphicRaycast(raycaster, data, list); } protected internal abstract void Internal_GraphicRaycast(GraphicRaycaster raycaster, PointerEventData data, List list); public static GameObject[] GetRootGameObjects(Scene scene) { return Instance.Internal_GetRootGameObjects(scene); } protected internal abstract GameObject[] Internal_GetRootGameObjects(Scene scene); public static int GetRootCount(Scene scene) { return Instance.Internal_GetRootCount(scene); } protected internal abstract int Internal_GetRootCount(Scene scene); public static void SetColorBlockAuto(Selectable selectable, Color baseColor) { Instance.Internal_SetColorBlock(selectable, baseColor, baseColor * 1.2f, baseColor * 0.8f); } public static void SetColorBlock(Selectable selectable, ColorBlock colors) { Instance.Internal_SetColorBlock(selectable, colors); } protected internal abstract void Internal_SetColorBlock(Selectable selectable, ColorBlock colors); public static void SetColorBlock(Selectable selectable, Color? normal = null, Color? highlighted = null, Color? pressed = null, Color? disabled = null) { Instance.Internal_SetColorBlock(selectable, normal, highlighted, pressed, disabled); } protected internal abstract void Internal_SetColorBlock(Selectable selectable, Color? normal = null, Color? highlighted = null, Color? pressed = null, Color? disabled = null); } } // ---- UniverseLib.Mono.dll :: UniverseLib.UniversalBehaviour ---- namespace UniverseLib { internal class UniversalBehaviour : MonoBehaviour { internal static UniversalBehaviour Instance { get; private set; } internal static void Setup() { GameObject gameObject = new GameObject("UniverseLibBehaviour"); Object.DontDestroyOnLoad(gameObject); gameObject.hideFlags |= HideFlags.HideAndDontSave; Instance = gameObject.AddComponent(); } internal void Update() { Universe.Update(); } } } // ---- UniverseLib.Mono.dll :: UniverseLib.Universe ---- namespace UniverseLib { public class Universe { public enum GlobalState { WaitingToSetup, SettingUp, SetupCompleted } public const string NAME = "UniverseLib"; public const string VERSION = "1.4.3"; public const string AUTHOR = "Sinai"; public const string GUID = "com.sinai.universelib"; private static float startupDelay; private static Action logHandler; public static RuntimeContext Context { get; } = RuntimeContext.Mono; public static GlobalState CurrentGlobalState { get; private set; } internal static Harmony Harmony { get; } = new Harmony("com.sinai.universelib"); private static event Action OnInitialized; public static void Init(Action onInitialized = null, Action logHandler = null) { Init(1f, onInitialized, logHandler, default(UniverseLibConfig)); } public static void Init(float startupDelay, Action onInitialized, Action logHandler, UniverseLibConfig config) { if (CurrentGlobalState == GlobalState.SetupCompleted) { InvokeOnInitialized(onInitialized); return; } if (startupDelay > Universe.startupDelay) { Universe.startupDelay = startupDelay; } ConfigManager.LoadConfig(config); OnInitialized += onInitialized; if (logHandler != null && Universe.logHandler == null) { Universe.logHandler = logHandler; } if (CurrentGlobalState == GlobalState.WaitingToSetup) { CurrentGlobalState = GlobalState.SettingUp; Log("UniverseLib 1.4.3 initializing..."); UniversalBehaviour.Setup(); ReflectionUtility.Init(); RuntimeHelper.Init(); RuntimeHelper.Instance.Internal_StartCoroutine(SetupCoroutine()); Log("Finished UniverseLib initial setup."); } } internal static void Update() { UniversalUI.Update(); } private static IEnumerator SetupCoroutine() { yield return null; Stopwatch sw = new Stopwatch(); sw.Start(); while (ReflectionUtility.Initializing || (float)sw.ElapsedMilliseconds * 0.001f < startupDelay) { yield return null; } InputManager.Init(); UniversalUI.Init(); Log("UniverseLib 1.4.3 initialized."); CurrentGlobalState = GlobalState.SetupCompleted; InvokeOnInitialized(Universe.OnInitialized); } private static void InvokeOnInitialized(Action onInitialized) { if (onInitialized == null) { return; } Delegate[] invocationList = onInitialized.GetInvocationList(); foreach (Delegate obj in invocationList) { try { obj.DynamicInvoke(); } catch (Exception arg) { LogWarning($"Exception invoking onInitialized callback! {arg}"); } } } internal static void Log(object message) { Log(message, LogType.Log); } internal static void LogWarning(object message) { Log(message, LogType.Warning); } internal static void LogError(object message) { Log(message, LogType.Error); } private static void Log(object message, LogType logType) { logHandler("[UniverseLib] " + (message?.ToString() ?? string.Empty), logType); } internal static bool Patch(Type type, string methodName, MethodType methodType, Type[] arguments = null, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null) { try { string text = methodType switch { MethodType.Getter => "get_", MethodType.Setter => "set_", _ => string.Empty, }; MethodInfo methodInfo = ((arguments == null) ? type.GetMethod(text + methodName, AccessTools.all) : type.GetMethod(text + methodName, AccessTools.all, null, arguments, null)); if ((object)methodInfo == null) { return false; } PatchProcessor patchProcessor = Harmony.CreateProcessor(methodInfo); if ((object)prefix != null) { patchProcessor.AddPrefix(new HarmonyMethod(prefix)); } if ((object)postfix != null) { patchProcessor.AddPostfix(new HarmonyMethod(postfix)); } if ((object)finalizer != null) { patchProcessor.AddFinalizer(new HarmonyMethod(finalizer)); } patchProcessor.Patch(); return true; } catch (Exception arg) { LogWarning($"\t Exception patching {type.FullName}.{methodName}: {arg}"); return false; } } internal static bool Patch(Type type, string[] possibleNames, MethodType methodType, Type[] arguments = null, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null) { foreach (string methodName in possibleNames) { if (Patch(type, methodName, methodType, arguments, prefix, postfix, finalizer)) { return true; } } return false; } internal static bool Patch(Type type, string[] possibleNames, MethodType methodType, Type[][] possibleArguments, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null) { foreach (string methodName in possibleNames) { foreach (Type[] arguments in possibleArguments) { if (Patch(type, methodName, methodType, arguments, prefix, postfix, finalizer)) { return true; } } } return false; } internal static bool Patch(Type type, string methodName, MethodType methodType, Type[][] possibleArguments, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo finalizer = null) { foreach (Type[] arguments in possibleArguments) { if (Patch(type, methodName, methodType, arguments, prefix, postfix, finalizer)) { return true; } } return false; } } } // ---- UniverseLib.Mono.dll :: UniverseLib.Utility.ArgumentUtility ---- namespace UniverseLib.Utility { public static class ArgumentUtility { public static readonly Type[] EmptyTypes = new Type[0]; public static readonly object[] EmptyArgs = new object[0]; public static readonly Type[] ParseArgs = new Type[1] { typeof(string) }; } } // ---- UniverseLib.Mono.dll :: UniverseLib.Utility.IOUtility ---- namespace UniverseLib.Utility { public static class IOUtility { private static readonly char[] invalidDirectoryCharacters = Path.GetInvalidPathChars(); private static readonly char[] invalidFilenameCharacters = Path.GetInvalidFileNameChars(); public static string EnsureValidFilePath(string fullPathWithFile) { fullPathWithFile = string.Concat(fullPathWithFile.Split(invalidDirectoryCharacters)); Directory.CreateDirectory(Path.GetDirectoryName(fullPathWithFile)); return fullPathWithFile; } public static string EnsureValidFilename(string filename) { return string.Concat(filename.Split(invalidFilenameCharacters)); } } } // ---- UniverseLib.Mono.dll :: UniverseLib.Utility.MiscUtility ---- namespace UniverseLib.Utility { public static class MiscUtility { public static bool ContainsIgnoreCase(this string _this, string s) { return CultureInfo.CurrentCulture.CompareInfo.IndexOf(_this, s, CompareOptions.IgnoreCase) >= 0; } public static bool HasFlag(this Enum flags, Enum value) { try { ulong num = Convert.ToUInt64(value); return (Convert.ToUInt64(flags) & num) == num; } catch { long num2 = Convert.ToInt64(value); return (Convert.ToInt64(flags) & num2) == num2; } } public static bool EndsWith(this StringBuilder sb, string _string) { int length = _string.Length; if (sb.Length < length) { return false; } int num = 0; int num2 = sb.Length - length; while (num2 < sb.Length) { if (sb[num2] != _string[num]) { return false; } num2++; num++; } return true; } } } // ---- UniverseLib.Mono.dll :: UniverseLib.Utility.ParseUtility ---- namespace UniverseLib.Utility { public static class ParseUtility { internal delegate object ParseMethod(string input); internal delegate string ToStringMethod(object obj); public static readonly string NumberFormatString = "0.####"; private static readonly Dictionary numSequenceStrings = new Dictionary(); private static readonly HashSet nonPrimitiveTypes = new HashSet { typeof(string), typeof(decimal), typeof(DateTime) }; private static readonly HashSet formattedTypes = new HashSet { typeof(float), typeof(double), typeof(decimal) }; private static readonly Dictionary typeInputExamples = new Dictionary(); private static readonly Dictionary customTypes = new Dictionary { { typeof(Vector2).FullName, TryParseVector2 }, { typeof(Vector3).FullName, TryParseVector3 }, { typeof(Vector4).FullName, TryParseVector4 }, { typeof(Quaternion).FullName, TryParseQuaternion }, { typeof(Rect).FullName, TryParseRect }, { typeof(Color).FullName, TryParseColor }, { typeof(Color32).FullName, TryParseColor32 }, { typeof(LayerMask).FullName, TryParseLayerMask } }; private static readonly Dictionary customTypesToString = new Dictionary { { typeof(Vector2).FullName, Vector2ToString }, { typeof(Vector3).FullName, Vector3ToString }, { typeof(Vector4).FullName, Vector4ToString }, { typeof(Quaternion).FullName, QuaternionToString }, { typeof(Rect).FullName, RectToString }, { typeof(Color).FullName, ColorToString }, { typeof(Color32).FullName, Color32ToString }, { typeof(LayerMask).FullName, LayerMaskToString } }; public static string FormatDecimalSequence(params object[] numbers) { if (numbers.Length == 0) { return null; } return string.Format(CultureInfo.CurrentCulture, GetSequenceFormatString(numbers.Length), numbers); } internal static string GetSequenceFormatString(int count) { if (count <= 0) { return null; } if (numSequenceStrings.ContainsKey(count)) { return numSequenceStrings[count]; } string[] array = new string[count]; for (int i = 0; i < count; i++) { array[i] = $"{{{i}:{NumberFormatString}}}"; } string text = string.Join(" ", array); numSequenceStrings.Add(count, text); return text; } public static bool CanParse(Type type) { return !string.IsNullOrEmpty(type?.FullName) && (type.IsPrimitive || type.IsEnum || nonPrimitiveTypes.Contains(type) || customTypes.ContainsKey(type.FullName)); } public static bool CanParse() { return CanParse(typeof(T)); } public static bool TryParse(string input, out T obj, out Exception parseException) { object obj2; bool result = TryParse(input, typeof(T), out obj2, out parseException); if (obj2 != null) { obj = (T)obj2; } else { obj = default(T); } return result; } public static bool TryParse(string input, Type type, out object obj, out Exception parseException) { obj = null; parseException = null; if ((object)type == null) { return false; } if ((object)type == typeof(string)) { obj = input; return true; } if (type.IsEnum) { try { obj = Enum.Parse(type, input); return true; } catch (Exception e) { parseException = e.GetInnerMostException(); return false; } } try { if (customTypes.ContainsKey(type.FullName)) { obj = customTypes[type.FullName](input); } else { obj = AccessTools.Method(type, "Parse", ArgumentUtility.ParseArgs).Invoke(null, new object[1] { input }); } return true; } catch (Exception e2) { Exception innerMostException = e2.GetInnerMostException(); parseException = innerMostException; } return false; } public static string ToStringForInput(object obj) { return ToStringForInput(obj, typeof(T)); } public static string ToStringForInput(object obj, Type type) { if ((object)type == null || obj == null) { return null; } if ((object)type == typeof(string)) { return obj as string; } if (type.IsEnum) { return Enum.IsDefined(type, obj) ? Enum.GetName(type, obj) : obj.ToString(); } try { if (customTypes.ContainsKey(type.FullName)) { return customTypesToString[type.FullName](obj); } if (formattedTypes.Contains(type)) { return AccessTools.Method(type, "ToString", new Type[2] { typeof(string), typeof(IFormatProvider) }).Invoke(obj, new object[2] { NumberFormatString, CultureInfo.CurrentCulture }) as string; } return obj.ToString(); } catch (Exception arg) { Universe.LogWarning($"Exception formatting object for input: {arg}"); return null; } } public static string GetExampleInput() { return GetExampleInput(typeof(T)); } public static string GetExampleInput(Type type) { if (!typeInputExamples.ContainsKey(type.AssemblyQualifiedName)) { try { if (type.IsEnum) { typeInputExamples.Add(type.AssemblyQualifiedName, Enum.GetNames(type).First()); } else { object obj = Activator.CreateInstance(type); typeInputExamples.Add(type.AssemblyQualifiedName, ToStringForInput(obj, type)); } } catch (Exception message) { Universe.LogWarning("Exception generating default instance for example input for '" + type.FullName + "'"); Universe.Log(message); return ""; } } return typeInputExamples[type.AssemblyQualifiedName]; } internal static object TryParseVector2(string input) { Vector2 vector = default(Vector2); string[] array = input.Split(new char[1] { ' ' }); vector.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture); vector.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture); return vector; } internal static string Vector2ToString(object obj) { if (!(obj is Vector2 vector) || 1 == 0) { return null; } return FormatDecimalSequence(vector.x, vector.y); } internal static object TryParseVector3(string input) { Vector3 vector = default(Vector3); string[] array = input.Split(new char[1] { ' ' }); vector.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture); vector.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture); vector.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture); return vector; } internal static string Vector3ToString(object obj) { if (!(obj is Vector3 vector) || 1 == 0) { return null; } return FormatDecimalSequence(vector.x, vector.y, vector.z); } internal static object TryParseVector4(string input) { Vector4 vector = default(Vector4); string[] array = input.Split(new char[1] { ' ' }); vector.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture); vector.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture); vector.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture); vector.w = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture); return vector; } internal static string Vector4ToString(object obj) { if (!(obj is Vector4 vector) || 1 == 0) { return null; } return FormatDecimalSequence(vector.x, vector.y, vector.z, vector.w); } internal static object TryParseQuaternion(string input) { Vector3 euler = default(Vector3); string[] array = input.Split(new char[1] { ' ' }); if (array.Length == 4) { return new Quaternion { x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture), y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture), z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture), w = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture) }; } euler.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture); euler.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture); euler.z = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture); return Quaternion.Euler(euler); } internal static string QuaternionToString(object obj) { if (!(obj is Quaternion quaternion) || 1 == 0) { return null; } Vector3 eulerAngles = quaternion.eulerAngles; return FormatDecimalSequence(eulerAngles.x, eulerAngles.y, eulerAngles.z); } internal static object TryParseRect(string input) { Rect rect = default(Rect); string[] array = input.Split(new char[1] { ' ' }); rect.x = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture); rect.y = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture); rect.width = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture); rect.height = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture); return rect; } internal static string RectToString(object obj) { if (!(obj is Rect rect) || 1 == 0) { return null; } return FormatDecimalSequence(rect.x, rect.y, rect.width, rect.height); } internal static object TryParseColor(string input) { Color color = default(Color); string[] array = input.Split(new char[1] { ' ' }); color.r = float.Parse(array[0].Trim(), CultureInfo.CurrentCulture); color.g = float.Parse(array[1].Trim(), CultureInfo.CurrentCulture); color.b = float.Parse(array[2].Trim(), CultureInfo.CurrentCulture); if (array.Length > 3) { color.a = float.Parse(array[3].Trim(), CultureInfo.CurrentCulture); } else { color.a = 1f; } return color; } internal static string ColorToString(object obj) { if (!(obj is Color color) || 1 == 0) { return null; } return FormatDecimalSequence(color.r, color.g, color.b, color.a); } internal static object TryParseColor32(string input) { Color32 color = default(Color32); string[] array = input.Split(new char[1] { ' ' }); color.r = byte.Parse(array[0].Trim(), CultureInfo.CurrentCulture); color.g = byte.Parse(array[1].Trim(), CultureInfo.CurrentCulture); color.b = byte.Parse(array[2].Trim(), CultureInfo.CurrentCulture); if (array.Length > 3) { color.a = byte.Parse(array[3].Trim(), CultureInfo.CurrentCulture); } else { color.a = byte.MaxValue; } return color; } internal static string Color32ToString(object obj) { if (!(obj is Color32 color) || 1 == 0) { return null; } return $"{color.r} {color.g} {color.b} {color.a}"; } internal static object TryParseLayerMask(string input) { return (LayerMask)int.Parse(input); } internal static string LayerMaskToString(object obj) { if (!(obj is LayerMask layerMask) || 1 == 0) { return null; } return layerMask.value.ToString(); } } } // ---- UniverseLib.Mono.dll :: UniverseLib.Utility.SignatureHighlighter ---- namespace UniverseLib.Utility { public static class SignatureHighlighter { public const string NAMESPACE = "#a8a8a8"; public const string CONST = "#92c470"; public const string CLASS_STATIC = "#3a8d71"; public const string CLASS_INSTANCE = "#2df7b2"; public const string STRUCT = "#0fba3a"; public const string INTERFACE = "#9b9b82"; public const string FIELD_STATIC = "#8d8dc6"; public const string FIELD_INSTANCE = "#c266ff"; public const string METHOD_STATIC = "#b55b02"; public const string METHOD_INSTANCE = "#ff8000"; public const string PROP_STATIC = "#588075"; public const string PROP_INSTANCE = "#55a38e"; public const string LOCAL_ARG = "#a6e9e9"; public const string OPEN_COLOR = ""); public static readonly Color StringOrange = new Color(0.83f, 0.61f, 0.52f); public static readonly Color EnumGreen = new Color(0.57f, 0.76f, 0.43f); public static readonly Color KeywordBlue = new Color(0.3f, 0.61f, 0.83f); public static readonly string keywordBlueHex = KeywordBlue.ToHex(); public static readonly Color NumberGreen = new Color(0.71f, 0.8f, 0.65f); private static readonly Dictionary typeToRichType = new Dictionary(); private static readonly Dictionary highlightedMethods = new Dictionary(); private static readonly Dictionary builtInTypesToShorthand = new Dictionary { { typeof(object), "object" }, { typeof(string), "string" }, { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(sbyte), "sbyte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(float), "float" }, { typeof(int), "int" }, { typeof(uint), "uint" }, { typeof(long), "long" }, { typeof(ulong), "ulong" }, { typeof(short), "short" }, { typeof(ushort), "ushort" }, { typeof(void), "void" } }; public static string Parse(Type type, bool includeNamespace, MemberInfo memberInfo = null) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (memberInfo is MethodInfo method) { return ParseMethod(method); } if (memberInfo is ConstructorInfo ctor) { return ParseConstructor(ctor); } StringBuilder stringBuilder = new StringBuilder(); if (type.IsByRef) { AppendOpenColor(stringBuilder, "#" + keywordBlueHex).Append("ref ").Append(""); } Type type2 = type; while (type2.HasElementType) { type2 = type2.GetElementType(); } includeNamespace &= !builtInTypesToShorthand.ContainsKey(type2); if (!type.IsGenericParameter && (!type.HasElementType || !type.GetElementType().IsGenericParameter) && includeNamespace && TryGetNamespace(type, out var ns)) { AppendOpenColor(stringBuilder, "#a8a8a8").Append(ns).Append("").Append('.'); } stringBuilder.Append(ProcessType(type)); if ((object)memberInfo != null) { stringBuilder.Append('.'); int index = stringBuilder.Length - 1; AppendOpenColor(stringBuilder, GetMemberInfoColor(memberInfo, out var isStatic)).Append(memberInfo.Name).Append(""); if (isStatic) { stringBuilder.Insert(index, ""); stringBuilder.Append(""); } } return stringBuilder.ToString(); } private static string ProcessType(Type type) { string key = type.ToString(); if (typeToRichType.ContainsKey(key)) { return typeToRichType[key]; } StringBuilder stringBuilder = new StringBuilder(); if (!type.IsGenericParameter) { int length = stringBuilder.Length; Type declaringType = type.DeclaringType; while ((object)declaringType != null) { stringBuilder.Insert(length, HighlightType(declaringType) + "."); declaringType = declaringType.DeclaringType; } stringBuilder.Append(HighlightType(type)); if (type.IsGenericType) { ProcessGenericArguments(type, stringBuilder); } } else { stringBuilder.Append("') .Append(type.Name) .Append(""); } string text = stringBuilder.ToString(); typeToRichType.Add(key, text); return text; } internal static string GetClassColor(Type type) { if (type.IsAbstract && type.IsSealed) { return "#3a8d71"; } if (type.IsEnum || type.IsGenericParameter) { return "#92c470"; } if (type.IsValueType) { return "#0fba3a"; } if (type.IsInterface) { return "#9b9b82"; } return "#2df7b2"; } private static bool TryGetNamespace(Type type, out string ns) { return !string.IsNullOrEmpty(ns = type.Namespace?.Trim()); } private static StringBuilder AppendOpenColor(StringBuilder sb, string color) { return sb.Append("'); } private static string HighlightType(Type type) { StringBuilder stringBuilder = new StringBuilder(); if (type.IsByRef) { type = type.GetElementType(); } int num = 0; Match match = ArrayTokenRegex.Match(type.Name); if (match != null && match.Success) { num = 1 + match.Value.Count((char c) => c == ','); type = type.GetElementType(); } if (builtInTypesToShorthand.TryGetValue(type, out var value)) { AppendOpenColor(stringBuilder, "#" + keywordBlueHex).Append(value).Append(""); } else { stringBuilder.Append("").Append(type.Name).Append(""); } if (num > 0) { stringBuilder.Append('[').Append(new string(',', num - 1)).Append(']'); } return stringBuilder.ToString(); } private static void ProcessGenericArguments(Type type, StringBuilder sb) { List list = type.GetGenericArguments().ToList(); for (int i = 0; i < sb.Length; i++) { if (!list.Any()) { break; } if (sb[i] != '`') { continue; } int num = i; i++; StringBuilder stringBuilder = new StringBuilder(); for (; char.IsDigit(sb[i]); i++) { stringBuilder.Append(sb[i]); } string text = stringBuilder.ToString(); int num2 = int.Parse(text); sb.Remove(num, text.Length + 1); int num3 = 1; num++; while (num3 < "".Length && sb[num] == ""[num3]) { num3++; num++; } sb.Insert(num, '<'); num++; int length = sb.Length; while (num2 > 0 && list.Any()) { num2--; Type type2 = list.First(); list.RemoveAt(0); sb.Insert(num, ProcessType(type2)); if (num2 > 0) { num += sb.Length - length; sb.Insert(num, ", "); num += 2; length = sb.Length; } } sb.Insert(num + sb.Length - length, '>'); } } public static string RemoveHighlighting(string _string) { if (_string == null) { throw new ArgumentNullException("_string"); } _string = _string.Replace("", string.Empty); _string = _string.Replace("", string.Empty); _string = colorTagRegex.Replace(_string, string.Empty); _string = _string.Replace("", string.Empty); return _string; } [Obsolete("Use 'ParseMethod(MethodInfo)' instead (rename).")] public static string HighlightMethod(MethodInfo method) { return ParseMethod(method); } public static string ParseMethod(MethodInfo method) { string key = method.FullDescription(); if (highlightedMethods.ContainsKey(key)) { return highlightedMethods[key]; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(Parse(method.DeclaringType, includeNamespace: false)); stringBuilder.Append('.'); string text = ((!method.IsStatic) ? "#ff8000" : "#b55b02"); stringBuilder.Append("" + method.Name + ""); if (method.IsGenericMethod) { stringBuilder.Append("<"); Type[] genericArguments = method.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { Type type = genericArguments[i]; if (type.IsGenericParameter) { stringBuilder.Append("" + genericArguments[i].Name + ""); } else { stringBuilder.Append(Parse(type, includeNamespace: false)); } if (i < genericArguments.Length - 1) { stringBuilder.Append(", "); } } stringBuilder.Append(">"); } stringBuilder.Append('('); ParameterInfo[] parameters = method.GetParameters(); for (int j = 0; j < parameters.Length; j++) { ParameterInfo parameterInfo = parameters[j]; stringBuilder.Append(Parse(parameterInfo.ParameterType, includeNamespace: false)); if (j < parameters.Length - 1) { stringBuilder.Append(", "); } } stringBuilder.Append(')'); string text2 = stringBuilder.ToString(); highlightedMethods.Add(key, text2); return text2; } [Obsolete("Use 'ParseConstructor(ConstructorInfo)' instead (rename).")] public static string HighlightConstructor(ConstructorInfo ctor) { return ParseConstructor(ctor); } public static string ParseConstructor(ConstructorInfo ctor) { string key = ctor.FullDescription(); if (highlightedMethods.ContainsKey(key)) { return highlightedMethods[key]; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(Parse(ctor.DeclaringType, includeNamespace: false)); string value = stringBuilder.ToString(); stringBuilder.Append('.'); stringBuilder.Append(value); stringBuilder.Append('('); ParameterInfo[] parameters = ctor.GetParameters(); for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; stringBuilder.Append(Parse(parameterInfo.ParameterType, includeNamespace: false)); if (i < parameters.Length - 1) { stringBuilder.Append(", "); } } stringBuilder.Append(')'); string text = stringBuilder.ToString(); highlightedMethods.Add(key, text); return text; } public static string GetMemberInfoColor(MemberInfo memberInfo, out bool isStatic) { isStatic = false; if (memberInfo is FieldInfo fieldInfo) { if (fieldInfo.IsStatic) { isStatic = true; return "#8d8dc6"; } return "#c266ff"; } if (memberInfo is MethodInfo methodInfo) { if (methodInfo.IsStatic) { isStatic = true; return "#b55b02"; } return "#ff8000"; } if (memberInfo is PropertyInfo propertyInfo) { if (propertyInfo.GetAccessors(nonPublic: true)[0].IsStatic) { isStatic = true; return "#588075"; } return "#55a38e"; } if (memberInfo is ConstructorInfo) { isStatic = true; return "#2df7b2"; } throw new NotImplementedException(memberInfo.GetType().Name + " is not supported"); } } } // ---- UniverseLib.Mono.dll :: UniverseLib.Utility.ToStringUtility ---- namespace UniverseLib.Utility { public static class ToStringUtility { internal static Dictionary toStringMethods = new Dictionary(); private const string nullString = "null"; private const string nullUnknown = "null (?)"; private const string destroyedString = "Destroyed"; private const string untitledString = "untitled"; private const string eventSystemNamespace = "UnityEngine.EventSystem"; public static string PruneString(string s, int chars = 200, int lines = 5) { if (string.IsNullOrEmpty(s)) { return s; } StringBuilder stringBuilder = new StringBuilder(Math.Max(chars, s.Length)); int num = 0; for (int i = 0; i < s.Length; i++) { if (num >= lines || i >= chars) { stringBuilder.Append("..."); break; } char c = s[i]; if (c == '\r' || c == '\n') { num++; } stringBuilder.Append(c); } return stringBuilder.ToString(); } public static string ToStringWithType(object value, Type fallbackType, bool includeNamespace = true) { if (value.IsNullOrDestroyed() && (object)fallbackType == null) { return "null (?)"; } Type type = value?.GetActualType() ?? fallbackType; string text = SignatureHighlighter.Parse(type, includeNamespace); StringBuilder stringBuilder = new StringBuilder(); if (value.IsNullOrDestroyed()) { if (value == null) { stringBuilder.Append("null"); AppendRichType(stringBuilder, text); return stringBuilder.ToString(); } stringBuilder.Append("Destroyed"); AppendRichType(stringBuilder, text); return stringBuilder.ToString(); } if (value is UnityEngine.Object obj) { if (string.IsNullOrEmpty(obj.name)) { stringBuilder.Append("untitled"); } else { stringBuilder.Append('"'); stringBuilder.Append(PruneString(obj.name, 50, 1)); stringBuilder.Append('"'); } AppendRichType(stringBuilder, text); } else if (type.FullName.StartsWith("UnityEngine.EventSystem")) { stringBuilder.Append(text); } else { string text2 = ToString(value); if (type.IsGenericType || text2 == type.FullName || text2 == type.FullName + " " + type.FullName || text2 == "Il2Cpp" + type.FullName || type.FullName == "Il2Cpp" + text2) { stringBuilder.Append(text); } else { stringBuilder.Append(PruneString(text2)); AppendRichType(stringBuilder, text); } } return stringBuilder.ToString(); } private static void AppendRichType(StringBuilder sb, string richType) { sb.Append(' '); sb.Append('('); sb.Append(richType); sb.Append(')'); } private static string ToString(object value) { if (value.IsNullOrDestroyed()) { if (value == null) { return "null"; } return "Destroyed"; } Type actualType = value.GetActualType(); if (!toStringMethods.ContainsKey(actualType.AssemblyQualifiedName)) { MethodInfo method = actualType.GetMethod("ToString", ArgumentUtility.EmptyTypes); toStringMethods.Add(actualType.AssemblyQualifiedName, method); } value = value.TryCast(actualType); string theString; try { theString = (string)toStringMethods[actualType.AssemblyQualifiedName].Invoke(value, ArgumentUtility.EmptyArgs); } catch (Exception e) { theString = e.ReflectionExToString(); } return ReflectionUtility.ProcessTypeInString(actualType, theString); } } } // ---- UniverseLib.Mono.dll :: UniverseLib.Utility.UnityHelpers ---- namespace UniverseLib.Utility { public static class UnityHelpers { private static PropertyInfo onEndEdit; public static bool OccuredEarlierThanDefault(this float time) { return Time.realtimeSinceStartup - 0.01f >= time; } public static bool OccuredEarlierThan(this float time, float secondsAgo) { return Time.realtimeSinceStartup - secondsAgo >= time; } public static bool IsNullOrDestroyed(this object obj, bool suppressWarning = true) { try { if (obj == null) { if (!suppressWarning) { Universe.LogWarning("The target instance is null!"); } return true; } if (obj is UnityEngine.Object obj2 && !obj2) { if (!suppressWarning) { Universe.LogWarning("The target UnityEngine.Object was destroyed!"); } return true; } return false; } catch { return true; } } public static string GetTransformPath(this Transform transform, bool includeSelf = false) { StringBuilder stringBuilder = new StringBuilder(); if (includeSelf) { stringBuilder.Append(transform.name); } while ((bool)transform.parent) { transform = transform.parent; stringBuilder.Insert(0, '/'); stringBuilder.Insert(0, transform.name); } return stringBuilder.ToString(); } public static string ToHex(this Color color) { byte b = (byte)Mathf.Clamp(Mathf.RoundToInt(color.r * 255f), 0, 255); byte b2 = (byte)Mathf.Clamp(Mathf.RoundToInt(color.g * 255f), 0, 255); byte b3 = (byte)Mathf.Clamp(Mathf.RoundToInt(color.b * 255f), 0, 255); return $"{b:X2}{b2:X2}{b3:X2}"; } public static Color ToColor(this string _string) { _string = _string.Replace("#", ""); if (_string.Length != 6) { return Color.magenta; } byte b = byte.Parse(_string.Substring(0, 2), NumberStyles.HexNumber); byte b2 = byte.Parse(_string.Substring(2, 2), NumberStyles.HexNumber); byte b3 = byte.Parse(_string.Substring(4, 2), NumberStyles.HexNumber); return new Color { r = (float)((decimal)b / 255m), g = (float)((decimal)b2 / 255m), b = (float)((decimal)b3 / 255m), a = 1f }; } public static UnityEvent GetOnEndEdit(this InputField _this) { if ((object)onEndEdit == null) { onEndEdit = AccessTools.Property(typeof(InputField), "onEndEdit") ?? throw new Exception("Could not get InputField.onEndEdit property!"); } return onEndEdit.GetValue(_this, null).TryCast>(); } } } // ---- UniverseLib.Mono.dll :: UniverseLib.UI.UIBase ---- namespace UniverseLib.UI { public class UIBase { internal static readonly int TOP_SORTORDER = 30000; public string ID { get; } public GameObject RootObject { get; } public RectTransform RootRect { get; } public Canvas Canvas { get; } public Action UpdateMethod { get; } public PanelManager Panels { get; } public bool Enabled { get { return (bool)RootObject && RootObject.activeSelf; } set { UniversalUI.SetUIActive(ID, value); } } public UIBase(string id, Action updateMethod) { if (string.IsNullOrEmpty(id)) { throw new ArgumentException("Cannot register a UI with a null or empty id!"); } if (UniversalUI.registeredUIs.ContainsKey(id)) { throw new ArgumentException("A UI with the id '" + id + "' is already registered!"); } ID = id; UpdateMethod = updateMethod; RootObject = UIFactory.CreateUIObject(id + "_Root", UniversalUI.CanvasRoot); RootObject.SetActive(value: false); RootRect = RootObject.GetComponent(); Canvas = RootObject.AddComponent(); Canvas.renderMode = RenderMode.ScreenSpaceCamera; Canvas.referencePixelsPerUnit = 100f; Canvas.sortingOrder = TOP_SORTORDER; Canvas.overrideSorting = true; CanvasScaler canvasScaler = RootObject.AddComponent(); canvasScaler.referenceResolution = new Vector2(1920f, 1080f); canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand; RootObject.AddComponent(); RectTransform component = RootObject.GetComponent(); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.pivot = new Vector2(0.5f, 0.5f); Panels = CreatePanelManager(); RootObject.SetActive(value: true); UniversalUI.registeredUIs.Add(id, this); UniversalUI.uiBases.Add(this); } protected virtual PanelManager CreatePanelManager() { return new PanelManager(this); } public void SetOnTop() { RootObject.transform.SetAsLastSibling(); foreach (UIBase uiBasis in UniversalUI.uiBases) { int num = UniversalUI.CanvasRoot.transform.childCount - uiBasis.RootRect.GetSiblingIndex(); uiBasis.Canvas.sortingOrder = TOP_SORTORDER - num; } UniversalUI.uiBases.Sort((UIBase a, UIBase b) => b.RootObject.transform.GetSiblingIndex().CompareTo(a.RootObject.transform.GetSiblingIndex())); } internal void Update() { try { Panels.Update(); UpdateMethod?.Invoke(); } catch (Exception arg) { Universe.LogWarning($"Exception invoking update method for {ID}: {arg}"); } } } } // ---- UniverseLib.Mono.dll :: UniverseLib.UI.UIFactory ---- namespace UniverseLib.UI { public static class UIFactory { internal static Vector2 largeElementSize = new Vector2(100f, 30f); internal static Vector2 smallElementSize = new Vector2(25f, 25f); internal static Color defaultTextColor = Color.white; public static GameObject CreateUIObject(string name, GameObject parent, Vector2 sizeDelta = default(Vector2)) { GameObject gameObject = new GameObject(name) { layer = 5, hideFlags = HideFlags.HideAndDontSave }; if ((bool)parent) { gameObject.transform.SetParent(parent.transform, worldPositionStays: false); } RectTransform rectTransform = gameObject.AddComponent(); rectTransform.sizeDelta = sizeDelta; return gameObject; } internal static void SetDefaultTextValues(Text text) { text.color = defaultTextColor; text.font = UniversalUI.DefaultFont; text.fontSize = 14; } internal static void SetDefaultSelectableValues(Selectable selectable) { Navigation navigation = selectable.navigation; navigation.mode = Navigation.Mode.Explicit; selectable.navigation = navigation; RuntimeHelper.Instance.Internal_SetColorBlock(selectable, new Color(0.2f, 0.2f, 0.2f), new Color(0.3f, 0.3f, 0.3f), new Color(0.15f, 0.15f, 0.15f)); } public static LayoutElement SetLayoutElement(GameObject gameObject, int? minWidth = null, int? minHeight = null, int? flexibleWidth = null, int? flexibleHeight = null, int? preferredWidth = null, int? preferredHeight = null, bool? ignoreLayout = null) { LayoutElement layoutElement = gameObject.GetComponent(); if (!layoutElement) { layoutElement = gameObject.AddComponent(); } if (minWidth.HasValue) { layoutElement.minWidth = minWidth.Value; } if (minHeight.HasValue) { layoutElement.minHeight = minHeight.Value; } if (flexibleWidth.HasValue) { layoutElement.flexibleWidth = flexibleWidth.Value; } if (flexibleHeight.HasValue) { layoutElement.flexibleHeight = flexibleHeight.Value; } if (preferredWidth.HasValue) { layoutElement.preferredWidth = preferredWidth.Value; } if (preferredHeight.HasValue) { layoutElement.preferredHeight = preferredHeight.Value; } if (ignoreLayout.HasValue) { layoutElement.ignoreLayout = ignoreLayout.Value; } return layoutElement; } public static T SetLayoutGroup(GameObject gameObject, bool? forceWidth = null, bool? forceHeight = null, bool? childControlWidth = null, bool? childControlHeight = null, int? spacing = null, int? padTop = null, int? padBottom = null, int? padLeft = null, int? padRight = null, TextAnchor? childAlignment = null) where T : HorizontalOrVerticalLayoutGroup { T val = gameObject.GetComponent(); if (!val) { val = gameObject.AddComponent(); } return SetLayoutGroup(val, forceWidth, forceHeight, childControlWidth, childControlHeight, spacing, padTop, padBottom, padLeft, padRight, childAlignment); } public static T SetLayoutGroup(T group, bool? forceWidth = null, bool? forceHeight = null, bool? childControlWidth = null, bool? childControlHeight = null, int? spacing = null, int? padTop = null, int? padBottom = null, int? padLeft = null, int? padRight = null, TextAnchor? childAlignment = null) where T : HorizontalOrVerticalLayoutGroup { if (forceWidth.HasValue) { group.childForceExpandWidth = forceWidth.Value; } if (forceHeight.HasValue) { group.childForceExpandHeight = forceHeight.Value; } if (childControlWidth.HasValue) { group.SetChildControlWidth(childControlWidth.Value); } if (childControlHeight.HasValue) { group.SetChildControlHeight(childControlHeight.Value); } if (spacing.HasValue) { group.spacing = spacing.Value; } if (padTop.HasValue) { group.padding.top = padTop.Value; } if (padBottom.HasValue) { group.padding.bottom = padBottom.Value; } if (padLeft.HasValue) { group.padding.left = padLeft.Value; } if (padRight.HasValue) { group.padding.right = padRight.Value; } if (childAlignment.HasValue) { group.childAlignment = childAlignment.Value; } return group; } public static GameObject CreatePanel(string name, GameObject parent, out GameObject contentHolder, Color? bgColor = null) { GameObject gameObject = CreateUIObject(name, parent); SetLayoutGroup(gameObject, true, true, true, true, 0, 1, 1, 1, 1); RectTransform component = gameObject.GetComponent(); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.anchoredPosition = Vector2.zero; component.sizeDelta = Vector2.zero; gameObject.AddComponent().color = Color.black; gameObject.AddComponent(); contentHolder = CreateUIObject("Content", gameObject); Image image = contentHolder.AddComponent(); image.type = Image.Type.Filled; image.color = ((!bgColor.HasValue) ? new Color(0.07f, 0.07f, 0.07f) : bgColor.Value); SetLayoutGroup(contentHolder, true, true, true, true, 3, 3, 3, 3, 3); return gameObject; } public static GameObject CreateVerticalGroup(GameObject parent, string name, bool forceWidth, bool forceHeight, bool childControlWidth, bool childControlHeight, int spacing = 0, Vector4 padding = default(Vector4), Color bgColor = default(Color), TextAnchor? childAlignment = null) { GameObject gameObject = CreateUIObject(name, parent); SetLayoutGroup(gameObject, forceWidth, forceHeight, childControlWidth, childControlHeight, spacing, (int)padding.x, (int)padding.y, (int)padding.z, (int)padding.w, childAlignment); Image image = gameObject.AddComponent(); image.color = ((bgColor == default(Color)) ? new Color(0.17f, 0.17f, 0.17f) : bgColor); return gameObject; } public static GameObject CreateHorizontalGroup(GameObject parent, string name, bool forceExpandWidth, bool forceExpandHeight, bool childControlWidth, bool childControlHeight, int spacing = 0, Vector4 padding = default(Vector4), Color bgColor = default(Color), TextAnchor? childAlignment = null) { GameObject gameObject = CreateUIObject(name, parent); SetLayoutGroup(gameObject, forceExpandWidth, forceExpandHeight, childControlWidth, childControlHeight, spacing, (int)padding.x, (int)padding.y, (int)padding.z, (int)padding.w, childAlignment); Image image = gameObject.AddComponent(); image.color = ((bgColor == default(Color)) ? new Color(0.17f, 0.17f, 0.17f) : bgColor); return gameObject; } public static GameObject CreateGridGroup(GameObject parent, string name, Vector2 cellSize, Vector2 spacing, Color bgColor = default(Color)) { GameObject gameObject = CreateUIObject(name, parent); GridLayoutGroup gridLayoutGroup = gameObject.AddComponent(); gridLayoutGroup.childAlignment = TextAnchor.UpperLeft; gridLayoutGroup.cellSize = cellSize; gridLayoutGroup.spacing = spacing; Image image = gameObject.AddComponent(); image.color = ((bgColor == default(Color)) ? new Color(0.17f, 0.17f, 0.17f) : bgColor); return gameObject; } public static Text CreateLabel(GameObject parent, string name, string defaultText, TextAnchor alignment = TextAnchor.MiddleLeft, Color color = default(Color), bool supportRichText = true, int fontSize = 14) { GameObject gameObject = CreateUIObject(name, parent); Text text = gameObject.AddComponent(); SetDefaultTextValues(text); text.text = defaultText; text.color = ((color == default(Color)) ? defaultTextColor : color); text.supportRichText = supportRichText; text.alignment = alignment; text.fontSize = fontSize; return text; } public static ButtonRef CreateButton(GameObject parent, string name, string text, Color? normalColor = null) { Color valueOrDefault = normalColor.GetValueOrDefault(); if (!normalColor.HasValue) { valueOrDefault = new Color(0.25f, 0.25f, 0.25f); normalColor = valueOrDefault; } ButtonRef buttonRef = CreateButton(parent, name, text, default(ColorBlock)); RuntimeHelper.Instance.Internal_SetColorBlock(buttonRef.Component, normalColor, normalColor * 1.2f, normalColor * 0.7f); return buttonRef; } public static ButtonRef CreateButton(GameObject parent, string name, string text, ColorBlock colors) { GameObject gameObject = CreateUIObject(name, parent, smallElementSize); GameObject gameObject2 = CreateUIObject("Text", gameObject); Image image = gameObject.AddComponent(); image.type = Image.Type.Sliced; image.color = new Color(1f, 1f, 1f, 1f); Button button = gameObject.AddComponent