Decompiled source of Editor Expanded v1.0.0
EditorExpanded.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Events; using Events.Stunt; using HarmonyLib; using LevelEditorTools; using Newtonsoft.Json; using Serializers; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("EditorExpanded")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EditorExpanded")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("a5276705-fc20-4b5d-b06a-173f5528845c")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] public static class LevelEditorExtensions { public static void ClearAndSelect(this LevelEditor editor, GameObject prefab) { editor.ClearSelectedList(true); editor.SelectObject(prefab); } } namespace EditorExpanded { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class EditorToolAttribute : Attribute { } public static class EditorUtil { public static Dictionary<ToolCategory, int> CategorySort = new Dictionary<ToolCategory, int>(); public static Dictionary<int, GameObject> QuickSelectMemory = new Dictionary<int, GameObject>(); public static void SetQuickMemory(int index, GameObject instance) { QuickSelectMemory[index] = instance; } public static GameObject GetQuickMemory(int index) { if (QuickSelectMemory.ContainsKey(index)) { return QuickSelectMemory[index]; } return null; } public static void ClearQuickMemory() { QuickSelectMemory.Clear(); } public static void Inspect(GameObject Target) { NGUIObjectInspectorTab val = Object.FindObjectOfType<NGUIObjectInspectorTab>(); LevelEditor levelEditor_ = G.Sys.LevelEditor_; if (Object.op_Implicit((Object)(object)levelEditor_) && Object.op_Implicit((Object)(object)val)) { levelEditor_.ClearOutlines(); levelEditor_.SelectedObjects_.Clear(); levelEditor_.SelectedObjects_.Add(Target); levelEditor_.AddOutline(Target); levelEditor_.UpdateOutlines(); levelEditor_.activeObject_ = Target; ((NGUIObjectInspectorTabAbstract)val).targetObject_ = Target; ((NGUIObjectInspectorTabAbstract)val).ClearComponentInspectors(); ((NGUIObjectInspectorTabAbstract)val).InitComponentInspectorsOnTargetObject(); val.InitAddComponentButton(); val.propertiesNeedToBeUpdated_ = false; val.objectNameLabel_.text = GameObjectEx.GetDisplayName(((NGUIObjectInspectorTabAbstract)val).targetObject_); } } public static void InspectRoot() { LevelEditor levelEditor_ = G.Sys.LevelEditor_; GameObject activeObject_ = levelEditor_.activeObject_; if (Object.op_Implicit((Object)(object)levelEditor_) && Object.op_Implicit((Object)(object)activeObject_)) { Inspect(GameObjectEx.Root(activeObject_)); levelEditor_.ClearSelectedList(true); levelEditor_.SelectObject(GameObjectEx.Root(activeObject_)); } } public static bool IsSelectionRoot() { GameObject activeObject_ = G.Sys.LevelEditor_.activeObject_; if (Object.op_Implicit((Object)(object)activeObject_)) { return TransformExtensionOnly.IsRoot(activeObject_.transform); } return true; } public static void PrintToolInspectionStackError() { MessageBox.Create("You can't run this tool while inspecting a group stack.\nPlease select a root level object.", "ERROR").SetButtons((ButtonType)0).Show(); } } public class FileSystem { public string RootDirectory { get; } public string VirtualFileSystemRoot => Path.Combine(RootDirectory, "Data"); public FileSystem() { RootDirectory = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location); if (!Directory.Exists(VirtualFileSystemRoot)) { Directory.CreateDirectory(VirtualFileSystemRoot); } } public bool FileExists(string path) { string path2 = Path.Combine(VirtualFileSystemRoot, path); return File.Exists(path2); } public bool DirectoryExists(string path) { string path2 = Path.Combine(VirtualFileSystemRoot, path); return Directory.Exists(path2); } public bool PathExists(string path) { return FileExists(path) || DirectoryExists(path); } public byte[] ReadAllBytes(string filePath) { string text = Path.Combine(VirtualFileSystemRoot, filePath); if (!File.Exists(text)) { Mod.Log.LogInfo((object)("Couldn't read a file for path '" + text + "'. File does not exist.")); return null; } return File.ReadAllBytes(text); } public FileStream CreateFile(string filePath, bool overwrite = false) { string text = Path.Combine(VirtualFileSystemRoot, filePath); if (File.Exists(text)) { if (!overwrite) { Mod.Log.LogInfo((object)("Couldn't create a mod VFS file for path '" + text + "'. The file already exists.")); return null; } Mod.Log.LogInfo((object)("Couldn't delete a mod VFS file for path '" + text + "'. File does not exist.")); RemoveFile(filePath); } try { return File.Create(text); } catch (Exception ex) { Mod.Log.LogInfo((object)("Couldn't create a mod VFS file for path '" + text + "'.")); Mod.Log.LogInfo((object)ex); return null; } } public void RemoveFile(string filePath) { string text = Path.Combine(VirtualFileSystemRoot, filePath); if (!File.Exists(text)) { Mod.Log.LogInfo((object)("Couldn't delete a mod VFS file for path '" + text + "'. File does not exist.")); return; } try { File.Delete(text); } catch (Exception ex) { Mod.Log.LogInfo((object)("Couldn't delete a mod VFS file for path '" + text + "'.")); Mod.Log.LogInfo((object)ex); } } public void IterateOver(string directoryPath, Action<string, bool> action, bool sort = true) { string text = Path.Combine(VirtualFileSystemRoot, directoryPath); if (!Directory.Exists(text)) { Mod.Log.LogInfo((object)("Cannot iterate over directory at '" + text + "'. It doesn't exist.")); return; } List<string> list = Directory.GetFiles(text).ToList(); list.AddRange(Directory.GetDirectories(text)); if (sort) { list = list.OrderBy((string x) => x).ToList(); } foreach (string item in list) { try { bool arg = Directory.Exists(item); action(item, arg); } catch (Exception ex) { Mod.Log.LogInfo((object)("Action for the element at path '" + item + "' failed. See file system exception log for details.")); Mod.Log.LogInfo((object)ex); break; } } } public List<string> GetDirectories(string directoryPath, string searchPattern) { string text = Path.Combine(VirtualFileSystemRoot, directoryPath); if (!Directory.Exists(text)) { Mod.Log.LogInfo((object)("Cannot get directories in directory at '" + text + "'. It doesn't exist.")); return null; } return Directory.GetDirectories(text, searchPattern).ToList(); } public List<string> GetDirectories(string directoryPath) { return GetDirectories(directoryPath, "*"); } public List<string> GetFiles(string directoryPath, string searchPattern) { string text = Path.Combine(VirtualFileSystemRoot, directoryPath); if (!Directory.Exists(text)) { Mod.Log.LogInfo((object)("Cannot get files in directory at '" + text + "'. It doesn't exist.")); return null; } return Directory.GetFiles(text, searchPattern).ToList(); } public List<string> GetFiles(string directoryPath) { return GetFiles(directoryPath, "*"); } public FileStream OpenFile(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) { string text = Path.Combine(VirtualFileSystemRoot, filePath); if (!File.Exists(text)) { Mod.Log.LogInfo((object)("Couldn't open a VFS file. The requested file: '" + text + "' does not exist.")); return null; } try { return File.Open(text, fileMode, fileAccess, fileShare); } catch (Exception ex) { Mod.Log.LogInfo((object)("Couldn't open a VFS file for path '" + text + "'.")); Mod.Log.LogInfo((object)ex); return null; } } public FileStream OpenFile(string filePath) { return OpenFile(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); } public string CreateDirectory(string directoryName) { string text = Path.Combine(VirtualFileSystemRoot, directoryName); try { Directory.CreateDirectory(text); return text; } catch (Exception ex) { Mod.Log.LogInfo((object)("Couldn't create a VFS directory for path '" + text + "'.")); Mod.Log.LogInfo((object)ex); return string.Empty; } } public void RemoveDirectory(string directoryPath) { string text = Path.Combine(VirtualFileSystemRoot, directoryPath); if (!Directory.Exists(text)) { Mod.Log.LogInfo((object)("Couldn't remove a VFS directory for path '" + text + "'. Directory does not exist.")); return; } try { Directory.Delete(text, recursive: true); } catch (Exception ex) { Mod.Log.LogInfo((object)("Couldn't remove a VFS directory for path '" + text + "'.")); Mod.Log.LogInfo((object)ex); } } public static string GetValidFileName(string dirtyFileName, string replaceInvalidCharsWith = "_") { return Regex.Replace(dirtyFileName, "[^\\w\\s\\.]", replaceInvalidCharsWith, RegexOptions.None); } public static string GetValidFileNameToLower(string dirtyFileName, string replaceInvalidCharsWith = "_") { return GetValidFileName(dirtyFileName, replaceInvalidCharsWith).ToLower(); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class KeyboardShortcutAttribute : Attribute { public InputEvent SchemeA { get; } public InputEvent SchemeB { get; } public KeyboardShortcutAttribute(string A) { SchemeA = (SchemeB = InputEvent.Create(A)); } public KeyboardShortcutAttribute(string A, string B) { SchemeA = InputEvent.Create(A); SchemeB = InputEvent.Create(B); } public InputEvent Get(char scheme) { return (InputEvent)(scheme switch { 'A' => SchemeA, 'B' => SchemeB, _ => null, }); } } public sealed class MessageBox { private readonly string Message = ""; private readonly string Title = ""; private float Time = 0f; private ButtonType Buttons = (ButtonType)0; private Action Confirm; private Action Cancel; private MessageBox(string message, string title) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) Message = message; Title = title; Confirm = EmptyAction; Cancel = EmptyAction; } public static MessageBox Create(string content, string title = "") { return new MessageBox(content, title); } public MessageBox SetButtons(ButtonType buttons) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) Buttons = buttons; return this; } public MessageBox SetTimeout(float delay) { Time = delay; return this; } public MessageBox OnConfirm(Action action) { Confirm = action; return this; } public MessageBox OnCancel(Action action) { Cancel = action; return this; } public void Show() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_0042: Expected O, but got Unknown G.Sys.MenuPanelManager_.ShowMessage(Message, Title, (OnButtonClicked)delegate { Confirm(); }, (OnButtonClicked)delegate { Cancel(); }, Buttons, false, (Pivot)4, Time); } private void EmptyAction() { } } [BepInPlugin("Distance.EditorExpanded", "Editor Expanded", "1.0.0")] public class Mod : BaseUnityPlugin { private const string modGUID = "Distance.EditorExpanded"; private const string modName = "Editor Expanded"; private const string modVersion = "1.0.0"; public static string DevFolderKey = "Enable Dev Folder"; public static string AdvancedMusicSelectionKey = "Advanced Music Selection"; public static string DisplayWorkshopKey = "Display Workshop Levels"; public static string EditorIconKey = "Editor Icon Size"; public static string EnableGroupKey = "Enable Group Centerpoint Mover"; public static string UnlimitedMedalKey = "Unlimited Medal Times"; public static string RemoveLimitsKey = "Remove Editor Number Limits"; public static string RemoveRequirementsKey = "Remove Mode Requirements"; public static string MultipleCarKey = "Multiple Car Spawners"; public static string HiddenFolderKey = "Enable Hidden Folder"; public static string UnlimitedComponentKey = "Unlimited Add Component"; public static string AllChangeTrackKey = "Change Track Type Includes All Splines"; public static string SubTextureKey = "Enable Sub Materials"; public static string EditorPrecisionKey = "Decimal Precision"; public static string CursorBackgroundKey = "Cursor Ignores Background Layer"; public static string EnableHiddenComponentKey = "Enable Hidden Components"; public static string RemoveCreatorKey = "Remove Level Creator Field"; public static string EnableAllModesKey = "Enable All Modes"; private static readonly Harmony harmony = new Harmony("Distance.EditorExpanded"); public static ManualLogSource Log = new ManualLogSource("Editor Expanded"); public static Mod Instance; public static ConfigEntry<bool> DevFolderEnabled { get; set; } public static ConfigEntry<bool> AdvancedMusicSelection { get; set; } public static ConfigEntry<bool> DisplayWorkshopLevels { get; set; } public static ConfigEntry<float> EditorIconSize { get; set; } public static ConfigEntry<bool> EnableGroupCenterMover { get; set; } public static ConfigEntry<bool> UnlimitedMedalTimes { get; set; } public static ConfigEntry<bool> RemoveNumberLimits { get; set; } public static ConfigEntry<bool> RemoveModeRequirements { get; set; } public static ConfigEntry<bool> MultipleCarSpawners { get; set; } public static ConfigEntry<bool> HiddenFolderEnabled { get; set; } public static ConfigEntry<bool> UnlimitedAddComponent { get; set; } public static ConfigEntry<bool> IncludeAllSplinesInChangeTrackType { get; set; } public static ConfigEntry<bool> EnableSubTextures { get; set; } public static ConfigEntry<int> EditorDecimalPrecision { get; set; } public static ConfigEntry<bool> CursorIgnoresBackground { get; set; } public static ConfigEntry<bool> EnableHiddenComponent { get; set; } public static ConfigEntry<bool> RemoveCreatorField { get; set; } public static ConfigEntry<bool> EnableAllModes { get; set; } public static bool DevMode => IsCommandLineSwitchPresent("-dev"); public static bool DevBuildForCreatorName { get; set; } public TrackNodeColors TrackNodeColors { get; set; } public static bool IsCommandLineSwitchPresent(string item) { return (from arg in Environment.GetCommandLineArgs() select arg.ToLower()).Contains(item); } private void Awake() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Expected O, but got Unknown //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Expected O, but got Unknown //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Expected O, but got Unknown //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected O, but got Unknown //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Expected O, but got Unknown //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Expected O, but got Unknown //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Expected O, but got Unknown //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Expected O, but got Unknown //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Expected O, but got Unknown //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Expected O, but got Unknown //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Expected O, but got Unknown //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Expected O, but got Unknown //IL_0355: Unknown result type (might be due to invalid IL or missing references) //IL_035f: Expected O, but got Unknown //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; } Log = Logger.CreateLogSource("Distance.EditorExpanded"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Thanks for using Editor Expanded!"); TrackNodeColors = TrackNodeColors.FromSettings("SplineColors.json"); TrackNodeColors.OnFileReloaded += ReloadTrackNodeColors; DevFolderEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", DevFolderKey, true, new ConfigDescription("Enables the Dev folder in the level editor Library tab.\nSome of the objects in this folder might not work properly, be careful when using them!", (AcceptableValueBase)null, new object[0])); RemoveNumberLimits = ((BaseUnityPlugin)this).Config.Bind<bool>("General", RemoveLimitsKey, true, new ConfigDescription("Removes number limits from the editor. This will allow negative values for many settings. Be sure to get test the level in sprint mode. Some values do not get interpreted properly.", (AcceptableValueBase)null, new object[0])); EnableGroupCenterMover = ((BaseUnityPlugin)this).Config.Bind<bool>("General", EnableGroupKey, true, new ConfigDescription("Enables the group centerpoint mover option.", (AcceptableValueBase)null, new object[0])); AdvancedMusicSelection = ((BaseUnityPlugin)this).Config.Bind<bool>("General", AdvancedMusicSelectionKey, true, new ConfigDescription("Display hidden dev music cues in the level editor music selector window.", (AcceptableValueBase)null, new object[0])); DisplayWorkshopLevels = ((BaseUnityPlugin)this).Config.Bind<bool>("General", DisplayWorkshopKey, false, new ConfigDescription("Allows to open the workshop levels from the level editor (read only).", (AcceptableValueBase)null, new object[0])); IncludeAllSplinesInChangeTrackType = ((BaseUnityPlugin)this).Config.Bind<bool>("General", AllChangeTrackKey, true, new ConfigDescription("All splines are now included in the Change Track Type tool", (AcceptableValueBase)null, new object[0])); EnableSubTextures = ((BaseUnityPlugin)this).Config.Bind<bool>("General", SubTextureKey, false, new ConfigDescription("Now displays sub textures in the properties menu for objects. This is good for coloring individual parts of an object you couldn't before.", (AcceptableValueBase)null, new object[0])); CursorIgnoresBackground = ((BaseUnityPlugin)this).Config.Bind<bool>("General", CursorBackgroundKey, false, new ConfigDescription("The Level Editor Cursor will no longer collide with background objects.", (AcceptableValueBase)null, new object[0])); EditorDecimalPrecision = ((BaseUnityPlugin)this).Config.Bind<int>("General", EditorPrecisionKey, 3, new ConfigDescription("Sets the precision of decimals displayed in the editor. Range 0-10.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), new object[0])); EnableHiddenComponent = ((BaseUnityPlugin)this).Config.Bind<bool>("General", EnableHiddenComponentKey, false, new ConfigDescription("Enables the visibility of components that normally are ignored. The box trigger on a killgridbox for example.", (AcceptableValueBase)null, new object[0])); UnlimitedMedalTimes = ((BaseUnityPlugin)this).Config.Bind<bool>("General", UnlimitedMedalKey, false, new ConfigDescription("Uncaps the medal time limit and allows any time to be set. So for example, a diamond medal can have a lower time than a bronze medal.", (AcceptableValueBase)null, new object[0])); UnlimitedAddComponent = ((BaseUnityPlugin)this).Config.Bind<bool>("General", UnlimitedComponentKey, false, new ConfigDescription("Allows components to be added to any object. \nWARNING: This can create very strange behaviour with certain objects, test the level in arcade mode to make sure it works!", (AcceptableValueBase)null, new object[0])); RemoveCreatorField = ((BaseUnityPlugin)this).Config.Bind<bool>("General", RemoveCreatorKey, false, new ConfigDescription("Disables the visibility of the Level Creator Name field in the level settings. This field is only used by Official tier community levels.", (AcceptableValueBase)null, new object[0])); RemoveModeRequirements = ((BaseUnityPlugin)this).Config.Bind<bool>("General", RemoveRequirementsKey, false, new ConfigDescription("Removes the requirements needed to save a level. \nRemember to playtest your level in arcade mode before uploading to the workshop.", (AcceptableValueBase)null, new object[0])); MultipleCarSpawners = ((BaseUnityPlugin)this).Config.Bind<bool>("General", MultipleCarKey, false, new ConfigDescription("Allows the use of multiple Level Editor Car Spawners as well as multiple Tag Bubbles. The extra ones are unused by the game if placed.", (AcceptableValueBase)null, new object[0])); EnableAllModes = ((BaseUnityPlugin)this).Config.Bind<bool>("General", EnableAllModesKey, false, new ConfigDescription("Allows all modes to be visible in the Level Settings menu. Modes outside of Sprint, Challenge, Stunt, Reverse Tag, and Trackmogrify are unplayable. \nIt might be a good idea to keep this disabled.", (AcceptableValueBase)null, new object[0])); HiddenFolderEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", HiddenFolderKey, false, new ConfigDescription("Adds a folder to titled \"Hidden\" to the editor that contains objects not listed anywhere; including the dev folder. \nWARNING: These objects are not meant to be editor objects, they may corrupt level files or crash the game.", (AcceptableValueBase)null, new object[0])); EditorIconSize = ((BaseUnityPlugin)this).Config.Bind<float>("General", EditorIconKey, 67f, new ConfigDescription("Adjusts the size of editor icons in the Library tab. \nThis value should be adjusted from the zoom slider in the library tab, not in this menu.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(32f, 256f), new object[0])); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Loading..."); harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded!"); } private void OnConfigChanged(object sender, EventArgs e) { SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null); if (val != null) { } } private void ReloadTrackNodeColors(object sender, EventArgs e) { TrackManipulatorNode[] array = Object.FindObjectsOfType<TrackManipulatorNode>(); foreach (TrackManipulatorNode val in array) { val.SetColorAndMesh(); } } public static bool CheckWhichIsHiddenFolder(LevelPrefabFileInfo info) { if ((PrimitiveEx.IsNullOrWhiteSpace(info.name_) ? "null" : info.name_).Equals("Hidden")) { return true; } return false; } } public class TrackNodeColors { [Serializable] private class Data { [JsonProperty("spline_colors")] public Dictionary<string, JsonColor> spline_colors = new Dictionary<string, JsonColor>(); } [Serializable] public class JsonColor { public const string TYPE_HEX = "hex"; public const string TYPE_RGB = "rgb"; public const string TYPE_HSB = "hsb"; public const string TYPE_COPY = "copy"; [JsonProperty(/*Could not decode attribute arguments.*/)] public string type = "hex"; [JsonProperty("hex")] public string hex = ""; [JsonProperty("from")] public string from = ""; [JsonProperty("hue")] public int hue = 0; [JsonProperty("saturation")] public float saturation = 0.8f; [JsonProperty("brightness")] public float brightness = 1f; [JsonProperty("red")] public int red = 128; [JsonProperty("green")] public int green = 128; [JsonProperty("blue")] public int blue = 128; public Color ToColor() { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) switch (type.ToLower()) { case "hex": return ColorEx.HexToColor(hex, byte.MaxValue); case "rgb": return new Color((float)red / 255f, (float)green / 255f, (float)blue / 255f, 1f); case "hsb": { ColorHSB val = new ColorHSB((float)hue / 360f, saturation, brightness, 1f); return ((ColorHSB)(ref val)).ToColor(); } default: throw new NotSupportedException("Color type \"" + type + "\" not supported, valid values are: hex, rgb and hsb"); } } public static implicit operator Color(JsonColor col) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return col.ToColor(); } } public const char ITEM_DELIMITER = '/'; public readonly FileInfo file; private FileSystemWatcher watcher; private Data data; private Dictionary<string, Color> splineColors; private Dictionary<Regex, Color> keyRegexList; public Color? this[string key] { get { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) string key2 = key.ToLower(); if (string.IsNullOrEmpty(key)) { return null; } if (splineColors.ContainsKey(key2)) { return splineColors[key2]; } foreach (KeyValuePair<Regex, Color> keyRegex in keyRegexList) { if (keyRegex.Key.IsMatch(key)) { return keyRegex.Value; } } return null; } } public event EventHandler OnFileReloaded; public TrackNodeColors(string fileName) : this(new FileInfo(fileName)) { } public TrackNodeColors(FileInfo file) { this.file = file; MakeWatcher(); LoadData(); } public static TrackNodeColors FromFile(string fileName) { return new TrackNodeColors(fileName); } public static TrackNodeColors FromFile(FileInfo file) { return new TrackNodeColors(file); } public static TrackNodeColors FromSettings(string settingsFileName) { FileSystem fileSystem = new FileSystem(); DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(fileSystem.RootDirectory, "Settings")); if (!directoryInfo.Exists) { directoryInfo.Create(); } string fullName = new FileInfo(Path.Combine(directoryInfo.FullName, settingsFileName)).FullName; return new TrackNodeColors(fullName); } private void MakeWatcher() { watcher = new FileSystemWatcher(file.Directory.FullName, file.Name) { EnableRaisingEvents = true }; watcher.Changed += OnFileChanged; } private void OnFileChanged(object sender, FileSystemEventArgs e) { if (string.Equals(e.FullPath, file.FullName, StringComparison.InvariantCultureIgnoreCase)) { Mod.Log.LogWarning((object)("Reloading file " + file.FullName)); LoadData(); this.OnFileReloaded?.Invoke(this, EventArgs.Empty); } } private void LoadData() { //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) data = GetOrCreate(file, new Data()); Mod.Log.LogInfo((object)"Loading data"); splineColors = new Dictionary<string, Color>(); keyRegexList = new Dictionary<Regex, Color>(); HashSet<string> hashSet = new HashSet<string>(); Dictionary<string, JsonColor> dictionary = new Dictionary<string, JsonColor>(); foreach (KeyValuePair<string, JsonColor> spline_color in data.spline_colors) { JsonColor value = spline_color.Value; if (string.Equals(value.type, "copy", StringComparison.InvariantCultureIgnoreCase)) { if (data.spline_colors.ContainsKey(value.from)) { dictionary.Add(spline_color.Key, data.spline_colors[value.from]); } else { hashSet.Add(spline_color.Key); } } } CollectionExtensions.Do<string>((IEnumerable<string>)hashSet, (Action<string>)delegate(string key) { data.spline_colors.Remove(key); }); foreach (KeyValuePair<string, JsonColor> item in dictionary) { data.spline_colors.Remove(item.Key); data.spline_colors.Add(item.Key, item.Value); } foreach (KeyValuePair<string, JsonColor> spline_color2 in data.spline_colors) { try { string[] array = spline_color2.Key.Split(new char[1] { '/' }); Array.Sort(array); string key2 = string.Join(string.Empty, array).ToLower(); Color val = spline_color2.Value; splineColors.Add(key2, val); keyRegexList.Add(new Regex(spline_color2.Key), val); Mod.Log.LogInfo((object)(spline_color2.Key + " (" + ColorEx.ColorToHexUnity(Color32.op_Implicit(val)) + ")")); } catch (Exception ex) { Mod.Log.LogInfo((object)ex); Mod.Log.LogError((object)("Could not read color data for spline_color \"" + spline_color2.Key + "\"")); } } } public static void Save<TYPE>(string file, TYPE data, bool overwrite = true) { Save(new FileInfo(file), data, overwrite); } public static void Save<TYPE>(FileInfo file, TYPE data, bool overwrite = true) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown if (file.Exists) { if (!overwrite) { throw new Exception("File already exists: " + file.FullName); } file.Delete(); } JsonSerializer val = new JsonSerializer { NullValueHandling = (NullValueHandling)0 }; using StreamWriter streamWriter = new StreamWriter(file.FullName); JsonWriter val2 = (JsonWriter)new JsonTextWriter((TextWriter)streamWriter) { Formatting = (Formatting)1 }; try { val.Serialize(val2, (object)data); } finally { ((IDisposable)val2)?.Dispose(); } } public static TYPE Load<TYPE>(string file) where TYPE : new() { return Load<TYPE>(new FileInfo(file)); } public static TYPE Load<TYPE>(string file, TYPE @default) where TYPE : new() { return Load(new FileInfo(file), @default); } public static TYPE Load<TYPE>(FileInfo file) where TYPE : new() { return Load(file, new TYPE()); } public static TYPE Load<TYPE>(FileInfo file, TYPE @default) where TYPE : new() { if (file.Exists) { try { using StreamReader streamReader = new StreamReader(file.FullName); return JsonConvert.DeserializeObject<TYPE>(streamReader.ReadToEnd()); } catch (Exception) { return @default; } } return @default; } public static TYPE GetOrCreate<TYPE>(string file, TYPE @default) where TYPE : new() { return GetOrCreate(new FileInfo(file), @default); } public static TYPE GetOrCreate<TYPE>(FileInfo file, TYPE @default) where TYPE : new() { if (!file.Exists) { Save(file, @default); } return Load<TYPE>(file); } } } namespace EditorExpanded.Patches { [HarmonyPatch(typeof(Set), "ShouldBeIgnored")] internal static class DontInspectComponentsSet__ShouldBeIgnored { [HarmonyPostfix] internal static void Postfix(ref bool __result, Component comp) { if (Mod.EnableHiddenComponent.Value) { if ((Object)(object)comp == (Object)null) { __result = true; } else { __result = false; } } } } [HarmonyPatch(typeof(GameManager), "GetModeShowInLevelEditor")] internal static class GameManager__GetModeShowInLevelEditor { [HarmonyPostfix] internal static void Postfix(ref bool __result, GameModeID ID) { if (Mod.EnableAllModes.Value) { __result = true; } } } [HarmonyPatch(typeof(AddAnimatedComponentTool), "ValidateObject")] internal static class AddAnimatedComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddAnimatorAudioComponentTool), "ValidateObject")] internal static class AddAnimatorAudioComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddAnimatorCameraShakeComponentTool), "ValidateObject")] internal static class AddAnimatorCameraShakeComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddComponentTool<AddedComponent>), "Run")] internal static class AddComponentTool__Run { [HarmonyPrefix] internal static bool Prefix(ref bool __result) { if (!EditorUtil.IsSelectionRoot()) { EditorUtil.PrintToolInspectionStackError(); __result = false; return false; } return true; } } [HarmonyPatch(typeof(AddEngageBrokenPiecesComponentTool), "ValidateObject")] internal static class AddEngageBrokenPiecesComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddExcludeFromEMPComponentTool), "ValidateObject")] internal static class AddExcludeFromEMPComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddFadeOutComponentTool), "ValidateObject")] internal static class AddFadeOutComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddGoldenAnimatorComponentTool), "ValidateObject")] internal static class AddGoldenAnimatorComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddIgnoreInCullGroupsComponentTool), "ValidateObject")] internal static class AddIgnoreInCullGroupsComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddLookAtCameraComponentTool), "ValidateObject")] internal static class AddLookAtCameraComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddPulseAllComponentTool), "ValidateObject")] internal static class AddPulseAllComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddSetActiveAfterWarpComponentTool), "ValidateObject")] internal static class AddSetActiveAfterWarpComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddShowDuringGlitchComponentTool), "ValidateObject")] internal static class AddShowDuringGlitchComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddTurnLightOnNearCarComponentTool), "ValidateObject")] internal static class AddTurnLightOnNearCarComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(AddZEventListenerComponentTool), "ValidateObject")] internal static class AddZEventListenerComponentTool__ValidateObject { [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (Mod.UnlimitedAddComponent.Value) { __result = true; } } } [HarmonyPatch(typeof(ChangeLayerTool), "OnSelectLayer")] internal static class ChangeLayerTool__OnSelectLayer { [HarmonyPrefix] internal static bool Prefix(ChangeLayerTool __instance) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!EditorUtil.IsSelectionRoot()) { EditorUtil.PrintToolInspectionStackError(); __instance.state_ = (ToolState)3; return false; } return true; } } [HarmonyPatch(typeof(ChangeTrackTypeTool), "Start")] internal static class ChangeTrackTypeTool__Start { [HarmonyPostfix] internal static void Postfix() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_055d: Unknown result type (might be due to invalid IL or missing references) //IL_0573: Unknown result type (might be due to invalid IL or missing references) //IL_0589: Unknown result type (might be due to invalid IL or missing references) //IL_059f: Unknown result type (might be due to invalid IL or missing references) //IL_07e3: Unknown result type (might be due to invalid IL or missing references) //IL_07f9: Unknown result type (might be due to invalid IL or missing references) //IL_080f: Unknown result type (might be due to invalid IL or missing references) //IL_0825: Unknown result type (might be due to invalid IL or missing references) if (Mod.IncludeAllSplinesInChangeTrackType.Value) { ChangeTrackTypeTool.roadEntries_ = new KeyValuePair<string, string>[34] { ChangeTrackTypeTool.Folder("Roads", ChangeTrackTypeTool.selectedFolderColor_), ChangeTrackTypeTool.Folder("Shapes", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Decorations", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Utility", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.KVP("Ancient Road", "SplineRoad"), ChangeTrackTypeTool.KVP("Ancient Road Sideless", "AncientSidelessRoad"), ChangeTrackTypeTool.KVP("Empire Road", "EmpireSplineRoad"), ChangeTrackTypeTool.KVP("Empire Road Sideless", "EmpireSplineRoadSideless"), ChangeTrackTypeTool.KVP("Glass Road", "GlassSplineRoad"), ChangeTrackTypeTool.KVP("Glass Road 2", "GlassSplineRoad002"), ChangeTrackTypeTool.KVP("Glass Road Sideless", "GlassSplineRoadSideless"), ChangeTrackTypeTool.KVP("Glass Road Sideless 2", "GlassSplineRoadSideless002"), ChangeTrackTypeTool.KVP("Virus Road", "VirusSplineRoad"), ChangeTrackTypeTool.KVP("Virus Road Sideless", "VirusSplineSidelessRoad"), ChangeTrackTypeTool.KVP("Nitronic Road", "NitronicSplineRoadStraight"), ChangeTrackTypeTool.KVP("Nitronic Sideless Road", "NitronicSidelessSplineRoadStraight 1"), ChangeTrackTypeTool.KVP("Nitronic Glass Road", "NitronicGlassSplineRoadStraight"), ChangeTrackTypeTool.KVP("Nitronic Glass Sideless Road", "NitronicGlassSidelessSplineRoadStraight"), ChangeTrackTypeTool.KVP("Nitronic Core Road", "NitronicCorePanelSidelessSplineRoadStraight"), ChangeTrackTypeTool.KVP("Nitronic Platform Road", "NitronicPlatformPiece"), ChangeTrackTypeTool.KVP("Golden Road", "SplineRoadSimple"), ChangeTrackTypeTool.KVP("Golden Tunnel", "TunnelFlat"), ChangeTrackTypeTool.KVP("Empire Transit Wall", "EmpireTransitWall"), ChangeTrackTypeTool.KVP("Empire Transit Window 1", "EmpireTransitWindow001"), ChangeTrackTypeTool.KVP("Empire Transit Window 2", "EmpireTransitWindow002"), ChangeTrackTypeTool.KVP("Empire Transit Half Wall", "EmpireTransitHalfWall"), ChangeTrackTypeTool.KVP("Empire Transit Half Window", "EmpireTransitHalfWindow"), ChangeTrackTypeTool.KVP("Empire Pipe Tunnel", "EmpirePipeTunnel"), ChangeTrackTypeTool.KVP("Empire Tunnel", "EmpireTunnel"), ChangeTrackTypeTool.KVP("Empire Tunnel 2", "EmpireTunnel2"), ChangeTrackTypeTool.KVP("Empire Tunnel 3", "EmpireTunnel3"), ChangeTrackTypeTool.KVP("Virus Tunnel", "VirusTunnel"), ChangeTrackTypeTool.KVP("Sky Islands Tunnel", "SkyIslandsTunnel01"), ChangeTrackTypeTool.KVP("Nitronic Tunnel", "NitronicEchoTunnel") }; ChangeTrackTypeTool.shapeEntries_ = new KeyValuePair<string, string>[24] { ChangeTrackTypeTool.Folder("Roads", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Shapes", ChangeTrackTypeTool.selectedFolderColor_), ChangeTrackTypeTool.Folder("Decorations", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Utility", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.KVP("Cylinder", "SplineCylinder"), ChangeTrackTypeTool.KVP("Hexagon", "SplineHexagon"), ChangeTrackTypeTool.KVP("Square", "SplineQuad"), ChangeTrackTypeTool.KVP("Scales", "SplineScales"), ChangeTrackTypeTool.KVP("Girder 2D", "SplineGirder2D"), ChangeTrackTypeTool.KVP("Girder 3D", "SplineGirder3D"), ChangeTrackTypeTool.KVP("Golden Wires 1", "SplineWires1"), ChangeTrackTypeTool.KVP("Golden Wires 2", "SplineWirse2"), ChangeTrackTypeTool.KVP("Quarter Pipe", "SplineQPipe"), ChangeTrackTypeTool.KVP("40 Pipe", "Spline40Pipe"), ChangeTrackTypeTool.KVP("Half Pipe", "SplineHalfPipe"), ChangeTrackTypeTool.KVP("Quarter Tube", "SplineQTube"), ChangeTrackTypeTool.KVP("Half Tube", "SplineHalfTube"), ChangeTrackTypeTool.KVP("Tube", "SplineTube"), ChangeTrackTypeTool.KVP("Square Tube", "SplineQuadTube"), ChangeTrackTypeTool.KVP("Hexagon Tube", "SplineHexTube"), ChangeTrackTypeTool.KVP("Tape", "SplineTape"), ChangeTrackTypeTool.KVP("Cylinder HD", "SplineCylinderHD"), ChangeTrackTypeTool.KVP("Golden Road", "SplineRoadSimple"), ChangeTrackTypeTool.KVP("Golden Tunnel", "TunnelFlat") }; ChangeTrackTypeTool.decorationEntries_ = new KeyValuePair<string, string>[28] { ChangeTrackTypeTool.Folder("Roads", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Shapes", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Decorations", ChangeTrackTypeTool.selectedFolderColor_), ChangeTrackTypeTool.Folder("Utility", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.KVP("TrafficPlane", "TrafficPlane (Slow)"), ChangeTrackTypeTool.KVP("Traffic Plane (not slow)", "TrafficPlane"), ChangeTrackTypeTool.KVP("TrafficTube", "TrafficTube (Slow)"), ChangeTrackTypeTool.KVP("Traffic Tube (not slow)", "TrafficTube"), ChangeTrackTypeTool.KVP("Traffic Tube Plane", "TrafficTubePlane"), ChangeTrackTypeTool.KVP("Traffic Plane Nitronic", "TrafficPlaneNitronic"), ChangeTrackTypeTool.KVP("Wire", "ElectroPulseWire"), ChangeTrackTypeTool.KVP("Wire (Thick)", "ElectroPulseWireThick"), ChangeTrackTypeTool.KVP("Wire (Animated)", "ElectroPulseWireAnimated"), ChangeTrackTypeTool.KVP("Nitronic Wire 1", "NitronicSplineWire01"), ChangeTrackTypeTool.KVP("Nitronic Wire 2", "NitronicSplineWire02"), ChangeTrackTypeTool.KVP("Nitronic Wire 3", "NitronicSplineWire03"), ChangeTrackTypeTool.KVP("Nitronic Wire 4", "NitronicSplineWire04"), ChangeTrackTypeTool.KVP("Nitronic Wire 5", "NitronicSplineWire05"), ChangeTrackTypeTool.KVP("Nitronic Wire (Animated)", "Wire (Animated)"), ChangeTrackTypeTool.KVP("Vine Leaf High", "VineLeafHi"), ChangeTrackTypeTool.KVP("Vine Leaf Medium", "VineLeafMid"), ChangeTrackTypeTool.KVP("Vine Leaf Low", "VineLeafLow"), ChangeTrackTypeTool.KVP("Vine Leaf Sparse High", "VineLeafSparseHi"), ChangeTrackTypeTool.KVP("Vine Leaf Sparse Medium", "VineLeafSparseMid"), ChangeTrackTypeTool.KVP("Vine Leaf Sparse Low", "VineLeafSparseLow"), ChangeTrackTypeTool.KVP("Vine Leaf Stagger Low", "VineLeafStaggerLow"), ChangeTrackTypeTool.KVP("Halcyon Wall Edge Spline", "HalcyonWallEdgeSpline"), ChangeTrackTypeTool.KVP("Halcyon Wall Spline", "HalcyonWallSpline") }; ChangeTrackTypeTool.utilityEntries_ = new KeyValuePair<string, string>[6] { ChangeTrackTypeTool.Folder("Roads", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Shapes", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Decorations", ChangeTrackTypeTool.folderColor_), ChangeTrackTypeTool.Folder("Utility", ChangeTrackTypeTool.selectedFolderColor_), ChangeTrackTypeTool.KVP("Invisible Spline", "InvisibleSpline"), ChangeTrackTypeTool.KVP("Killgrid Spline", "KillGridSplineCylinder") }; } } } [HarmonyPatch(typeof(CreateCustomObjectTool), "Start")] internal static class CreateCustomObjectTool__Start { internal static bool Prefix() { if (!EditorUtil.IsSelectionRoot()) { EditorUtil.PrintToolInspectionStackError(); return false; } return true; } } [HarmonyPatch(typeof(CreditsNameOrbLogic), "Visit")] internal static class CreditsNameOrbLogic__Visit { [HarmonyPrefix] internal static bool Prefix(CreditsNameOrbLogic __instance, IVisitor visitor, ISerializable prefabComp, int version) { if (version != 0) { visitor.Visit("name_", ref __instance.name_, (string)null); if (visitor is ISerializer) { visitor.Visit("key_", ref __instance.key_, (string)null); visitor.Visit("linkedKey_", ref __instance.linkedKey_, (string)null); } } if (__instance.initialized_ || !G.Sys.GameManager_.IsLevelEditorMode_) { } return false; } } [HarmonyPatch(typeof(DeleteTool), "Run")] internal static class DeleteTool__Run { [HarmonyPrefix] internal static bool Prefix(ref bool __result) { if (!EditorUtil.IsSelectionRoot()) { EditorUtil.PrintToolInspectionStackError(); __result = false; return false; } return true; } } [HarmonyPatch(typeof(GameManager), "GetModeCheckRequirements")] internal static class GameManager__GetModeCheckRequirements { [HarmonyPrefix] internal static bool Prefix(ref CheckModeRequirements __result) { if (Mod.RemoveModeRequirements.Value) { __result = null; return false; } return true; } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class GameManager__IsDevBuild_get { internal static bool Prefix(ref bool __result) { if (Mod.DevMode) { __result = true; return false; } return true; } [HarmonyPostfix] internal static void Postfix(ref bool __result) { if (!Mod.RemoveCreatorField.Value) { if (Mod.DevBuildForCreatorName) { __result = true; } Mod.DevBuildForCreatorName = false; } } } [HarmonyPatch(typeof(GenerateTrackmogrifyLevelTool), "Finish")] internal static class GenerateTrackmogrifyLevelTool__Finish { [HarmonyPrefix] internal static void Prefix() { EditorUtil.ClearQuickMemory(); } } [HarmonyPatch(typeof(GroupTool), "Run")] internal static class GroupTool__Run { [HarmonyPrefix] internal static bool Prefix(ref bool __result) { if (!EditorUtil.IsSelectionRoot()) { EditorUtil.PrintToolInspectionStackError(); __result = false; return false; } return true; } } [HarmonyPatch(typeof(Group), "Visit")] internal static class Group__Visit { [HarmonyPrefix] internal static bool Prefix(Group __instance, IVisitor visitor) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) if (!(visitor is Serializer) && !(visitor is Deserializer)) { GameObject[] children = GameObjectEx.GetChildren(((Component)__instance).gameObject); if (children.Length == 0) { IVisitorEx.VisualLabel(visitor, NGUIEx.Colorize("No child objects found!", Color.white)); return false; } if (children.Length != 0) { IVisitorEx.VisualLabel(visitor, "Group Hierarchy"); int num = 1; GameObject[] array = children; foreach (GameObject Children in array) { string arg = ((Object)Children).name; if (GameObjectEx.HasComponent<CustomName>(Children)) { CustomName component = Children.GetComponent<CustomName>(); arg = NGUIEx.Colorize("[b]" + component.CustomName_ + "[/b]", Color.white); } IVisitorEx.VisitAction(visitor, $"Inspect {arg} (#{num})", (Action)delegate { EditorUtil.Inspect(Children); }, (string)null); num++; } } } return true; } [HarmonyPostfix] internal static void Postfix(Group __instance, IVisitor visitor, ISerializable prefabComp) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) if (Mod.EnableGroupCenterMover.Value && (Object)prefabComp == (Object)null) { Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(((Component)__instance).transform.localPosition.x, ((Component)__instance).transform.localPosition.y, ((Component)__instance).transform.localPosition.z); Quaternion rotation = default(Quaternion); ((Quaternion)(ref rotation))..ctor(((Component)__instance).transform.rotation.x, ((Component)__instance).transform.rotation.y, ((Component)__instance).transform.rotation.z, ((Component)__instance).transform.rotation.w); List<Vector3> list = new List<Vector3>(); List<Quaternion> list2 = new List<Quaternion>(); GameObject[] children = GameObjectEx.GetChildren(((Component)__instance).gameObject); foreach (GameObject val2 in children) { list.Add(val2.transform.position); list2.Add(val2.transform.rotation); } visitor.Visit("Centerpoint Position", ref val, (string)null); visitor.Visit("Centerpoint Rotation", ref rotation, (string)null); Vector3 val3 = val - ((Component)__instance).transform.localPosition; ((Component)__instance).transform.localPosition = ((Component)__instance).transform.localPosition + val3; ((Component)__instance).transform.rotation = rotation; int num = 0; GameObject[] children2 = GameObjectEx.GetChildren(((Component)__instance).gameObject); foreach (GameObject val4 in children2) { val4.transform.position = list.ToArray()[num]; val4.transform.rotation = list2.ToArray()[num]; num++; } __instance.localBounds_ = Group.CalculateBoundsFromImmediateChildren(__instance); } } } [HarmonyPatch(typeof(LevelEditorCarSpawner), "LevelEditorStartVirtual")] internal static class LevelEditorCarSpawner__LevelEditorStartVirtual { [HarmonyPrefix] internal static bool Prefix(LevelEditorCarSpawner __instance) { if (Mod.MultipleCarSpawners.Value) { LevelEditor levelEditor_ = G.Sys.LevelEditor_; foreach (LevelEditorCarSpawner item in levelEditor_.WorkingLevel_.FindComponentsOfType<LevelEditorCarSpawner>()) { if (item == __instance) { } } return false; } return true; } } [HarmonyPatch(typeof(LevelEditorLevelNameSelectMenuLogic), "GenerateLevelNameList")] internal static class LevelEditorLevelNameSelectMenuLogic__GenerateLevelNameList { [HarmonyPostfix] internal static void Postfix(LevelEditorLevelNameSelectMenuLogic __instance) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (Mod.DisplayWorkshopLevels.Value && !G.Sys.GameManager_.IsDevBuild_) { LevelSetsManager levelSets_ = G.Sys.LevelSets_; __instance.CreateButtons(levelSets_.LevelsLevelFilePaths_.ToList(), YellowColors.gold, (DisplayOption)0); __instance.CreateButtons(levelSets_.WorkshopLevelFilePaths_.ToList(), GConstants.communityLevelColor_, (DisplayOption)2); ((UIExButtonContainer)__instance.buttonList_).SortAndUpdateVisibleButtons(); } } } [HarmonyPatch(typeof(LevelEditorMusicTrackSelectMenuLogic), "GenerateMusicNameList")] internal static class LevelEditorMusicTrackSelectMenuLogic__GenerateMusicNameList { [HarmonyPostfix] internal static void Postfix(LevelEditorMusicTrackSelectMenuLogic __instance) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) if (!Mod.AdvancedMusicSelection.Value || G.Sys.GameManager_.IsDevBuild_) { return; } ((UIExButtonContainer)__instance.buttonList_).Clear(); List<MusicCue> musicCues_ = G.Sys.AudioManager_.MusicCues_; if (!Mod.AdvancedMusicSelection.Value) { musicCues_.RemoveAll((MusicCue x) => x.devEvent_); } __instance.CreateButtons(musicCues_, Color.white); ((UIExButtonContainer)__instance.buttonList_).SortAndUpdateVisibleButtons(); } } [HarmonyPatch(typeof(LevelEditor), "SelectObject")] internal static class LevelEditor__SelectObject { [HarmonyPrefix] internal static bool Prefix(LevelEditor __instance, ref bool __result, ref GameObject newObj) { if (newObj == null) { Mod.Log.LogWarning((object)"Trying to select a null object"); __result = false; return false; } if (TransformExtensionOnly.IsRoot(newObj.transform) && false) { Mod.Log.LogWarning((object)"Trying to select a child object"); __result = false; return false; } if (!__instance.selectedObjects_.Contains(newObj)) { LevelLayer layerOfObject = __instance.workingLevel_.GetLayerOfObject(newObj); if (layerOfObject != null && !layerOfObject.Frozen_) { __instance.AddObjectToSelectedList(newObj); __result = true; return false; } } else { __instance.SetActiveObject(newObj); } __result = false; return false; } } [HarmonyPatch(typeof(LevelEditor), "UpdateOutlines")] internal static class LevelEditor__UpdateOutlines { [HarmonyPrefix] internal static bool Prefix(LevelEditor __instance) { int count = __instance.selectedObjects_.List_.Count; if (count != __instance.outlines_.Count) { Mod.Log.LogInfo((object)$"Object Count: {count} Outline Count: {__instance.outlines_.Count}"); Mod.Log.LogInfo((object)"List of selected Objects: "); foreach (GameObject item in __instance.selectedObjects_.List_) { Mod.Log.LogInfo((object)((Object)item).name); } Debug.LogError((object)"Outlines Count is different than Selected Objects Count"); } else { for (int i = 0; i < count; i++) { __instance.UpdateOutlineColor(i); } } return false; } } [HarmonyPatch(typeof(LevelSettings), "GetDefaultModesMap")] internal static class LevelSettings__GetDefaultModesMap { [HarmonyPostfix] internal static void Postfix(ref Dictionary<int, bool> __result) { if (Mod.EnableAllModes.Value) { __result.Add(0, value: false); __result.Add(4, value: false); __result.Add(7, value: false); __result.Add(17, value: false); } } } [HarmonyPatch(typeof(LevelSettings), "MedalTimeSpanToString")] internal static class LevelSettings__MedalTimeSpanToString { [HarmonyPrefix] internal static bool Prefix(ref string __result, TimeSpan timeSpan) { if (Mod.UnlimitedMedalTimes.Value) { int num = timeSpan.Milliseconds / 10; __result = $"{timeSpan.Minutes + timeSpan.Hours * 60 + timeSpan.Days * 1440:00}:{timeSpan.Seconds:00}.{num:00}"; return false; } return true; } } [HarmonyPatch(typeof(LevelSettings), "MedalTimeSpanTryParse")] internal static class LevelSettings__MedalTimeSpanTryParse { [HarmonyPrefix] internal static bool Prefix(ref bool __result, string timeSpanStr, out TimeSpan span) { if (string.IsNullOrEmpty(timeSpanStr)) { span = TimeSpan.Zero; __result = false; return false; } if (timeSpanStr.StartsWith("-") || timeSpanStr.StartsWith("$") || timeSpanStr.StartsWith("I") || timeSpanStr.StartsWith("+")) { span = TimeSpan.Zero; __result = false; return false; } int num = timeSpanStr.IndexOf(':'); int num2 = timeSpanStr.LastIndexOf(':'); if (num == -1 || num != num2) { span = TimeSpan.Zero; __result = false; return false; } int num3 = timeSpanStr.IndexOf('.'); int num4 = timeSpanStr.LastIndexOf('.'); if (num3 == -1 || num3 != num4 || num3 < num || num == timeSpanStr.Length - 1) { span = TimeSpan.Zero; __result = false; return false; } if (!int.TryParse(timeSpanStr.Substring(0, num), out var result)) { span = TimeSpan.Zero; __result = false; return false; } if (!int.TryParse(timeSpanStr.Substring(num + 1, num3 - num - 1), out var result2)) { span = TimeSpan.Zero; __result = false; return false; } if (!int.TryParse(timeSpanStr.Substring(num3 + 1, Mathf.Min(timeSpanStr.Length - num3 - 1, 2)), out var result3)) { span = TimeSpan.Zero; __result = false; return false; } int minutes = result; result2 = Mathf.Min(Mathf.Max(result2, 0), 59); result3 = Mathf.Min(Mathf.Max(result3, 0), 99) * 10; span = new TimeSpan(0, 0, minutes, result2, result3); __result = true; return false; } } [HarmonyPatch(typeof(LevelSettings), "NGUIVisitMedalTime")] internal static class LevelSettings__NGUIVisitMedalTime { [HarmonyPrefix] internal static bool Prefix(ref LevelSettings __instance, IVisitor visitor, string timeName, ref float time) { if (Mod.UnlimitedMedalTimes.Value) { string text = ""; text = (float.IsNegativeInfinity(time) ? "-I" : (float.IsPositiveInfinity(time) ? "+I" : (float.IsNaN(time) ? "NaN" : ((!(time < 0f)) ? __instance.MedalTimeSpanToString(TimeSpan.FromMilliseconds(Mathf.Max(time, 0f))) : ("-" + __instance.MedalTimeSpanToString(TimeSpan.FromMilliseconds(Mathf.Abs(time)))))))); string text2 = text; visitor.Visit(timeName, ref text2, LevelSettings.medalTimeOptions_); TimeSpan timeSpan = default(TimeSpan); if (text2 != text && __instance.MedalTimeSpanTryParse(text2, ref timeSpan)) { time = ((timeSpan.TotalMilliseconds <= 0.0) ? 0f : ((float)timeSpan.TotalMilliseconds)); } else if (text2 != text && text2.StartsWith("-") && __instance.MedalTimeSpanTryParse(text2.Substring(1, text2.Length - 1), ref timeSpan)) { time = 0f - (float)timeSpan.TotalMilliseconds; } else if (text2 != text && text2.StartsWith("$") && text2.EndsWith("$") && text2.Length > 1) { try { time = float.Parse(text2.Substring(1, text2.Length - 2)); } catch { time = float.NaN; } } else if (text2 != text && (text2.StartsWith("I") || text2.StartsWith("+I"))) { time = float.PositiveInfinity; } else if (text2 != text && text2.StartsWith("-I")) { time = float.NegativeInfinity; } else if (text2 != text && text2.StartsWith("N")) { time = float.NaN; } return false; } return true; } } [HarmonyPatch(typeof(LevelSettings), "Visit")] internal static class LevelSettings__Visit { [HarmonyPrefix] internal static void Prefix(LevelSettings __instance, IVisitor visitor, ISerializable prefabComp, int version) { if (!Mod.RemoveCreatorField.Value) { Mod.DevBuildForCreatorName = true; } } } [HarmonyPatch(typeof(LibraryTab), "Start")] internal static class LibraryTab__Start { [HarmonyPrefix] internal static bool Prefix(LibraryTab __instance) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown ((UIProgressBar)__instance.iconSizeSlider_).onChange.Add(new EventDelegate((Callback)delegate { Mod.EditorIconSize.Value = __instance.IconSize_; })); __instance.iconSize_ = Mod.EditorIconSize.Value; __instance.rootFileData_ = G.Sys.ResourceManager_.LevelPrefabFileInfosRoot_; if (!Mod.DevFolderEnabled.Value && !G.Sys.GameManager_.IsDevBuild_) { __instance.rootFileData_.RemoveAllChildInfos((Predicate<LevelPrefabFileInfo>)((LevelPrefabFileInfo x) => x.IsDirectory_ && x.Name_ == "Dev")); } __instance.currentDirectory_ = __instance.rootFileData_; ((UIProgressBar)__instance.iconSizeSlider_).value = Mathf.InverseLerp(32f, 256f, __instance.iconSize_); __instance.searchInput_ = ((Component)__instance).GetComponentInChildren<UIExInput>(); ((MonoBehaviour)__instance).StartCoroutine(__instance.CreateIconsAfterAFrame()); return false; } } [HarmonyPatch(typeof(LoadLevelTool), "Update")] internal static class LoadLevelTool__Update { [HarmonyPrefix] internal static void Prefix() { EditorUtil.ClearQuickMemory(); } } [HarmonyPatch(typeof(NewLevelTool), "CreateNewLevel")] internal static class NewLevelTool__CreateNewLevel { [HarmonyPrefix] internal static void Prefix() { EditorUtil.ClearQuickMemory(); } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class MaterialWrapper__ComponentName_ { [HarmonyPostfix] internal static void Postfix(ref string __result, MaterialWrapper __instance) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (Mod.EnableSubTextures.Value) { __result = "Material: " + NGUIEx.Colorize(__instance.matInfo_.matName_ + __instance.materialIndex_, GreenColors.seaGreen); } } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class MaterialWrapper__MaterialName_ { [HarmonyPostfix] internal static void Postfix(ref string __result, MaterialWrapper __instance) { if (Mod.EnableSubTextures.Value) { __result = __instance.matInfo_.matName_ + __instance.materialIndex_ + ((Object)__instance.renderer_).GetInstanceID(); } } } [HarmonyPatch(typeof(MoveCursorTool), "Run")] internal static class MoveCursorTool__Run { [HarmonyPrefix] internal static bool Prefix(ref bool __result) { //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) LevelEditor levelEditor_ = G.Sys.LevelEditor_; Transform transform = levelEditor_.Cursor_.transform; int num = (int)LayerEx.CreateExcludeMask((Layers[])(object)new Layers[4] { (Layers)2, (Layers)11, (Layers)20, (Layers)8 }); if (Mod.CursorIgnoresBackground.Value) { num = (int)LayerEx.CreateExcludeMask((Layers[])(object)new Layers[6] { (Layers)2, (Layers)11, (Layers)20, (Layers)8, (Layers)29, (Layers)30 }); } RaycastHit val = default(RaycastHit); if (levelEditor_.RaycastMousePosition(ref val, num)) { transform.localRotation = MoveCursorTool.GetRayCastHitOrientation(val); transform.localPosition = ((RaycastHit)(ref val)).point + ((RaycastHit)(ref val)).normal * 0.01f; } else { Camera camera_ = G.Sys.LevelEditor_.Camera_; Transform transform2 = ((Component)camera_).transform; float nearClipPlane = camera_.nearClipPlane; Vector3 val2 = transform2.InverseTransformPoint(transform.localPosition); Vector3 mousePosition = Input.mousePosition; mousePosition.z = nearClipPlane + val2.z; transform.localPosition = camera_.ScreenToWorldPoint(mousePosition); transform.up = Vector3.up; } Vector3 localPosition = transform.localPosition; LevelEditorTool.PrintMessage("Moved the cursor to: " + ((object)(Vector3)(ref localPosition)).ToString()); __result = false; return false; } } [HarmonyPatch(typeof(NGUIFloatInspector), "AddOptions")] internal static class NGUIFloatInspector__AddOptions { [HarmonyPostfix] internal static void Postfix(NGUIFloatInspector __instance) { if (Mod.RemoveNumberLimits.Value) { ((NGUIGenericNumericInpectorOf<float>)(object)__instance).SetMin(float.MinValue); ((NGUIGenericNumericInpectorOf<float>)(object)__instance).SetMax(float.MaxValue); } } } [HarmonyPatch(typeof(NGUIIntInspector), "AddOptions")] internal static class NGUIIntInspector__AddOptions { [HarmonyPostfix] internal static void Postfix(NGUIIntInspector __instance) { if (Mod.RemoveNumberLimits.Value) { ((NGUIGenericNumericInpectorOf<int>)(object)__instance).SetMin(int.MinValue); ((NGUIGenericNumericInpectorOf<int>)(object)__instance).SetMax(int.MaxValue); } } } [HarmonyPatch(typeof(NGUIObjectInspectorTabAbstract), "CreateComponentInspectorsOnObject")] internal static class NGUIObjectInspectorTabAbstract__CreateComponentInspectorsOnObject { [HarmonyPrefix] internal static bool Prefix(NGUIObjectInspectorTabAbstract __instance, ref Set ignoreList, ref bool objectSupportsUndo, ref GameObject obj) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Invalid comparison between Unknown and I4 //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Invalid comparison between Unknown and I4 //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Invalid comparison between Unknown and I4 //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Expected O, but got Unknown bool flag = ((object)obj).Equals((object?)__instance.targetObject_); bool flag2 = TransformExtensionOnly.IsRoot(obj.transform) || flag; if (flag2 && (!ignoreList.ShouldBeIgnored((Component)(object)obj.transform) || flag)) { __instance.CreateISerializableInspector((ISerializable)(object)ComponentSerializeWrapper.Create((Component)(object)obj.transform, true), objectSupportsUndo); } Group component = obj.GetComponent<Group>(); bool flag3 = (Object)(object)component == (Object)null; bool flag4 = flag2 && ((Object)(object)component == (Object)null || (int)component.inspectChildren_ > 0); if (Object.op_Implicit((Object)(object)component)) { __instance.CreateISerializableInspector((ISerializable)(object)component, objectSupportsUndo); } if (flag4) { __instance.CreateMaterialWrappers(ArrayEx.EncapsulateInArray<GameObject>(obj), ignoreList, objectSupportsUndo); } List<ISerializable> list = new List<ISerializable>(); __instance.GetSerializables((ICollection<ISerializable>)list, ignoreList, obj, flag3); foreach (ISerializable item in list) { __instance.CreateISerializableInspector(item, objectSupportsUndo); } if (!Object.op_Implicit((Object)(object)component)) { return false; } if ((int)component.inspectChildren_ == 2) { foreach (Transform item2 in obj.transform) { Transform val = item2; if (((Component)val).gameObject.activeSelf) { __instance.CreateComponentInspectorsOnObject(ignoreList, objectSupportsUndo, ((Component)val).gameObject); } } } else { if ((int)component.inspectChildren_ != 1) { return false; } __instance.CreateComponentInspectorsForObjects(ignoreList, objectSupportsUndo, GameObjectEx.GetChildren(obj)); } return false; } } [HarmonyPatch(typeof(NGUIVector3Inspector), "AddOptions")] internal static class NGUIVector3Inspector__AddOptions { [HarmonyPostfix] internal static void Postfix(NGUIVector3Inspector __instance) { if (!Mod.RemoveNumberLimits.Value) { return; } List<UIExNumericInput> list = new List<UIExNumericInput> { __instance.inputX_, __instance.inputY_, __instance.inputZ_ }; foreach (UIExNumericInput item in list) { ((UIExGenericNumericInput<float>)(object)item).Min_ = float.MinValue; ((UIExGenericNumericInput<float>)(object)item).Max_ = float.MaxValue; } } } [HarmonyPatch(typeof(QuitToMainMenuTool), "Finish")] internal static class QuitToMainMenuTool__Finish { [HarmonyPrefix] internal static void Prefix() { EditorUtil.ClearQuickMemory(); } } [HarmonyPatch(typeof(RemoveComponentTool<AddedComponent>), "Run")] internal static class RemoveComponentTool__Run { [HarmonyPrefix] internal static bool Prefix(ref bool __result) { if (!EditorUtil.IsSelectionRoot()) { EditorUtil.PrintToolInspectionStackError(); __result = false; return false; } return true; } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class ResourceManager__LevelPrefabFileInfosRoot_ { [HarmonyPostfix] internal static void Postfix(ref LevelPrefabFileInfo __result) { //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Expected O, but got Unknown //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Expected O, but got Unknown //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Expected O, but got Unknown //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Expected O, but got Unknown //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Expected O, but got Unknown //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Expected O, but got Unknown //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Expected O, but got Unknown //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Expected O, but got Unknown //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Expected O, but got Unknown //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Expected O, but got Unknown //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Expected O, but got Unknown //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Expected O, but got Unknown //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Expected O, but got Unknown //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: Expected O, but got Unknown //IL_055a: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Expected O, but got Unknown //IL_053b: Unknown result type (might be due to invalid IL or missing references) //IL_0542: Expected O, but got Unknown bool flag = false; foreach (LevelPrefabFileInfo item in __result.childInfos_) { if ((PrimitiveEx.IsNullOrWhiteSpace(item.name_) ? "null" : item.name_).Equals("Hidden")) { flag = true; if (!Mod.HiddenFolderEnabled.Value) { Predicate<LevelPrefabFileInfo> predicate = Mod.CheckWhichIsHiddenFolder; __result.RemoveAllChildInfos(predicate); return; } } } if ((flag && Mod.HiddenFolderEnabled.Value) || !Mod.HiddenFolderEnabled.Value) { return; } ResourceManager resourceManager_ = G.Sys.ResourceManager_; Dictionary<string, List<string>> resourceMap_ = resourceManager_.resourceMap_; LevelPrefabFileInfo val = new LevelPrefabFileInfo("Hidden", __result); LevelPrefabFileInfo val2 = new LevelPrefabFileInfo("Audio", val); LevelPrefabFileInfo val3 = new LevelPrefabFileInfo("Car", val); LevelPrefabFileInfo val4 = new LevelPrefabFileInfo("Archive", val3); LevelPrefabFileInfo val5 = new LevelPrefabFileInfo("Catalyst", val3); LevelPrefabFileInfo val6 = new LevelPrefabFileInfo("Hats", val3); LevelPrefabFileInfo val7 = new LevelPrefabFileInfo("Refractor", val3); val3.AddChildInfo(val4); val3.AddChildInfo(val5); val3.AddChildInfo(val6); val3.AddChildInfo(val7); LevelPrefabFileInfo val8 = new LevelPrefabFileInfo("Detonator", val); LevelPrefabFileInfo val9 = new LevelPrefabFileInfo("DirtyLens", val); LevelPrefabFileInfo val10 = new LevelPrefabFileInfo("GameAnalytics", val); LevelPrefabFileInfo val11 = new LevelPrefabFileInfo("GameModes", val); LevelPrefabFileInfo val12 = new LevelPrefabFileInfo("HoverScreen", val); LevelPrefabFileInfo val13 = new LevelPrefabFileInfo("LegacyGUI", val); LevelPrefabFileInfo val14 = new LevelPrefabFileInfo("LevelEditorPrivate", val); LevelPrefabFileInfo val15 = new LevelPrefabFileInfo("Managers", val); LevelPrefabFileInfo val16 = new LevelPrefabFileInfo("Replays", val); LevelPrefabFileInfo val17 = new LevelPrefabFileInfo("Settings", val); LevelPrefabFileInfo val18 = new LevelPrefabFileInfo("Trackmogrify", val); val.AddChildInfo(val2); val.AddChildInfo(val3); val.AddChildInfo(val8); val.AddChildInfo(val9); val.AddChildInfo(val10); val.AddChildInfo(val11); val.AddChildInfo(val12); val.AddChildInfo(val13); val.AddChildInfo(val14); val.AddChildInfo(val15); val.AddChildInfo(val16); val.AddChildInfo(val17); val.AddChildInfo(val18); foreach (KeyValuePair<string, List<string>> item2 in resourceMap_) { foreach (string item3 in item2.Value) { if (!item3.Contains("Prefabs") || item3.Contains("LevelBackups") || item3.Contains("/Custom/") || item3.Contains("/LevelEditor/") || item3.Contains("LevelEditorMenus") || item3.Contains("Menus") || item3.Contains("Managers") || item3.Contains("wheel") || item3.Contains("ExampleListView")) { continue; } LevelPrefabFileInfo val19 = null; if (item3.Contains("/Audio/")) { val19 = val2; } else if (item3.Contains("/Car/")) { val19 = (item3.Contains("/Archive/") ? val4 : (item3.Contains("/Catalyst/") ? val5 : (item3.Contains("/Hats/") ? val6 : ((!item3.Contains("/Refractor/")) ? val3 : val7)))); } else if (item3.Contains("/Detonator/")) { val19 = val8; } else if (item3.Contains("/DirtyLens/")) { val19 = val9; } else if (item3.Contains("/GameAnalytics/")) { val19 = val10; } else if (item3.Contains("/GameModes/")) { val19 = val11; } else if (item3.Contains("/HoverScreen/")) { val19 = val12; } else if (item3.Contains("/LegacyGUI/")) { val19 = val13; } else if (item3.Contains("/LevelEditorPrivate/")) { val19 = val14; } else if (item3.Contains("/Managers/")) { val19 = val15; } else if (item3.Contains("/Replays/")) { val19 = val16; } else if (item3.Contains("/Settings/")) { val19 = val17; } else if (item3.Contains("/Trackmogrify/")) { val19 = val18; } Object val20 = Resources.Load(item3, typeof(Object)); if (val20 != (Object)null) { GameObject val21 = (((Object)(object)resourceManager_ != (Object)null) ? resourceManager_.GetResource<GameObject>(item2.Key, true) : Resources.Load<GameObject>(item2.Key)); if (val19 == null) { LevelPrefabFileInfo val22 = new LevelPrefabFileInfo(item2.Key, val21, val); val.AddChildInfo(val22); } else { LevelPrefabFileInfo val22 = new LevelPrefabFileInfo(item2.Key, val21, val19); val19.AddChildInfo(val22); } } } } __result.AddChildInfo(val); } } [HarmonyPatch(typeof(ResourceManager), "SetupPrefabFileDatas")] internal static class ResourceManger__SetupPrefabFileDatas { [HarmonyPrefix] public static bool Prefix(ResourceManager __instance) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown __instance.levelPrefabFileInfosRoot_ = new LevelPrefabFileInfo("Default", (LevelPrefabFileInfo)null); DirectoryInfo directoryInfo = new DirectoryInfo(Resource.PersonalCustomObjectsDirPath_); if (directoryInfo.Exists) { __instance.customObjectFileInfosRoot_ = new LevelPrefabFileInfo("Custom", __instance.levelPrefabFileInfosRoot_); __instance.levelPrefabFileInfosRoot_.AddChildInfo(__instance.customObjectFileInfosRoot_); AddSubfoldersRecursive(directoryInfo, __instance.customObjectFileInfosRoot_); } string text = Application.dataPath + "/Resources/LevelEditorPrefabDirectoryInfo.xml"; XmlDeserializer val = new XmlDeserializer(text); while (val.Read("LevelEditorPrefabDirectoryInformation")) { __instance.ReadFileDataRecursive(val, __instance.levelPrefabFileInfosRoot_); } if (val != null) { ((Deserializer)val).Finish(); } return false; } public static void AddSubfoldersRecursive(DirectoryInfo directory, LevelPrefabFileInfo parent) { DirectoryInfo[] directories = directory.GetDirectories(); foreach (DirectoryInfo directoryInfo in directories) { AddSubfoldersRecursive(directoryInfo, CreateSubdirectory(parent, directoryInfo.Name)); } FileInfo[] files = directory.GetFiles("*.bytes"); foreach (FileInfo file in files) { AddOrUpdatePrefabInfo(parent, file); } } public static LevelPrefabFileInfo CreateSubdirectory(LevelPrefabFileInfo parent, string name) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown LevelPrefabFileInfo val = new LevelPrefabFileInfo(name, parent); parent.AddChildInfo(val); return val; } public static LevelPrefabFileInfo AddOrUpdatePrefabInfo(LevelPrefabFileInfo parent, FileInfo file) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown string text = Resource.NormalizePath(file.FullName); string name = Path.GetFileNameWithoutExtension(text); LevelPrefabFileInfo val = parent.GetChildFileInfo((Predicate<LevelPrefabFileInfo>)((LevelPrefabFileInfo value) => value.Name_ == name)); if (val == null) { val = new LevelPrefabFileInfo(name, text, parent); parent.AddChildInfo(val); } else { val.CustomPrefabPath_ = text; } return val; } } [HarmonyPatch(typeof(SaveTool), "SortMedalRequirements")] internal static class SaveTool__SortMedalRequirements { [HarmonyPrefix] internal static bool Prefix() { if (Mod.UnlimitedMedalTimes.Value) { return false; } return true; } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class SelectionGroupData__ctor_ { [HarmonyPostfix] internal static void Postfix(ref Vector3 ___position_, ref Quaternion ___rotation_, IEnumerable<GameObject> selectedObjects, GameObject activeObject) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) ___position_ = Vector3.zero; ___rotation_ = (Object.op_Implicit((Object)(object)activeObject) ? activeObject.transform.rotation : Quaternion.identity); int num = 0; foreach (GameObject selectedObject in selectedObjects) { if (Object.op_Implicit((Object)(object)selectedObject)) { ___position_ += selectedObject.transform.position; } num++; } ___position_ /= (float)num; if (!GUtils.IsValid(___position_)) { ___position_ = Vector3.zero; } } } [HarmonyPatch(typeof(SelectMusicTrackNameFromListTool), "AddEntries")] internal static class SelectMusicTrackNameFromListTool__AddEntries { [HarmonyPrefix] internal static bool Prefix(ref Dictionary<string, string> entryList) { if (Mod.AdvancedMusicSelection.Value) { foreach (MusicCue item in G.Sys.AudioManager_.MusicCues_) { entryList.Add(item.displayName_, item.displayName_); } return false; } return true; } } [HarmonyPatch(typeof(StuntBubbleLogic), "Awake")] internal static class StuntBubbleLogic__Awake { [HarmonyPrefix] internal static bool Prefix(StuntBubbleLogic __instance) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) __instance.col_ = ((Component)__instance).GetComponent<SphereCollider>(); __instance.color_ = ((Renderer)__instance.bubbleRend_).material.GetColor("_Color"); __instance.alpha_ = __instance.color_.a; __instance.emitColor_ = ((Renderer)__instance.bubbleRend_).material.GetColor("_EmitColor"); __instance.emitAlpha_ = __instance.emitColor_.a; __instance.outlineColor_ = ((Renderer)__instance.bubbleOutlineRend_).material.GetColor("_Color"); __instance.scale_ = ((Component)__instance).transform.localScale; __instance.SetAlpha(0f); return false; } } [HarmonyPatch(typeof(StuntCollectibleLogic), "Awake")] internal static class StuntCollectibleLogic__Awake { [HarmonyPrefix] internal static bool Prefix(StuntCollectibleLogic __instance) { StaticEvent<Data>.Subscribe((Delegate<Data>)__instance.OnEventStuntCollectibleSpawned); StaticEvent<Data>.Subscribe((Delegate<Data>)__instance.OnHitTagStuntCollectible); __instance.col_ = ((Component)__instance).GetComponent<SphereCollider>(); ((Collider)__instance.col_).enabled = false; __instance.phantom_ = ((Component)__instance).GetComponent<Phantom>(); return false; } } [HarmonyPatch(typeof(TrackManipulatorNode), "SetColorAndMesh", new Type[] { })] internal static class TrackManipulatorNode__SetColorAndMesh { [HarmonyPrefix] internal static bool Prefix(TrackManipulatorNode __instance) { //IL_00b7: Unknown result type (might be due to invalid IL or missing references) if (!__instance.IsLinkConnected_) { return true; } object obj; if (__instance == null) { obj = null; } else { TrackLink link_ = __instance.Link_; if (link_ == null) { obj = null; } else { TrackSegment segment_ = link_.Segment_; obj = ((segment_ != null) ? ((Object)segment_).name : null); } } string text = (string)obj; object obj2; if (__instance == null) { obj2 = null; } else { TrackLink link_2 = __instance.Link_; if (link_2 == null) { obj2 = null; } else { TrackSegment connectedSegment_ = link_2.ConnectedSegment_; obj2 = ((connectedSegment_ != null) ? ((Object)connectedSegment_).name : null); } } string text2 = (string)obj2; string[] array = new string[2] { text, text2 }; Array.Sort(array); string key = (string.Equals(text, text2) ? text : string.Join(string.Empty, array)); Color? val = Mod.Instance.TrackNodeColors[key]; if (val.HasValue) { __instance.SetColorAndMesh(val.Value, __instance.linkedMesh_); return false; } return true; } } [HarmonyPatch(typeof(TransformWrapper), "Visit")] internal static class TransformWrapper__Visit { [HarmonyPrefix] internal static void Prefix(TransformWrapper __instance, IVisitor visitor) { if (visitor is Serializer || visitor is Deserializer) { return; } Transform ObjectTransform = ((GenericComponentSerializeWrapper<Transform>)(object)__instance).tComponent_; if (TransformExtensionOnly.IsRoot(ObjectTransform)) { return; } IVisitorEx.VisitAction(visitor, "Inspect Parent", (Action)delegate { LevelEditor levelEditor_ = G.Sys.LevelEditor_; List<GameObject> selectedObjects_ = levelEditor_.SelectedObjects_; if (selectedObjects_.Count == 1) { EditorUtil.Inspect(((Component)ObjectTransform.parent).gameObject); } else { MessageBox.Create("You must select only 1 object to use this tool.", "ERROR").SetButtons((ButtonType)0).Show(); } }, (string)null); } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class UIExGenericNumericInput__Max__set { [HarmonyPrefix] internal static void Prefix(UIExGenericNumericInput<float> __instance) { if (Mod.RemoveNumberLimits.Value) { UIExNumericInput val = (UIExNumericInput)(object)((__instance is UIExNumericInput) ? __instance : null); if (val != null) { ((UIExGenericNumericInput<float>)(object)val).max_ = float.MaxValue; } } } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class UIExGenericNumericInput__Min__set { [HarmonyPrefix] internal static void Prefix(UIExGenericNumericInput<float> __instance) { if (Mod.RemoveNumberLimits.Value) { UIExNumericInput val = (UIExNumericInput)(object)((__instance is UIExNumericInput) ? __instance : null); if (val != null) { ((UIExGenericNumericInput<float>)(object)val).min_ = float.MinValue; } } } } [HarmonyPatch(typeof(UIExNumericInput), "ConvertValueToString")] internal static class UIExNumericInput__ConvertValueToString { [HarmonyPostfix] internal static void Postfix(ref string __result, float val) { string text = "0.0"; for (int i = 0; i < Mod.EditorDecimalPrecision.Value; i++) { text += "#"; } __result = val.ToString(text); } } [HarmonyPatch(typeof(UIExNumericInput), "ValidateValue")] internal static class UIExNumericInput__ValidateValue { [HarmonyPrefix] internal static bool Prefix(ref float __result, float val) { if (Mod.RemoveNumberLimits.Value) { if (float.IsNaN(val)) { __result = 0f; } else { __result = val; } return false; } return true; } } [HarmonyPatch(typeof(UngroupTool), "Run")] internal static class UngroupTool__Run { [HarmonyPrefix] internal static bool Prefix(ref bool __result) { if (!EditorUtil.IsSelectionRoot()) { EditorUtil.PrintToolInspectionStackError(); __result = false; return false; } return true; } } } namespace EditorExpanded.Editor.Tools.Quickselect { [EditorTool] [KeyboardShortcut("CTRL+ALPHA1")] public class SaveSelection1 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 1", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1110); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 1; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA1")] public class LoadSelection1 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 1", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1210); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 1; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA2")] public class SaveSelection2 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 2", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1120); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 2; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA2")] public class LoadSelection2 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 2", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1220); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 2; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA3")] public class SaveSelection3 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 3", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1130); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 3; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA3")] public class LoadSelection3 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 3", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1230); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 3; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA4")] public class SaveSelection4 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 4", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1140); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 4; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA4")] public class LoadSelection4 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 4", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1240); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 4; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA5")] public class SaveSelection5 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 5", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1150); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 5; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA5")] public class LoadSelection5 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 5", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1250); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 5; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA6")] public class SaveSelection6 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 6", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1160); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 6; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA6")] public class LoadSelection6 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 6", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1260); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 6; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA7")] public class SaveSelection7 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 7", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1170); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 7; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA7")] public class LoadSelection7 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 7", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1270); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 7; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA8")] public class SaveSelection8 : SaveSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Save Selection 8", "Saves the inspected object into the memory.", (ToolCategory)9, (ToolButtonState)0, true, 1180); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 8; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("SHIFT+ALPHA8")] public class LoadSelection8 : LoadSelectionToolBase { internal new static ToolInfo info_ => new ToolInfo("Load Selection 8", "Inspects the object saved into the memory.", (ToolCategory)9, (ToolButtonState)0, false, 1280); public override ToolInfo Info_ => info_; public override int QuickAccessIndex => 8; public new static void Register() { G.Sys.LevelEditor_.RegisterTool(info_); } } [EditorTool] [KeyboardShortcut("CTRL+ALPHA9")] public class Sa
Newtonsoft.Json.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Json.NET Unity3D")] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")] [assembly: InternalsVisibleTo("Assembly-CSharp")] [assembly: InternalsVisibleTo("Assembly-CSharp-Editor")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: AssemblyFileVersion("9.0.1.19813")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("9.0.0.0")] namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[] array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type _namingStrategyType; private object[] _namingStrategyParameters; public string Id { get; set; } public string Title { get; set; } public string Description { get; set; } public Type ItemConverterType { get; set; } public object[] ItemConverterParameters { get; set; } public Type NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[] NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference ?? false; } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference ?? false; } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling ?? TypeNameHandling.None; } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings> DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string value) { return ToString(value, '"'); } public static string ToString(string value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } public static string SerializeObject(object value) { return SerializeObject(value, (Type)null, (JsonSerializerSettings)null); } public static string SerializeObject(object value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings)null); } public static string SerializeObject(object value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } public static string SerializeObject(object value, JsonSerializerSettings settings) { return SerializeObject(value, null, settings); } public static string SerializeObject(object value, Type type, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) { return SerializeObject(value, null, formatting, settings); } public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } public static object DeserializeObject(string value) { return DeserializeObject(value, (Type)null, (JsonSerializerSettings)null); } public static object DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } public static object DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings)null); } public static T DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings)null); } public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } public static T DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } public static T DeserializeObject<T>(string value, JsonSerializerSettings settings) { return (T)DeserializeObject(value, typeof(T), settings); } public static object DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) { throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); } } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object value, JsonSerializer serializer); public abstract object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[] ConverterParameters { get; private set; } public JsonConverterAttribute(Type converterType) { if ((object)converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal Required? _itemRequired; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public Required ItemRequired { get { return _itemRequired ?? Required.Default; } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[6] { '.', ' ', '[', ']', '(', ')' }; internal JsonContainerType Type; internal int Position; internal string PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); sb.Append(propertyName); sb.Append("']"); break; } if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder); } } currentPosition?.WriteTo(stringBuilder); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type ItemConverterType { get; set; } public object[] ItemConverterParameters { get; set; } public Type NamingStrategyType { get; set; } public object[] NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling ?? NullValueHandling.Include; } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling ?? DefaultValueHandling.Include; } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling ?? ObjectCreationHandling.Auto; } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling ?? TypeNameHandling.None; } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference ?? false; } set { _isReference = value; } } public int Order { get { return _order ?? 0; } set { _order = value; } } public Required Required { get { return _required ?? Required.Default; } set { _required = value; } } public string PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling ?? TypeNameHandling.None; } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference ?? false; } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private List<JsonPosition> _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object Value => _value; public virtual Type ValueType { get { if (_value == null) { return null; } return _value.GetType(); } } public virtual int Depth { get { int num = ((_stack != null) ? _stack.Count : 0); if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (_maxDepth.HasValue) { int num = Depth + 1; int? maxDepth = _maxDepth; if (num > maxDepth.GetValueOrDefault() && maxDepth.HasValue && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is int)) { SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), updateIndex: false); } return (int)Value; case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken) && Value != null) { string text = ((Value is IFormattable) ? ((IFormattable)Value).ToString(null, Culture) : ((!(Value is Uri)) ? Value.ToString() : ((Uri)Value).OriginalString)); SetToken(JsonToken.String, text, updateIndex: false); return text; } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[] ReadAsBytes() { JsonToken contentToken = GetContentToken(); if (contentToken == JsonToken.None) { return null; } if (TokenType == JsonToken.StartObject) { ReadIntoWrappedTypeObject(); byte[] array = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } switch (contentToken) { case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? new byte[0] : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if ((object)ValueType == typeof(Guid)) { byte[] array2 = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); while (true) { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: break; case JsonToken.EndArray: { byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } list.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is double)) { double num = Convert.ToDouble(Value, CultureInfo.InvariantCulture); SetToken(JsonToken.Float, num, updateIndex: false); } return (double)Value; case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is decimal)) { SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), updateIndex: false); } return (decimal)Value; case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset) { SetToken(JsonToken.Date, ((DateTimeOffset)Value).DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime) { SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, updateIndex: true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { if (SupportMultipleContent) { _currentState = State.Start; } else { _currentState = State.Finished; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; private set; } public int LinePosition { get; private set; } public string Path { get; private set; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal JsonReaderException(string message, Exception innerException, string path, int lineNumber, int linePosition) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, ex, path, lineNumber, linePosition); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonSerializationException(message, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal FormatterAssemblyStyle _typeNameAssemblyFormat; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; internal ITraceWriter _traceWriter; internal IEqualityComparer _equalityComparer; internal SerializationBinder _binder; internal StreamingContext _context; private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } public virtual SerializationBinder Binder { get { return _binder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _binder = value; } } public virtual ITraceWriter TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _typeNameAssemblyFormat; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormat = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting ?? Formatting.None; } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? DateFormatHandling.IsoDateFormat; } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? FloatParseHandling.Double; } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? FloatFormatHandling.String; } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? StringEscapeHandling.Default; } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent ?? false; } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _binder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormat.HasValue) { serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.Binder != null) { serializer.Binder = settings.Binder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out var previousCulture, out var previousDateTimeZoneHandling, out var previousDateParseHandling, out var previousFloatParseHandling, out var previousMaxDepth, out var previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } public T Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } public object Deserialize(JsonReader reader, Type objectType) { return DeserializeInternal(reader, objectType); } internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out var previousCulture, out var previousDateTimeZoneHandling, out var previousDateParseHandling, out var previousFloatParseHandling, out var previousMaxDepth, out var previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null); object result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.NameTable = defaultContractResolver.GetState().NameTable; } } private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader) { jsonTextReader.NameTable = null; } } public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object value) { SerializeInternal(jsonWriter, value, null); } internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal const FormatterAssemblyStyle DefaultTypeNameAssemblyFormat = FormatterAssemblyStyle.Simple; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const FormatterAssemblyStyle DefaultFormatterAssemblyStyle = FormatterAssemblyStyle.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string _dateFormatString; internal bool _dateFormatStringSet; internal FormatterAssemblyStyle? _typeNameAssemblyFormat; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling ?? MissingMemberHandling.Ignore; } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling ?? ObjectCreationHandling.Auto; } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling ?? NullValueHandling.Include; } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling ?? DefaultValueHandling.Include; } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling ?? PreserveReferencesHandling.None; } set { _preserveReferencesHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling ?? TypeNameHandling.None; } set { _typeNameHandling = value; } } public MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling ?? MetadataPropertyHandling.Default; } set { _metadataPropertyHandling = value; } } public FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _typeNameAssemblyFormat ?? FormatterAssemblyStyle.Simple; } set { _typeNameAssemblyFormat = value; } } public ConstructorHandling ConstructorHandling { get { return _constructorHandling ?? ConstructorHandling.Default; } set { _constructorHandling = value; } } public IContractResolver ContractResolver { get; set; } public IEqualityComparer EqualityComparer { get; set; } [Obsolete("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")] public IReferenceResolver ReferenceResolver { get { if (ReferenceResolverProvider == null) { return null; } return ReferenceResolverProvider(); } set { ReferenceResolverProvider = ((value != null) ? ((Func<IReferenceResolver>)(() => value)) : null); } } public Func<IReferenceResolver> ReferenceResolverProvider { get; set; } public ITraceWriter TraceWriter { get; set; } public SerializationBinder Binder { get; set; } public EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> Error { get; set; } public StreamingContext Context { get { return _context ?? DefaultContext; } set { _context = value; } } public string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public Formatting Formatting { get { return _formatting ?? Formatting.None; } set { _formatting = value; } } public DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? DateFormatHandling.IsoDateFormat; } set { _dateFormatHandling = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? FloatFormatHandling.String; } set { _floatFormatHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? FloatParseHandling.Double; } set { _floatParseHandling = value; } } public StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? StringEscapeHandling.Default; } set { _stringEscapeHandling = value; } } public CultureInfo Culture { get { return _culture ?? DefaultCulture; } set { _culture = value; } } public bool CheckAdditionalContent { get { return _checkAdditionalContent ?? false; } set { _checkAdditionalContent = value; } } static JsonSerializerSettings() { DefaultContext = default(StreamingContext); DefaultCulture = CultureInfo.InvariantCulture; } public JsonSerializerSettings() { Converters = new List<JsonConverter>(); } } internal enum ReadType { Read, ReadAsInt32, ReadAsBytes, ReadAsString, ReadAsDecimal, ReadAsDateTime, ReadAsDateTimeOffset, ReadAsDouble, ReadAsBoolean } public class JsonTextReader : JsonReader, IJsonLineInfo { private const char UnicodeReplacementChar = '\ufffd'; private const int MaximumJavascriptIntegerCharacterLength = 380; private readonly TextReader _reader; private char[] _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; private int _lineNumber; private bool _isEndOfFile; private StringBuffer _stringBuffer; private StringReference _stringReference; private IArrayPool<char> _arrayPool; internal PropertyNameTable NameTable; public IArrayPool<char> ArrayPool { get { return _arrayPool; } set { if (value == null) { throw new ArgumentNullException("value"); } _arrayPool = value; } } public int LineNumber { get { if (base.CurrentState == State.Start && LinePosition == 0 && TokenType != JsonToken.Comment) { return 0; } return _lineNumber; } } public int LinePosition => _charPos - _lineStartPos; public JsonTextReader(TextReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } _reader = reader; _lineNumber = 1; } private void EnsureBufferNotEmpty() { if (_stringBuffer.IsEmpty) { _stringBuffer = new StringBuffer(_arrayPool, 1024); } } private void OnNewLine(int pos) { _lineNumber++; _lineStartPos = pos; } private void ParseString(char quote, ReadType readType) { _charPos++; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quote); SetPostValueState(updateIndex: true); switch (readType) { case ReadType.ReadAsBytes: { Guid g; byte[] value2 = ((_stringReference.Length == 0) ? new byte[0] : ((_stringReference.Length != 36 || !ConvertUtils.TryConvertGuid(_stringReference.ToString(), out g)) ? Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length) : g.ToByteArray())); SetToken(JsonToken.Bytes, value2, updateIndex: false); return; } case ReadType.ReadAsString: { string value = _stringReference.ToString(); SetToken(JsonToken.String, value, updateIndex: false); _quoteChar = quote; return; } case ReadType.ReadAsInt32: case ReadType.ReadAsDecimal: case ReadType.ReadAsBoolean: return; } if (_dateParseHandling != 0) { DateTimeOffset dt2; if (readType switch { ReadType.ReadAsDateTime => 1, ReadType.ReadAsDateTimeOffset => 2, _ => (int)_dateParseHandling, } == 1) { if (DateTimeUtils.TryParseDateTime(_stringReference, base.DateTimeZoneHandling, base.DateFormatString, base.Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return; } } else if (DateTimeUtils.TryParseDateTimeOffset(_stringReference, base.DateFormatString, base.Culture, out dt2)) { SetToken(JsonToken.Date, dt2, updateIndex: false); return; } } SetToken(JsonToken.String, _stringReference.ToString(), updateIndex: false); _quoteChar = quote; } private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { Buffer.BlockCopy(src, srcOffset * 2, dst, dstOffset * 2, count * 2); } private void ShiftBufferIfNeeded() { int num = _chars.Length; if ((double)(num - _charPos) <= (double)num * 0.1) { int num2 = _charsUsed - _charPos; if (num2 > 0) { BlockCopyChars(_chars, _charPos, _chars, 0, num2); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = num2; _chars[_charsUsed] = '\0'; } } private int ReadData(bool append) { return ReadData(append, 0); } private int ReadData(bool append, int charsRequired) { if (_isEndOfFile) { return 0; } if (_charsUsed + charsRequired >= _chars.Length - 1) { if (append) { int minSize = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1); char[] array = BufferUtils.RentBuffer(_arrayPool, minSize); BlockCopyChars(_chars, 0, array, 0, _chars.Length); BufferUtils.ReturnBuffer(_arrayPool, _chars); _chars = array; } else { int num = _charsUsed - _charPos; if (num + charsRequired + 1 >= _chars.Length) { char[] array2 = BufferUtils.RentBuffer(_arrayPool, num + charsRequired + 1); if (num > 0) { BlockCopyChars(_chars, _charPos, array2, 0, num); } BufferUtils.ReturnBuffer(_arrayPool, _chars); _chars = array2; } else if (num > 0) { BlockCopyChars(_chars, _charPos, _chars, 0, num); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = num; } } int count = _chars.Length - _charsUsed - 1; int num2 = _reader.Read(_chars, _charsUsed, count); _charsUsed += num2; if (num2 == 0) { _isEndOfFile = true; } _chars[_charsUsed] = '\0'; return num2; } private bool EnsureChars(int relativePosition, bool append) { if (_charPos + relativePosition >= _charsUsed) { return ReadChars(relativePosition, append); } return true; } private bool ReadChars(int relativePosition, bool append) { if (_isEndOfFile) { return false; } int num = _charPos + relativePosition - _charsUsed + 1; int num2 = 0; do { int num3 = ReadData(append, num - num2); if (num3 == 0) { break; } num2 += num3; } while (num2 < num); if (num2 < num) { return false; } return true; } public override bool Read() { EnsureBuffer(); do { switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.ConstructorStart: case State.Constructor: return ParseValue(); case State.ObjectStart: case State.Object: return ParseObject(); case State.PostValue: break; case State.Finished: if (EnsureChars(0, append: false)) { EatWhitespace(oneOrMore: false); if (_isEndOfFile) { SetToken(JsonToken.None); return false; } if (_chars[_charPos] == '/') { ParseComment(setToken: true); return true; } throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } SetToken(JsonToken.None); return false; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } while (!ParsePostValue()); return true; } public override int? ReadAsInt32() { return (int?)ReadNumberValue(ReadType.ReadAsInt32); } public override DateTime? ReadAsDateTime() { return (DateTime?)ReadStringValue(ReadType.ReadAsDateTime); } public override string ReadAsString() { return (string)ReadStringValue(ReadType.ReadAsString); } public override byte[] ReadAsBytes() { EnsureBuffer(); bool flag = false; switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': { ParseString(c, ReadType.ReadAsBytes); byte[] array = (byte[])Value; if (flag) { ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array, updateIndex: false); } return array; } case '{': _charPos++; SetToken(JsonToken.StartObject); ReadIntoWrappedTypeObject(); flag = true; break; case '[': _charPos++; SetToken(JsonToken.StartArray); return ReadArrayIntoByteArray(); case 'n': HandleNull(); return null; case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } private object ReadStringValue(ReadType readType) { EnsureBuffer(); switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': ParseString(c, readType); switch (readType) { case ReadType.ReadAsBytes: return Value; case ReadType.ReadAsString: return Value; case ReadType.ReadAsDateTime: if (Value is DateTime) { return (DateTime)Value; } return ReadDateTimeString((string)Value); case ReadType.ReadAsDateTimeOffset: if (Value is DateTimeOffset) { return (DateTimeOffset)Value; } return ReadDateTimeOffsetString((string)Value); default: throw new ArgumentOutOfRangeException("readType"); } case '-': if (EnsureChars(1, append: true) && _chars[_charPos + 1] == 'I') { return ParseNumberNegativeInfinity(readType); } ParseNumber(readType); return Value; case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (readType != ReadType.ReadAsString) { _charPos++; throw CreateUnexpectedCharacterException(c); } ParseNumber(ReadType.ReadAsString); return Value; case 'f': case 't': { if (readType != ReadType.ReadAsString) { _charPos++; throw CreateUnexpectedCharacterException(c); } string text = ((c == 't') ? JsonConvert.True : JsonConvert.False); if (!MatchValueWithTrailingSeparator(text)) { throw CreateUnexpectedCharacterException(_chars[_charPos]); } SetToken(JsonToken.String, text); return text; } case 'I': return ParseNumberPositiveInfinity(readType); case 'N': return ParseNumberNaN(readType); case 'n': HandleNull(); return null; case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } private JsonReaderException CreateUnexpectedCharacterException(char c) { return JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, c)); } public override bool? ReadAsBoolean() { EnsureBuffer(); switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': ParseString(c, ReadType.Read); return ReadBooleanString(_stringReference.ToString()); case 'n': HandleNull(); return null; case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { ParseNumber(ReadType.Read); bool flag2 = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); SetToken(JsonToken.Boolean, flag2, updateIndex: false); return flag2; } case 'f': case 't': { bool flag = c == 't'; string value = (flag ? JsonConvert.True : JsonConvert.False); if (!MatchValueWithTrailingSeparator(value)) { throw CreateUnexpectedCharacterException(_chars[_charPos]); } SetToken(JsonToken.Boolean, flag); return flag; } case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } private void ProcessValueComma() { _charPos++; if (_currentState != State.PostValue) { SetToken(JsonToken.Undefined); throw CreateUnexpectedCharacterException(','); } SetStateBasedOnCurrent(); } private object ReadNumberValue(ReadType readType) { EnsureBuffer(); switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': ParseString(c, readType); return readType switch { ReadType.ReadAsInt32 => ReadInt32String(_stringReference.ToString()), ReadType.ReadAsDecimal => ReadDecimalString(_stringReference.ToString()), ReadType.ReadAsDouble => ReadDoubleString(_stringReference.ToString()), _ => throw new ArgumentOutOfRangeException("readType"), }; case 'n': HandleNull(); return null; case 'N': return ParseNumberNaN(readType); case 'I': return ParseNumberPositiveInfinity(readType); case '-': if (EnsureChars(1, append: true) && _chars[_charPos + 1] == 'I') { return ParseNumberNegativeInfinity(readType); } ParseNumber(readType); return Value; case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ParseNumber(readType); return Value; case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } public override DateTimeOffset? ReadAsDateTimeOffset() { return (DateTimeOffset?)ReadStringValue(ReadType.ReadAsDateTimeOffset); } public override decimal? ReadAsDecimal() { return (decimal?)ReadNumberValue(ReadType.ReadAsDecimal); } public override double? ReadAsDouble() { return (double?)ReadNumberValue(ReadType.ReadAsDouble); } private void HandleNull() { if (EnsureChars(1, append: true)) { if (_chars[_charPos + 1] == 'u') { ParseNull(); return; } _charPos += 2; throw CreateUnexpectedCharacterException(_chars[_charPos - 1]); } _charPos = _charsUsed; throw CreateUnexpectedEndException(); } private void ReadF