Compare commits

..

55 Commits

Author SHA1 Message Date
46f35129c5 3.2.10
* The following preferences are now persistent between sessions: Active Menu Page, Scene Explorer Hide State, Debug Console Hide State
* The "Resize Cursor" is now just a `↔` Text label instead of a sprite.
* Added support for Unity 5.2+ games (previously was only supporting 5.6)
2021-03-26 19:49:53 +11:00
604c499822 Add Reset button to C# Console 2021-03-26 07:31:30 +11:00
8964c48ba0 Move melon attributes to ExplorerMelonMod.cs 2021-03-26 06:38:59 +11:00
e85a3e0f1e Merge bepinex/melonloader unhollowed libs 2021-03-26 06:04:44 +11:00
c658d393f5 Update README.md 2021-03-26 05:59:17 +11:00
9a45e29e02 Update README.md 2021-03-26 05:53:03 +11:00
418ece55e3 Improve UI inspect-under-mouse 2021-03-26 05:43:53 +11:00
bf455893e7 Include all references in lib folder 2021-03-26 05:40:12 +11:00
6d9cb8205a Update README.md 2021-03-25 18:48:40 +11:00
0f431e997b Update README.md 2021-03-25 18:47:52 +11:00
2107df70ad Improvements to CS Console
* Errors are now logged properly.
* Can now define classes, methods, etc - no longer has to be an expression body.
* Added `StartCoroutine(IEnumerator routine)` helper method to easily run a Coroutine
* Disabling suggestions now properly stops Explorer trying to update suggestion cache instead of just not showing them. In the rare cases that suggestions cause a crash, disabling them will now prevent those crashes.
* Various other misc improvements behind the scenes
2021-03-25 18:39:35 +11:00
a9fbea7c96 (C# Console) Only update autocomplete and indent if they are enabled 2021-03-24 17:14:13 +11:00
77878ddd94 Use reflection for adding Unity log callback to avoid unstripping errors 2021-03-24 17:13:43 +11:00
594abc47f8 Move RuntimeProvider.Init to after config is loaded 2021-03-24 17:13:26 +11:00
5e326916a2 bump version 2021-03-23 16:16:09 +11:00
31c2debb78 fix typo mistake in previous version 2021-03-23 16:15:16 +11:00
d919497e43 Config: use en-us culture, fix recursive exception 2021-03-23 04:47:55 +11:00
0c40b4fad9 Merge branch 'master' of https://github.com/sinai-dev/Explorer 2021-03-21 16:18:56 +11:00
bba912667f fix ToString exception 2021-03-21 16:18:47 +11:00
1807e7c5ff Update TextureUtilProvider.cs 2021-03-21 15:16:36 +11:00
9da2ea9b1b Update README and Lexer namespaces 2021-03-18 18:52:30 +11:00
1a5843f8e1 disable main menu page on failed init 2021-03-18 18:38:51 +11:00
25e48f2f37 Project refactor, namespace cleanup, splitting UI/functionality. 2021-03-18 17:17:29 +11:00
1c0011bef9 bump version 2021-03-16 18:13:14 +11:00
9e996816ef starting work on a cleanup/rewrite 2021-03-16 18:12:39 +11:00
9665753dc8 fix BIE5 mono release 2021-03-16 18:12:26 +11:00
942e9d7555 some commenting 2021-03-14 16:08:53 +11:00
9efb9581f5 Cleanups, method summaries, bump version 2021-03-12 18:41:57 +11:00
f10a462b00 More reflection caching, use deobfuscated names for ToString labels 2021-03-12 18:41:38 +11:00
9072b16c5a Save window size between launches 2021-03-12 18:39:57 +11:00
21408993c2 create subfolder for standalone 2021-03-11 18:40:04 +11:00
7a8b5b50d1 bump version, update readme 2021-03-11 18:32:57 +11:00
1a5e843070 handle ExplorerStandalone update internally 2021-03-11 18:16:52 +11:00
ade7539fde cleanups 2021-03-11 17:57:58 +11:00
5c588e5a03 Update README.md 2021-03-10 05:04:43 +11:00
af094832fe Update README.md 2021-03-09 22:31:26 +11:00
af0ee2e690 Update README.md 2021-03-09 22:29:53 +11:00
d2d6fb4d55 Update README.md 2021-03-09 22:28:43 +11:00
6c25662fe9 Update README.md 2021-03-09 17:36:49 +11:00
4bcf82ca10 separate Bep5 and Bep6 support. Fix enums not backed by ints. 2021-03-09 17:35:54 +11:00
ce38e8ac50 bump to MelonLoader 0.3.0 2021-03-06 17:25:54 +11:00
12cd718f12 3.1.12: store Il2CppToMonoType key as string AssemblyQualifiedName instead of Type object 2021-03-04 01:44:34 +11:00
995e2a3e93 3.1.11: fix potential crash on scene reload 2021-03-03 22:09:14 +11:00
2c95fec646 3.1.10: Add "Hide on startup" config option 2021-02-27 17:04:47 +11:00
69912d7ea4 Prevent GC Mark Overflow on C# Console copy+paste 2021-02-26 17:54:00 +11:00
9c5596ace4 Update lib versions 2021-02-26 17:52:21 +11:00
d4dac58fc8 Fix for deobfuscated unhollowed types not being properly resolved 2021-02-20 19:39:19 +11:00
77b97cbe17 Update README.md 2021-02-03 18:31:29 +11:00
c6f0f34ac0 Update README.md 2021-01-28 02:09:40 +11:00
d1f4f74d32 some ui cleanups (minor) 2021-01-22 21:56:00 +11:00
f13068bf01 Update README.md 2021-01-20 23:05:04 +11:00
dfc288a101 Update README.md 2021-01-20 19:10:13 +11:00
544009dc21 3.1.7
* Added standalone release build (thanks @Alloc86)
* Improved formatting for ToString methods which accept an IFormatProvider
* When editing a struct, the reference to the parent member will now be updated if you modify the struct values.
2021-01-20 17:22:36 +11:00
fdfaaadd89 3.1.6 - don't bother setting pixelPerfect on canvas 2021-01-14 17:46:32 +11:00
58d60a10d4 Update ForceUnlockCursor.cs 2021-01-04 01:23:20 +11:00
132 changed files with 5884 additions and 4448 deletions

View File

@ -17,16 +17,19 @@
- [Features](#features)
- [How to install](#how-to-install)
- [Mod Config](#mod-config)
- [Mouse Control](#mouse-control)
- [Building](#building)
- [Credits](#credits)
- [Acknowledgments](#acknowledgments)
## Releases
| Mod Loader | IL2CPP | Mono |
| ----------- | ------ | ---- |
| [MelonLoader](https://github.com/HerpDerpinstine/MelonLoader) | ✔️ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.MelonLoader.Il2Cpp.zip) | ✔️ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.MelonLoader.Mono.zip) |
| [BepInEx](https://github.com/BepInEx/BepInEx) | ✔️ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.BepInEx.Il2Cpp.zip) | ✔️ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.BepInEx.Mono.zip) |
| [BepInEx](https://github.com/BepInEx/BepInEx) 6.X | ✅ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.BepInEx.Il2Cpp.zip) | ❔* [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.BepInEx6.Mono.zip) |
| [BepInEx](https://github.com/BepInEx/BepInEx) 5.X | ❌ n/a | [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.BepInEx5.Mono.zip) |
| [MelonLoader](https://github.com/HerpDerpinstine/MelonLoader) 0.3 | ✅ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.MelonLoader.Il2Cpp.zip) | ✅ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.MelonLoader.Mono.zip) |
| Standalone | ✅ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.Standalone.Il2Cpp.zip) | ✅ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.Standalone.Mono.zip) |
\* BepInEx 6.X Mono release may not work on all games yet.
## Features
@ -41,26 +44,70 @@
* <b>Reflection Inspector</b>: Inspect Properties and Fields. Can also set primitive values and evaluate primitive methods.
* <b>Search</b>: Search for UnityEngine.Objects with various filters, or use the helpers for static Instances and Classes.
* <b>C# Console</b>: Interactive console for evaluating C# methods on the fly, with some basic helpers.
* <b>Inspect-under-mouse</b>: Hover over an object with a collider and inspect it by clicking on it.
* <b>Inspect-under-mouse</b>: Hover over an object with a collider and inspect it by clicking on it. There's also a UI mode to inspect UI objects.
### C# Console Tips
The C# Console can be used to define temporary classes and methods, or it can be used to evaluate an expression, but you cannot do both at the same time.
For example, you could run this code to define a temporary class (it will be visible within the console until you run `Reset();`).
```csharp
public class MyClass
{
public static void Method()
{
UnityExplorer.ExplorerCore.Log("hello");
}
}
```
You could then delete or comment out the class and run the following expression to run that method:
```csharp
MyClass.Method();
```
However, you cannot define a class and run it both at the same time. You must either define class(es) and run that, or define an expression and run that.
You can also make use of the helper methods in the console to simplify some tasks, which you can see listed when the console has nothing entered for input. These methods are **not** accessible within any temporary classes you define, they can only be used in the expression context.
## How to install
### BepInEx
Note: For IL2CPP you should use [BepInEx 6 (Bleeding Edge)](https://builds.bepis.io/projects/bepinex_be), for Mono you should use [BepInEx 5](https://github.com/BepInEx/BepInEx/releases) (until Mono support stabilizes in BepInEx 6).
0. Install [BepInEx](https://github.com/BepInEx/BepInEx) for your game.
1. Download the UnityExplorer release for BepInEx IL2CPP or Mono above.
2. Take the `UnityExplorer.BIE.___.dll` file and put it in `[GameFolder]\BepInEx\plugins\`
3. In IL2CPP, it is highly recommended to get the base Unity libs for the game's Unity version and put them in the `BepInEx\unhollowed\base\` folder.
3. In IL2CPP, it is highly recommended to get the base Unity libs for the game's Unity version and put them in the `BepInEx\unity-libs\` folder.
### MelonLoader
Note: You must use version 0.3 of MelonLoader or greater. Version 0.3 is currently in pre-release, so you must opt-in from your MelonLoader installer (enable alpha releases).
0. Install [MelonLoader](https://github.com/HerpDerpinstine/MelonLoader) for your game.
1. Download the UnityExplorer release for MelonLoader IL2CPP or Mono above.
2. Take the contents of the release and put it in the `[GameFolder]\Mods\` folder. It should look like `[GameFolder]\Mods\UnityExplorer.ML.___.dll`
## Mod Config
### Standalone
You can access the settings via the "Options" page of the main menu, or directly from the config at `Mods\UnityExplorer\config.ini` (generated after first launch).
The standalone release is based on the BepInEx build, so it requires Harmony 2.0 (or HarmonyX) to function properly.
0. Load the DLL from your mod or inject it. You must also make sure that the required libraries (Harmony, Unhollower for Il2Cpp, etc) are loaded.
1. Create an instance of Unity Explorer with `ExplorerStandalone.CreateInstance();`
2. Optionally subscribe to the `ExplorerStandalone.OnLog` event to handle logging if you wish.
## Logging
Explorer saves all logs to disk (only keeps the most recent 10 logs). They can be found in a "UnityExplorer" folder in the same place as where you put the DLL file.
These logs are also visible in the Debug Console part of the UI.
## Settings
You can change the settings via the "Options" page of the main menu, or directly from the config file (generated after first launch). The config file will be found either inside a "UnityExplorer" folder in the same directory as where you put the DLL file, or for BepInEx it will be at `BepInEx\config\UnityExplorer\`.
`Main Menu Toggle` (KeyCode)
* Default: `F7`
@ -78,31 +125,32 @@ You can access the settings via the "Options" page of the main menu, or directly
`Default Output Path` (string)
* Default: `Mods\UnityExplorer`
* Where output is generated to, by default (for Texture PNG saving, etc).
* Currently this is not actually used for anything, but it will be soon.
`Log Unity Debug` (bool)
* Default: `false`
* Listens for Unity `Debug.Log` messages and prints them to UnityExplorer's log.
`Hide on Startup` (bool)
* Default: `false`
* If true, UnityExplorer will be hidden when you start the game, you must open it via the keybind.
## Building
If you'd like to build this yourself, you will need to have installed BepInEx and/or MelonLoader for at least one Unity game. If you want to build all 4 versions, you will need at least one IL2CPP and one Mono game, with BepInEx and MelonLoader installed for both.
If you'd like to build this yourself, all you need to do is download this repository and build from Visual Studio.
1. Install BepInEx or MelonLoader for your game.
2. Open the `src\UnityExplorer.csproj` file in a text editor.
3. For IL2CPP builds, make sure you set `BIECppGameFolder` (for BepInEx) and/or `MLCppGameFolder` (for MelonLoader) so the project can locate the necessary references.
4. Open the `src\UnityExplorer.sln` project.
5. Select `Solution 'UnityExplorer' (1 of 1 project)` in the Solution Explorer panel, and set the <b>Active config</b> property to the version you want to build, then build it.
5. The DLLs are built to the `Release\` folder in the root of the repository.
6. If ILRepack fails or is missing, use the NuGet package manager to re-install `ILRepack.Lib.MSBuild.Task`, then re-build.
1. Open the `src\UnityExplorer.sln` project.
2. Select `Solution 'UnityExplorer' (1 of 1 project)` in the Solution Explorer panel, and set the <b>Active config</b> property to the version you want to build, then build it. Alternatively, use "Batch Build" and select all releases.
3. The DLLs are built to the `Release\` folder in the root of the repository.
## Credits
The references are all inside the `lib\` folder, if you need to change them for some reason then you can replace them there.
Written by Sinai.
## Acknowledgments
### Licensing
* [ManlyMarco](https://github.com/ManlyMarco) for [Runtime Unity Editor](https://github.com/ManlyMarco/RuntimeUnityEditor) (GPL), snippets from the REPL Console were used for UnityExplorer's C# Console.
* [denikson](https://github.com/denikson) (aka Horse) for [mcs-unity](https://github.com/denikson/mcs-unity) (MIT), used as the `Mono.CSharp` reference for the C# Console.
* [HerpDerpenstine](https://github.com/HerpDerpinstine) for [MelonCoroutines](https://github.com/LavaGang/MelonLoader/blob/master/MelonLoader.Support.Il2Cpp/MelonCoroutines.cs) (Apache), they were included for standalone Il2CPP coroutine support.
* [InGameCodeEditor](https://assetstore.unity.com/packages/tools/gui/ingame-code-editor-144254) (Apache) was used as the base for the syntax highlighting for UnityExplorer's C# console (`UnityExplorer.UI.Main.CSConsole.Lexer`).
This project uses code from:
* (GPL) [ManlyMarco](https://github.com/ManlyMarco)'s [Runtime Unity Editor](https://github.com/ManlyMarco/RuntimeUnityEditor), which I used for some aspects of the C# Console and Auto-Complete features. The snippets I used are indicated with a comment.
* (MIT) [denikson](https://github.com/denikson) (aka Horse)'s [mcs-unity](https://github.com/denikson/mcs-unity). I commented out the `SkipVisibilityExt` constructor since it was causing an exception with the Hook it attempted in IL2CPP.
* (Apache) [InGameCodeEditor](https://assetstore.unity.com/packages/tools/gui/ingame-code-editor-144254) was used as the base for the syntax highlighting for UnityExplorer's C# console, although it has been heavily rewritten and optimized. Used classes are in the `UnityExplorer.CSConsole.Lexer` namespace.
### Disclaimer
UnityExplorer is in no way associated with Unity Technologies. "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere.

Binary file not shown.

BIN
lib/BepInEx.Unity.dll Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
lib/MelonLoader.dll Normal file

Binary file not shown.

BIN
lib/UnhollowerBaseLib.dll Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,100 +0,0 @@
using System;
using System.IO;
using UnityEngine;
using IniParser;
using IniParser.Parser;
namespace UnityExplorer.Config
{
public class ModConfig
{
public static ModConfig Instance;
internal static readonly IniDataParser _parser = new IniDataParser();
internal static readonly string INI_PATH = Path.Combine(ExplorerCore.EXPLORER_FOLDER, "config.ini");
static ModConfig()
{
_parser.Configuration.CommentString = "#";
}
// Actual configs
public KeyCode Main_Menu_Toggle = KeyCode.F7;
public bool Force_Unlock_Mouse = true;
public int Default_Page_Limit = 25;
public string Default_Output_Path = ExplorerCore.EXPLORER_FOLDER + @"\Output";
public bool Log_Unity_Debug = false;
public bool Save_Logs_To_Disk = true;
public static event Action OnConfigChanged;
internal static void InvokeConfigChanged()
{
OnConfigChanged?.Invoke();
}
public static void OnLoad()
{
Instance = new ModConfig();
if (LoadSettings())
return;
SaveSettings();
}
public static bool LoadSettings()
{
if (!File.Exists(INI_PATH))
return false;
string ini = File.ReadAllText(INI_PATH);
var data = _parser.Parse(ini);
foreach (var config in data.Sections["Config"])
{
switch (config.KeyName)
{
case "Main_Menu_Toggle":
Instance.Main_Menu_Toggle = (KeyCode)Enum.Parse(typeof(KeyCode), config.Value);
break;
case "Force_Unlock_Mouse":
Instance.Force_Unlock_Mouse = bool.Parse(config.Value);
break;
case "Default_Page_Limit":
Instance.Default_Page_Limit = int.Parse(config.Value);
break;
case "Log_Unity_Debug":
Instance.Log_Unity_Debug = bool.Parse(config.Value);
break;
case "Save_Logs_To_Disk":
Instance.Save_Logs_To_Disk = bool.Parse(config.Value);
break;
case "Default_Output_Path":
Instance.Default_Output_Path = config.Value;
break;
}
}
return true;
}
public static void SaveSettings()
{
var data = new IniParser.Model.IniData();
data.Sections.AddSection("Config");
var sec = data.Sections["Config"];
sec.AddKey("Main_Menu_Toggle", Instance.Main_Menu_Toggle.ToString());
sec.AddKey("Force_Unlock_Mouse", Instance.Force_Unlock_Mouse.ToString());
sec.AddKey("Default_Page_Limit", Instance.Default_Page_Limit.ToString());
sec.AddKey("Log_Unity_Debug", Instance.Log_Unity_Debug.ToString());
sec.AddKey("Save_Logs_To_Disk", Instance.Save_Logs_To_Disk.ToString());
sec.AddKey("Default_Output_Path", Instance.Default_Output_Path);
File.WriteAllText(INI_PATH, data.ToString());
}
}
}

View File

@ -0,0 +1,29 @@
#if MONO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace UnityExplorer.Core.CSharp
{
public class DummyBehaviour : MonoBehaviour
{
public static DummyBehaviour Instance;
public static void Setup()
{
var obj = new GameObject("Explorer_DummyBehaviour");
DontDestroyOnLoad(obj);
obj.hideFlags |= HideFlags.HideAndDontSave;
obj.AddComponent<DummyBehaviour>();
}
internal void Awake()
{
Instance = this;
}
}
}
#endif

View File

@ -4,9 +4,9 @@ using System.IO;
using System.Reflection;
using Mono.CSharp;
// Thanks to ManlyMarco for this
// Thanks to ManlyMarco for most of this
namespace UnityExplorer.CSConsole
namespace UnityExplorer.Core.CSharp
{
public class ScriptEvaluator : Evaluator, IDisposable
{
@ -15,11 +15,12 @@ namespace UnityExplorer.CSConsole
"mscorlib", "System.Core", "System", "System.Xml"
};
private readonly TextWriter tw;
internal static TextWriter _textWriter;
internal static StreamReportPrinter _reportPrinter;
public ScriptEvaluator(TextWriter tw) : base(BuildContext(tw))
{
this.tw = tw;
_textWriter = tw;
ImportAppdomainAssemblies(ReferenceAssembly);
AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoad;
@ -28,23 +29,22 @@ namespace UnityExplorer.CSConsole
public void Dispose()
{
AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoad;
tw.Dispose();
_textWriter.Dispose();
}
private void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
string name = args.LoadedAssembly.GetName().Name;
if (StdLib.Contains(name))
{
return;
}
ReferenceAssembly(args.LoadedAssembly);
}
private static CompilerContext BuildContext(TextWriter tw)
{
var reporter = new StreamReportPrinter(tw);
_reportPrinter = new StreamReportPrinter(tw);
var settings = new CompilerSettings
{
@ -56,7 +56,7 @@ namespace UnityExplorer.CSConsole
EnhancedWarnings = false
};
return new CompilerContext(settings, reporter);
return new CompilerContext(settings, _reportPrinter);
}
private static void ImportAppdomainAssemblies(Action<Assembly> import)

View File

@ -1,10 +1,16 @@
using System;
using Mono.CSharp;
using UnityExplorer.UI;
using UnityExplorer.UI.Modules;
using UnityExplorer.Inspectors;
using UnityExplorer.UI.Main;
using UnityExplorer.Core.Inspectors;
using UnityExplorer.UI.Main.CSConsole;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using UnityExplorer.Core.Runtime;
namespace UnityExplorer.CSConsole
namespace UnityExplorer.Core.CSharp
{
public class ScriptInteraction : InteractiveBase
{
@ -13,19 +19,24 @@ namespace UnityExplorer.CSConsole
ExplorerCore.Log(message);
}
public static void StartCoroutine(IEnumerator ienumerator)
{
RuntimeProvider.Instance.StartConsoleCoroutine(ienumerator);
}
public static void AddUsing(string directive)
{
CSConsolePage.Instance.AddUsing(directive);
CSharpConsole.Instance.AddUsing(directive);
}
public static void GetUsing()
{
ExplorerCore.Log(CSConsolePage.Instance.m_evaluator.GetUsing());
ExplorerCore.Log(CSharpConsole.Instance.Evaluator.GetUsing());
}
public static void Reset()
{
CSConsolePage.Instance.ResetConsole();
CSharpConsole.Instance.ResetConsole();
}
public static object CurrentTarget()

View File

@ -3,9 +3,11 @@ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityExplorer.Helpers;
using UnityExplorer.Core;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI.Main.CSConsole;
namespace UnityExplorer.CSConsole
namespace UnityExplorer.Core.CSharp
{
public struct Suggestion
{
@ -48,7 +50,7 @@ namespace UnityExplorer.CSConsole
public static HashSet<string> Namespaces => m_namspaces ?? GetNamespaces();
private static HashSet<string> m_namspaces;
public static HashSet<string> Keywords => m_keywords ?? (m_keywords = new HashSet<string>(CSharpLexer.validKeywordMatcher.Keywords));
public static HashSet<string> Keywords => m_keywords ?? (m_keywords = new HashSet<string>(CSLexerHighlighter.validKeywordMatcher.Keywords));
private static HashSet<string> m_keywords;
private static readonly Color keywordColor = new Color(80f / 255f, 150f / 255f, 215f / 255f);

View File

@ -0,0 +1,205 @@
using System;
using System.IO;
using UnityEngine;
using IniParser;
using IniParser.Parser;
using UnityExplorer.UI;
using System.Globalization;
using UnityExplorer.Core.Inspectors;
using UnityExplorer.UI.Main;
namespace UnityExplorer.Core.Config
{
public class ExplorerConfig
{
public static ExplorerConfig Instance;
internal static readonly IniDataParser _parser = new IniDataParser();
internal static readonly string INI_PATH = Path.Combine(ExplorerCore.Loader.ConfigFolder, "config.ini");
internal static CultureInfo _enCulture = new CultureInfo("en-US");
// Actual configs
public KeyCode Main_Menu_Toggle = KeyCode.F7;
public bool Force_Unlock_Mouse = true;
public int Default_Page_Limit = 25;
public string Default_Output_Path = Path.Combine(ExplorerCore.EXPLORER_FOLDER, "Output");
public bool Log_Unity_Debug = false;
public bool Hide_On_Startup = false;
public string Window_Anchors = DEFAULT_WINDOW_ANCHORS;
public int Active_Tab = 0;
public bool DebugConsole_Hidden = false;
public bool SceneExplorer_Hidden = false;
private const string DEFAULT_WINDOW_ANCHORS = "0.25,0.10,0.78,0.95";
public static event Action OnConfigChanged;
internal static void InvokeConfigChanged()
{
OnConfigChanged?.Invoke();
}
public static void OnLoad()
{
Instance = new ExplorerConfig();
_parser.Configuration.CommentString = "#";
PanelDragger.OnFinishResize += PanelDragger_OnFinishResize;
SceneExplorer.OnToggleShow += SceneExplorer_OnToggleShow;
DebugConsole.OnToggleShow += DebugConsole_OnToggleShow;
MainMenu.OnActiveTabChanged += MainMenu_OnActiveTabChanged;
if (LoadSettings())
return;
SaveSettings();
}
public static bool LoadSettings()
{
if (!File.Exists(INI_PATH))
return false;
string ini = File.ReadAllText(INI_PATH);
var data = _parser.Parse(ini);
foreach (var config in data.Sections["Config"])
{
switch (config.KeyName)
{
case nameof(Main_Menu_Toggle):
Instance.Main_Menu_Toggle = (KeyCode)Enum.Parse(typeof(KeyCode), config.Value);
break;
case nameof(Force_Unlock_Mouse):
Instance.Force_Unlock_Mouse = bool.Parse(config.Value);
break;
case nameof(Default_Page_Limit):
Instance.Default_Page_Limit = int.Parse(config.Value);
break;
case nameof(Log_Unity_Debug):
Instance.Log_Unity_Debug = bool.Parse(config.Value);
break;
case nameof(Default_Output_Path):
Instance.Default_Output_Path = config.Value;
break;
case nameof(Hide_On_Startup):
Instance.Hide_On_Startup = bool.Parse(config.Value);
break;
case nameof(Window_Anchors):
Instance.Window_Anchors = config.Value;
break;
case nameof(Active_Tab):
Instance.Active_Tab = int.Parse(config.Value);
break;
case nameof(DebugConsole_Hidden):
Instance.DebugConsole_Hidden = bool.Parse(config.Value);
break;
case nameof(SceneExplorer_Hidden):
Instance.SceneExplorer_Hidden = bool.Parse(config.Value);
break;
}
}
return true;
}
public static void SaveSettings()
{
var data = new IniParser.Model.IniData();
data.Sections.AddSection("Config");
var sec = data.Sections["Config"];
sec.AddKey(nameof(Main_Menu_Toggle), Instance.Main_Menu_Toggle.ToString());
sec.AddKey(nameof(Force_Unlock_Mouse), Instance.Force_Unlock_Mouse.ToString());
sec.AddKey(nameof(Default_Page_Limit), Instance.Default_Page_Limit.ToString());
sec.AddKey(nameof(Log_Unity_Debug), Instance.Log_Unity_Debug.ToString());
sec.AddKey(nameof(Default_Output_Path), Instance.Default_Output_Path);
sec.AddKey(nameof(Hide_On_Startup), Instance.Hide_On_Startup.ToString());
sec.AddKey(nameof(Window_Anchors), GetWindowAnchorsString());
sec.AddKey(nameof(Active_Tab), Instance.Active_Tab.ToString());
sec.AddKey(nameof(DebugConsole_Hidden), Instance.DebugConsole_Hidden.ToString());
sec.AddKey(nameof(SceneExplorer_Hidden), Instance.SceneExplorer_Hidden.ToString());
if (!Directory.Exists(ExplorerCore.Loader.ConfigFolder))
Directory.CreateDirectory(ExplorerCore.Loader.ConfigFolder);
File.WriteAllText(INI_PATH, data.ToString());
}
private static void SceneExplorer_OnToggleShow()
{
Instance.SceneExplorer_Hidden = SceneExplorer.UI.Hiding;
SaveSettings();
}
private static void DebugConsole_OnToggleShow()
{
Instance.DebugConsole_Hidden = DebugConsole.Hiding;
SaveSettings();
}
private static void MainMenu_OnActiveTabChanged(int page)
{
Instance.Active_Tab = page;
SaveSettings();
}
// ============ Window Anchors specific stuff ============== //
private static void PanelDragger_OnFinishResize()
{
Instance.Window_Anchors = GetWindowAnchorsString();
SaveSettings();
}
internal Vector4 GetWindowAnchorsVector()
{
try
{
var split = Window_Anchors.Split(',');
if (split.Length != 4)
throw new Exception();
Vector4 ret = Vector4.zero;
ret.x = float.Parse(split[0], _enCulture);
ret.y = float.Parse(split[1], _enCulture);
ret.z = float.Parse(split[2], _enCulture);
ret.w = float.Parse(split[3], _enCulture);
return ret;
}
catch
{
return DefaultWindowAnchors();
}
}
internal static string GetWindowAnchorsString()
{
try
{
var rect = PanelDragger.Instance.Panel;
return string.Format(_enCulture, "{0},{1},{2},{3}", new object[]
{
rect.anchorMin.x,
rect.anchorMin.y,
rect.anchorMax.x,
rect.anchorMax.y
});
}
catch
{
return DEFAULT_WINDOW_ANCHORS;
}
}
internal static Vector4 DefaultWindowAnchors()
{
Instance.Window_Anchors = DEFAULT_WINDOW_ANCHORS;
return new Vector4(0.25f, 0.1f, 0.78f, 0.95f);
}
}
}

View File

@ -1,7 +1,7 @@
using UnityEngine;
using UnityEngine.EventSystems;
namespace UnityExplorer.Input
namespace UnityExplorer.Core.Input
{
public interface IHandleInput
{

View File

@ -1,13 +1,9 @@
using System;
using UnityEngine;
using UnityExplorer.Helpers;
using System.Diagnostics.CodeAnalysis;
using UnityEngine.EventSystems;
#if CPP
using UnhollowerBaseLib;
#endif
namespace UnityExplorer.Input
namespace UnityExplorer.Core.Input
{
public enum InputType
{
@ -43,12 +39,12 @@ namespace UnityExplorer.Input
public static void Init()
{
if (InputSystem.TKeyboard != null || (ReflectionHelpers.LoadModule("Unity.InputSystem") && InputSystem.TKeyboard != null))
if (InputSystem.TKeyboard != null || (ReflectionUtility.LoadModule("Unity.InputSystem") && InputSystem.TKeyboard != null))
{
m_inputModule = new InputSystem();
CurrentType = InputType.InputSystem;
}
else if (LegacyInput.TInput != null || (ReflectionHelpers.LoadModule("UnityEngine.InputLegacyModule") && LegacyInput.TInput != null))
else if (LegacyInput.TInput != null || (ReflectionUtility.LoadModule("UnityEngine.InputLegacyModule") && LegacyInput.TInput != null))
{
m_inputModule = new LegacyInput();
CurrentType = InputType.Legacy;

View File

@ -1,12 +1,12 @@
using System;
using System.Reflection;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityExplorer.UI;
using System.Collections.Generic;
namespace UnityExplorer.Input
namespace UnityExplorer.Core.Input
{
public class InputSystem : IHandleInput
{
@ -17,7 +17,7 @@ namespace UnityExplorer.Input
m_kbCurrentProp = TKeyboard.GetProperty("current");
m_kbIndexer = TKeyboard.GetProperty("Item", new Type[] { TKey });
var btnControl = ReflectionHelpers.GetTypeByName("UnityEngine.InputSystem.Controls.ButtonControl");
var btnControl = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Controls.ButtonControl");
m_btnIsPressedProp = btnControl.GetProperty("isPressed");
m_btnWasPressedProp = btnControl.GetProperty("wasPressedThisFrame");
@ -25,21 +25,21 @@ namespace UnityExplorer.Input
m_leftButtonProp = TMouse.GetProperty("leftButton");
m_rightButtonProp = TMouse.GetProperty("rightButton");
m_positionProp = ReflectionHelpers.GetTypeByName("UnityEngine.InputSystem.Pointer")
m_positionProp = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Pointer")
.GetProperty("position");
m_readVector2InputMethod = ReflectionHelpers.GetTypeByName("UnityEngine.InputSystem.InputControl`1")
m_readVector2InputMethod = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.InputControl`1")
.MakeGenericType(typeof(Vector2))
.GetMethod("ReadValue");
}
public static Type TKeyboard => m_tKeyboard ?? (m_tKeyboard = ReflectionHelpers.GetTypeByName("UnityEngine.InputSystem.Keyboard"));
public static Type TKeyboard => m_tKeyboard ?? (m_tKeyboard = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Keyboard"));
private static Type m_tKeyboard;
public static Type TMouse => m_tMouse ?? (m_tMouse = ReflectionHelpers.GetTypeByName("UnityEngine.InputSystem.Mouse"));
public static Type TMouse => m_tMouse ?? (m_tMouse = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Mouse"));
private static Type m_tMouse;
public static Type TKey => m_tKey ?? (m_tKey = ReflectionHelpers.GetTypeByName("UnityEngine.InputSystem.Key"));
public static Type TKey => m_tKey ?? (m_tKey = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Key"));
private static Type m_tKey;
private static PropertyInfo m_btnIsPressedProp;

View File

@ -1,11 +1,11 @@
using System;
using System.Reflection;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityExplorer.UI;
namespace UnityExplorer.Input
namespace UnityExplorer.Core.Input
{
public class LegacyInput : IHandleInput
{
@ -20,7 +20,7 @@ namespace UnityExplorer.Input
m_getMouseButtonDownMethod = TInput.GetMethod("GetMouseButtonDown", new Type[] { typeof(int) });
}
public static Type TInput => m_tInput ?? (m_tInput = ReflectionHelpers.GetTypeByName("UnityEngine.Input"));
public static Type TInput => m_tInput ?? (m_tInput = ReflectionUtility.GetTypeByName("UnityEngine.Input"));
private static Type m_tInput;
private static PropertyInfo m_mousePositionProp;

View File

@ -1,7 +1,7 @@
using UnityEngine;
using UnityEngine.EventSystems;
namespace UnityExplorer.Input
namespace UnityExplorer.Core.Input
{
// Just a stub for games where no Input module was able to load at all.

View File

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
using UnityExplorer.UI.Main;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityExplorer.Core.Inspectors.Reflection;
using UnityExplorer.Core.Runtime;
using UnityExplorer.UI.Main.Home;
namespace UnityExplorer.Core.Inspectors
{
public class InspectorManager
{
public static InspectorManager Instance { get; private set; }
internal static InspectorManagerUI UI;
public InspectorManager()
{
Instance = this;
UI = new InspectorManagerUI();
UI.ConstructInspectorPane();
}
public InspectorBase m_activeInspector;
public readonly List<InspectorBase> m_currentInspectors = new List<InspectorBase>();
public void Update()
{
for (int i = 0; i < m_currentInspectors.Count; i++)
{
if (i >= m_currentInspectors.Count)
break;
m_currentInspectors[i].Update();
}
}
public void Inspect(object obj, CacheObjectBase parentMember = null)
{
obj = ReflectionProvider.Instance.Cast(obj, ReflectionProvider.Instance.GetActualType(obj));
UnityEngine.Object unityObj = obj as UnityEngine.Object;
if (obj.IsNullOrDestroyed(false))
{
return;
}
// check if currently inspecting this object
foreach (InspectorBase tab in m_currentInspectors)
{
if (ReferenceEquals(obj, tab.Target))
{
SetInspectorTab(tab);
return;
}
#if CPP
else if (unityObj && tab.Target is UnityEngine.Object uTabObj)
{
if (unityObj.m_CachedPtr == uTabObj.m_CachedPtr)
{
SetInspectorTab(tab);
return;
}
}
#endif
}
InspectorBase inspector;
if (obj is GameObject go)
inspector = new GameObjectInspector(go);
else
inspector = new InstanceInspector(obj);
if (inspector is ReflectionInspector ri)
ri.ParentMember = parentMember;
m_currentInspectors.Add(inspector);
SetInspectorTab(inspector);
}
public void Inspect(Type type)
{
if (type == null)
{
ExplorerCore.LogWarning("The provided type was null!");
return;
}
foreach (var tab in m_currentInspectors.Where(x => x is StaticInspector))
{
if (ReferenceEquals(tab.Target as Type, type))
{
SetInspectorTab(tab);
return;
}
}
var inspector = new StaticInspector(type);
m_currentInspectors.Add(inspector);
SetInspectorTab(inspector);
}
public void SetInspectorTab(InspectorBase inspector)
{
MainMenu.Instance.SetPage(HomePage.Instance);
if (m_activeInspector == inspector)
return;
UnsetInspectorTab();
m_activeInspector = inspector;
inspector.SetActive();
UI.OnSetInspectorTab(inspector);
}
public void UnsetInspectorTab()
{
if (m_activeInspector == null)
return;
m_activeInspector.SetInactive();
UI.OnUnsetInspectorTab();
m_activeInspector = null;
}
}
}

View File

@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityExplorer.UI;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Core.Runtime;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI.Main.Home.Inspectors;
namespace UnityExplorer.Core.Inspectors
{
public class GameObjectInspector : InspectorBase
{
public override string TabLabel => $" <color=cyan>[G]</color> {TargetGO?.name}";
public static GameObjectInspector ActiveInstance { get; private set; }
public GameObject TargetGO;
public GameObjectInspectorUI UIModule;
// sub modules
internal static ChildList s_childList;
internal static ComponentList s_compList;
internal static GameObjectControls s_controls;
internal static bool m_UIConstructed;
public GameObjectInspector(GameObject target) : base(target)
{
ActiveInstance = this;
TargetGO = target;
if (!TargetGO)
{
ExplorerCore.LogWarning("Target GameObject is null!");
return;
}
// one UI is used for all gameobject inspectors. no point recreating it.
if (!m_UIConstructed)
{
m_UIConstructed = true;
s_childList = new ChildList();
s_compList = new ComponentList();
s_controls = new GameObjectControls();
UIModule.ConstructUI();
}
}
public override void SetActive()
{
base.SetActive();
ActiveInstance = this;
}
public override void SetInactive()
{
base.SetInactive();
ActiveInstance = null;
}
internal void ChangeInspectorTarget(GameObject newTarget)
{
if (!newTarget)
return;
this.Target = this.TargetGO = newTarget;
}
// Update
public override void Update()
{
base.Update();
if (m_pendingDestroy || !this.IsActive)
return;
UIModule.RefreshTopInfo();
s_childList.RefreshChildObjectList();
s_compList.RefreshComponentList();
s_controls.RefreshControls();
if (GameObjectControls.s_sliderChangedWanted)
GameObjectControls.UpdateSliderControl();
}
public override void CreateUIModule()
{
base.BaseUI = UIModule = new GameObjectInspectorUI();
}
}
}

View File

@ -0,0 +1,294 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityExplorer.Core;
using UnityExplorer.Core.Unity;
using UnityExplorer.Core.Input;
using UnityExplorer.Core.Runtime;
using UnityExplorer.UI;
using UnityExplorer.UI.Main;
using UnityExplorer.UI.Main.Home.Inspectors;
namespace UnityExplorer.Core.Inspectors
{
public class InspectUnderMouse
{
public enum MouseInspectMode
{
World,
UI
}
public static bool Enabled { get; set; }
public static MouseInspectMode Mode { get; set; }
private static GameObject s_lastHit;
private static Vector3 s_lastMousePos;
internal static MouseInspectorUI UI;
static InspectUnderMouse()
{
UI = new MouseInspectorUI();
}
private static readonly List<Graphic> _wasDisabledGraphics = new List<Graphic>();
private static readonly List<CanvasGroup> _wasDisabledCanvasGroups = new List<CanvasGroup>();
private static readonly List<GameObject> _objectsAddedCastersTo = new List<GameObject>();
public static void StartInspect(MouseInspectMode mode)
{
Mode = mode;
Enabled = true;
MainMenu.Instance.MainPanel.SetActive(false);
UI.s_UIContent.SetActive(true);
if (mode == MouseInspectMode.UI)
{
SetupUIRaycast();
}
}
internal static void ClearHitData()
{
s_lastHit = null;
UI.s_objNameLabel.text = "No hits...";
UI.s_objPathLabel.text = "";
}
public static void StopInspect()
{
Enabled = false;
MainMenu.Instance.MainPanel.SetActive(true);
UI.s_UIContent.SetActive(false);
if (Mode == MouseInspectMode.UI)
StopUIInspect();
ClearHitData();
}
internal static GraphicRaycaster[] m_gCasters;
public static void UpdateInspect()
{
if (InputManager.GetKeyDown(KeyCode.Escape))
{
StopInspect();
return;
}
var mousePos = InputManager.MousePosition;
if (mousePos != s_lastMousePos)
UpdatePosition(mousePos);
if (!UnityHelper.MainCamera)
return;
// actual inspect raycast
switch (Mode)
{
case MouseInspectMode.UI:
RaycastUI(mousePos); break;
case MouseInspectMode.World:
RaycastWorld(mousePos); break;
}
}
internal static void UpdatePosition(Vector2 mousePos)
{
s_lastMousePos = mousePos;
var inversePos = UIManager.CanvasRoot.transform.InverseTransformPoint(mousePos);
UI.s_mousePosLabel.text = $"<color=grey>Mouse Position:</color> {mousePos.ToString()}";
float yFix = mousePos.y < 120 ? 80 : -80;
UI.s_UIContent.transform.localPosition = new Vector3(inversePos.x, inversePos.y + yFix, 0);
}
internal static void OnHitGameObject(GameObject obj)
{
if (obj != s_lastHit)
{
s_lastHit = obj;
UI.s_objNameLabel.text = $"<b>Click to Inspect:</b> <color=cyan>{obj.name}</color>";
UI.s_objPathLabel.text = $"Path: {obj.transform.GetTransformPath(true)}";
}
if (InputManager.GetMouseButtonDown(0))
{
StopInspect();
InspectorManager.Instance.Inspect(obj);
}
}
// Collider raycasting
internal static void RaycastWorld(Vector2 mousePos)
{
var ray = UnityHelper.MainCamera.ScreenPointToRay(mousePos);
Physics.Raycast(ray, out RaycastHit hit, 1000f);
if (hit.transform)
{
var obj = hit.transform.gameObject;
OnHitGameObject(obj);
}
else
{
if (s_lastHit)
ClearHitData();
}
}
// UI Graphic raycasting
private static void SetupUIRaycast()
{
foreach (var obj in RuntimeProvider.Instance.FindObjectsOfTypeAll(typeof(Canvas)))
{
var canvas = obj.Cast(typeof(Canvas)) as Canvas;
if (!canvas || !canvas.enabled || !canvas.gameObject.activeInHierarchy)
continue;
if (!canvas.GetComponent<GraphicRaycaster>())
{
canvas.gameObject.AddComponent<GraphicRaycaster>();
//ExplorerCore.Log("Added raycaster to " + canvas.name);
_objectsAddedCastersTo.Add(canvas.gameObject);
}
}
// recache Graphic Raycasters each time we start
var casters = RuntimeProvider.Instance.FindObjectsOfTypeAll(typeof(GraphicRaycaster));
m_gCasters = new GraphicRaycaster[casters.Length];
for (int i = 0; i < casters.Length; i++)
{
m_gCasters[i] = casters[i].Cast(typeof(GraphicRaycaster)) as GraphicRaycaster;
}
// enable raycastTarget on Graphics
foreach (var obj in RuntimeProvider.Instance.FindObjectsOfTypeAll(typeof(Graphic)))
{
var graphic = obj.Cast(typeof(Graphic)) as Graphic;
if (!graphic || !graphic.enabled || graphic.raycastTarget || !graphic.gameObject.activeInHierarchy)
continue;
graphic.raycastTarget = true;
//ExplorerCore.Log("Enabled raycastTarget on " + graphic.name);
_wasDisabledGraphics.Add(graphic);
}
// enable blocksRaycasts on CanvasGroups
foreach (var obj in RuntimeProvider.Instance.FindObjectsOfTypeAll(typeof(CanvasGroup)))
{
var canvas = obj.Cast(typeof(CanvasGroup)) as CanvasGroup;
if (!canvas || !canvas.gameObject.activeInHierarchy || canvas.blocksRaycasts)
continue;
canvas.blocksRaycasts = true;
//ExplorerCore.Log("Enabled raycasts on " + canvas.name);
_wasDisabledCanvasGroups.Add(canvas);
}
}
internal static void RaycastUI(Vector2 mousePos)
{
var ped = new PointerEventData(null)
{
position = mousePos
};
#if MONO
var list = new List<RaycastResult>();
#else
var list = new Il2CppSystem.Collections.Generic.List<RaycastResult>();
#endif
//ExplorerCore.Log("~~~~~~~~~ begin raycast ~~~~~~~~");
GameObject hitObject = null;
int highestLayer = int.MinValue;
int highestOrder = int.MinValue;
int highestDepth = int.MinValue;
foreach (var gr in m_gCasters)
{
gr.Raycast(ped, list);
if (list.Count > 0)
{
foreach (var hit in list)
{
if (!hit.gameObject)
continue;
if (hit.gameObject.GetComponent<CanvasGroup>() is CanvasGroup group && group.alpha == 0)
continue;
if (hit.gameObject.GetComponent<Graphic>() is Graphic graphic && graphic.color.a == 0f)
continue;
//ExplorerCore.Log("Hit: " + hit.gameObject.name + ", depth: " + hit.depth + ", layer: " + hit.sortingLayer + ", order: " + hit.sortingOrder);
if (hit.sortingLayer < highestLayer)
continue;
if (hit.sortingLayer > highestLayer)
{
highestLayer = hit.sortingLayer;
highestOrder = int.MinValue;
}
if (hit.depth < highestDepth)
continue;
if (hit.depth > highestDepth)
{
highestDepth = hit.depth;
highestOrder = int.MinValue;
}
if (hit.sortingOrder <= highestOrder)
continue;
highestOrder = hit.sortingOrder;
hitObject = hit.gameObject;
}
}
else
{
if (s_lastHit)
ClearHitData();
}
}
if (hitObject)
OnHitGameObject(hitObject);
//ExplorerCore.Log("~~~~~~~~~ end raycast ~~~~~~~~");
}
private static void StopUIInspect()
{
foreach (var obj in _objectsAddedCastersTo)
{
if (obj.GetComponent<GraphicRaycaster>() is GraphicRaycaster raycaster)
GameObject.Destroy(raycaster);
}
foreach (var graphic in _wasDisabledGraphics)
graphic.raycastTarget = false;
foreach (var canvas in _wasDisabledCanvasGroups)
canvas.blocksRaycasts = false;
_objectsAddedCastersTo.Clear();
_wasDisabledCanvasGroups.Clear();
_wasDisabledGraphics.Clear();
}
}
}

View File

@ -0,0 +1,92 @@
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
using UnityExplorer.UI.Main.Home.Inspectors;
namespace UnityExplorer.Core.Inspectors
{
public abstract class InspectorBase
{
public object Target;
public InspectorBaseUI BaseUI;
public abstract string TabLabel { get; }
public bool IsActive { get; private set; }
internal bool m_pendingDestroy;
public InspectorBase(object target)
{
Target = target;
if (Target.IsNullOrDestroyed(false))
{
Destroy();
return;
}
CreateUIModule();
BaseUI.AddInspectorTab(this);
}
public abstract void CreateUIModule();
public virtual void SetActive()
{
this.IsActive = true;
BaseUI.Content?.SetActive(true);
}
public virtual void SetInactive()
{
this.IsActive = false;
BaseUI.Content?.SetActive(false);
}
public virtual void Update()
{
if (Target.IsNullOrDestroyed(false))
{
Destroy();
return;
}
BaseUI.tabText.text = TabLabel;
}
public virtual void Destroy()
{
m_pendingDestroy = true;
GameObject tabGroup = BaseUI.tabButton?.transform.parent.gameObject;
if (tabGroup)
{
GameObject.Destroy(tabGroup);
}
int thisIndex = -1;
if (InspectorManager.Instance.m_currentInspectors.Contains(this))
{
thisIndex = InspectorManager.Instance.m_currentInspectors.IndexOf(this);
InspectorManager.Instance.m_currentInspectors.Remove(this);
}
if (ReferenceEquals(InspectorManager.Instance.m_activeInspector, this))
{
InspectorManager.Instance.UnsetInspectorTab();
if (InspectorManager.Instance.m_currentInspectors.Count > 0)
{
var prevTab = InspectorManager.Instance.m_currentInspectors[thisIndex > 0 ? thisIndex - 1 : 0];
InspectorManager.Instance.SetInspectorTab(prevTab);
}
}
}
}
}

View File

@ -7,7 +7,7 @@ using UnityExplorer.UI;
using UnityEngine;
using UnityEngine.UI;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class CacheEnumerated : CacheObjectBase
{

View File

@ -4,10 +4,9 @@ using System.Linq;
using System.Text;
using System.Reflection;
using UnityExplorer.UI;
using UnityExplorer.Helpers;
using UnityEngine;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class CacheField : CacheMember
{
@ -33,6 +32,9 @@ namespace UnityExplorer.Inspectors.Reflection
{
var fi = MemInfo as FieldInfo;
fi.SetValue(fi.IsStatic ? null : DeclaringInstance, IValue.Value);
if (this.ParentInspector?.ParentMember != null)
this.ParentInspector.ParentMember.SetValue();
}
}
}

View File

@ -5,13 +5,13 @@ using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.UI;
using UnityExplorer.UI.Shared;
using UnityExplorer.Helpers;
#if CPP
using UnhollowerBaseLib;
#endif
using UnityExplorer.UI.Reusable;
using UnityExplorer.Core.Unity;
using UnityExplorer.Core.Runtime;
using UnityExplorer.Core;
using UnityExplorer.UI.Utility;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public abstract class CacheMember : CacheObjectBase
{
@ -19,6 +19,7 @@ namespace UnityExplorer.Inspectors.Reflection
public override Type FallbackType { get; }
public ReflectionInspector ParentInspector { get; set; }
public MemberInfo MemInfo { get; set; }
public Type DeclaringType { get; set; }
public object DeclaringInstance { get; set; }
@ -49,10 +50,8 @@ namespace UnityExplorer.Inspectors.Reflection
DeclaringType = memberInfo.DeclaringType;
DeclaringInstance = declaringInstance;
this.m_parentContent = parentContent;
#if CPP
if (DeclaringInstance != null)
DeclaringInstance = DeclaringInstance.Il2CppCast(DeclaringType);
#endif
DeclaringInstance = ReflectionProvider.Instance.Cast(declaringInstance, DeclaringType);
}
public static bool CanProcessArgs(ParameterInfo[] parameters)
@ -86,19 +85,19 @@ namespace UnityExplorer.Inspectors.Reflection
{
try
{
#if CPP
if (!IsReflectionSupported())
throw new Exception("Type not supported with Reflection");
#endif
Type baseType = ReflectionUtility.GetType(IValue.Value) ?? FallbackType;
if (!ReflectionProvider.Instance.IsReflectionSupported(baseType))
throw new Exception("Type not supported with reflection");
UpdateReflection();
#if CPP
if (IValue.Value != null)
IValue.Value = IValue.Value.Il2CppCast(ReflectionHelpers.GetActualType(IValue.Value));
#endif
IValue.Value = IValue.Value.Cast(ReflectionUtility.GetType(IValue.Value));
}
catch (Exception e)
{
ReflectionException = ReflectionHelpers.ExceptionToString(e, true);
ReflectionException = e.ReflectionExToString(true);
}
}
@ -178,46 +177,9 @@ namespace UnityExplorer.Inspectors.Reflection
private string GetRichTextName()
{
return m_richTextName = UISyntaxHighlight.ParseFullSyntax(MemInfo.DeclaringType, false, MemInfo);
return m_richTextName = SignatureHighlighter.ParseFullSyntax(MemInfo.DeclaringType, false, MemInfo);
}
#if CPP
internal bool IsReflectionSupported()
{
try
{
var baseType = ReflectionHelpers.GetActualType(IValue.Value) ?? IValue.FallbackType;
var gArgs = baseType.GetGenericArguments();
if (gArgs.Length < 1)
return true;
foreach (var arg in gArgs)
{
if (!Check(arg))
return false;
}
return true;
bool Check(Type type)
{
if (!typeof(Il2CppSystem.Object).IsAssignableFrom(type))
return true;
if (!ReflectionHelpers.Il2CppTypeNotNull(type, out IntPtr ptr))
return false;
return Il2CppSystem.Type.internal_from_handle(IL2CPP.il2cpp_class_get_type(ptr)) is Il2CppSystem.Type;
}
}
catch
{
return false;
}
}
#endif
#region UI
internal float GetMemberLabelWidth(RectTransform scrollRect)
@ -262,8 +224,8 @@ namespace UnityExplorer.Inspectors.Reflection
var topGroup = topGroupObj.GetComponent<HorizontalLayoutGroup>();
topGroup.childForceExpandHeight = false;
topGroup.childForceExpandWidth = false;
topGroup.childControlHeight = true;
topGroup.childControlWidth = true;
topGroup.SetChildControlHeight(true);
topGroup.SetChildControlWidth(true);
topGroup.spacing = 10;
topGroup.padding.left = 3;
topGroup.padding.right = 3;
@ -281,8 +243,8 @@ namespace UnityExplorer.Inspectors.Reflection
var leftGroup = m_leftGroup.GetComponent<HorizontalLayoutGroup>();
leftGroup.childForceExpandHeight = true;
leftGroup.childForceExpandWidth = false;
leftGroup.childControlHeight = true;
leftGroup.childControlWidth = true;
leftGroup.SetChildControlHeight(true);
leftGroup.SetChildControlWidth(true);
leftGroup.spacing = 4;
// member label
@ -316,8 +278,8 @@ namespace UnityExplorer.Inspectors.Reflection
var rightGroup = m_rightGroup.GetComponent<VerticalLayoutGroup>();
rightGroup.childForceExpandHeight = true;
rightGroup.childForceExpandWidth = false;
rightGroup.childControlHeight = true;
rightGroup.childControlWidth = true;
rightGroup.SetChildControlHeight(true);
rightGroup.SetChildControlWidth(true);
rightGroup.spacing = 2;
rightGroup.padding.top = 4;
rightGroup.padding.bottom = 2;
@ -379,8 +341,8 @@ namespace UnityExplorer.Inspectors.Reflection
var argLabelLayout = argLabelObj.AddComponent<LayoutElement>();
argLabelLayout.minHeight = 25;
var argText = argLabelObj.GetComponent<Text>();
var argTypeTxt = UISyntaxHighlight.ParseFullSyntax(arg.ParameterType, false);
argText.text = $"{argTypeTxt} <color={UISyntaxHighlight.Local}>{arg.Name}</color>";
var argTypeTxt = SignatureHighlighter.ParseFullSyntax(arg.ParameterType, false);
argText.text = $"{argTypeTxt} <color={SignatureHighlighter.LOCAL_ARG}>{arg.Name}</color>";
var argInputObj = UIFactory.CreateInputField(rowObj, 14, (int)TextAnchor.MiddleLeft, 1);
var argInputLayout = argInputObj.AddComponent<LayoutElement>();

View File

@ -5,9 +5,11 @@ using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityExplorer.Core;
using UnityExplorer.UI.Utility;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class CacheMethod : CacheMember
{
@ -75,7 +77,7 @@ namespace UnityExplorer.Inspectors.Reflection
e = e.InnerException;
ExplorerCore.LogWarning($"Exception evaluating: {e.GetType()}, {e.Message}");
ReflectionException = ReflectionHelpers.ExceptionToString(e);
ReflectionException = ReflectionUtility.ReflectionExToString(e);
}
IValue.Value = ret;
@ -90,7 +92,7 @@ namespace UnityExplorer.Inspectors.Reflection
for (int i = 0; i < GenericArgs.Length; i++)
{
var input = m_genericArgInput[i];
if (ReflectionHelpers.GetTypeByName(input) is Type t)
if (ReflectionUtility.GetTypeByName(input) is Type t)
{
if (GenericConstraints[i].Length == 0)
{
@ -150,7 +152,7 @@ namespace UnityExplorer.Inspectors.Reflection
if (constrainTxt != "")
constrainTxt += ", ";
constrainTxt += $"{UISyntaxHighlight.ParseFullSyntax(constraint, false)}";
constrainTxt += $"{SignatureHighlighter.ParseFullSyntax(constraint, false)}";
}
}
else
@ -168,7 +170,7 @@ namespace UnityExplorer.Inspectors.Reflection
//var argLayout = argLabelObj.AddComponent<LayoutElement>();
//argLayout.minWidth = 20;
var argText = argLabelObj.GetComponent<Text>();
argText.text = $"{constrainTxt} <color={UISyntaxHighlight.Enum}>{arg.Name}</color>";
argText.text = $"{constrainTxt} <color={SignatureHighlighter.CONST_VAR}>{arg.Name}</color>";
var argInputObj = UIFactory.CreateInputField(rowObj, 14, (int)TextAnchor.MiddleLeft, 1);
var argInputLayout = argInputObj.AddComponent<LayoutElement>();

View File

@ -4,11 +4,12 @@ using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityExplorer.UI;
using UnityExplorer.UI.Shared;
using UnityExplorer.Helpers;
using UnityExplorer.UI.Reusable;
using UnityExplorer.Core.Unity;
using UnityEngine.UI;
using UnityExplorer.Core;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public abstract class CacheObjectBase
{
@ -54,7 +55,7 @@ namespace UnityExplorer.Inspectors.Reflection
// if the type has changed fundamentally, make a new interactivevalue for it
var type = value == null
? FallbackType
: ReflectionHelpers.GetActualType(value);
: ReflectionUtility.GetType(value);
var ivalueType = InteractiveValue.GetIValueForType(type);
@ -91,9 +92,9 @@ namespace UnityExplorer.Inspectors.Reflection
m_mainRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 25);
var mainGroup = m_mainContent.GetComponent<VerticalLayoutGroup>();
mainGroup.childForceExpandWidth = true;
mainGroup.childControlWidth = true;
mainGroup.SetChildControlWidth(true);
mainGroup.childForceExpandHeight = true;
mainGroup.childControlHeight = true;
mainGroup.SetChildControlHeight(true);
var mainLayout = m_mainContent.AddComponent<LayoutElement>();
mainLayout.minHeight = 25;
mainLayout.flexibleHeight = 9999;

View File

@ -8,7 +8,7 @@ using UnityEngine;
using UnityEngine.UI;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public enum PairTypes
{

View File

@ -4,10 +4,10 @@ using System.Linq;
using System.Text;
using System.Reflection;
using UnityExplorer.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityEngine;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class CacheProperty : CacheMember
{
@ -63,6 +63,9 @@ namespace UnityExplorer.Inspectors.Reflection
var target = pi.GetAccessors()[0].IsStatic ? null : DeclaringInstance;
pi.SetValue(target, IValue.Value, ParseArguments());
if (this.ParentInspector?.ParentMember != null)
this.ParentInspector.ParentMember.SetValue();
}
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Reflection;
using UnityEngine;
using UnityExplorer.UI;
using UnityEngine.UI;
using System.IO;
using UnityExplorer.Core.Runtime;
using UnityExplorer.UI.Main.Home.Inspectors;
namespace UnityExplorer.Core.Inspectors.Reflection
{
public enum MemberScopes
{
All,
Instance,
Static
}
public class InstanceInspector : ReflectionInspector
{
public override string TabLabel => $" <color=cyan>[R]</color> {base.TabLabel}";
internal MemberScopes m_scopeFilter;
internal Button m_lastActiveScopeButton;
public InstanceInspector(object target) : base(target) { }
internal InstanceInspectorUI InstanceUI;
public void CreateInstanceUIModule()
{
InstanceUI = new InstanceInspectorUI(this);
}
internal void OnScopeFilterClicked(MemberScopes type, Button button)
{
if (m_lastActiveScopeButton)
{
var lastColors = m_lastActiveScopeButton.colors;
lastColors.normalColor = new Color(0.2f, 0.2f, 0.2f);
m_lastActiveScopeButton.colors = lastColors;
}
m_scopeFilter = type;
m_lastActiveScopeButton = button;
var colors = m_lastActiveScopeButton.colors;
colors.normalColor = new Color(0.2f, 0.6f, 0.2f);
m_lastActiveScopeButton.colors = colors;
FilterMembers(null, true);
base.ReflectionUI.m_sliderScroller.m_slider.value = 1f;
}
}
}

View File

@ -4,10 +4,10 @@ using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveBool : InteractiveValue
{

View File

@ -5,16 +5,16 @@ using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Config;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Config;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
using UnityExplorer.UI.Shared;
using UnityExplorer.UI.Reusable;
using System.Reflection;
#if CPP
using CppDictionary = Il2CppSystem.Collections.IDictionary;
#endif
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveDictionary : InteractiveValue
{
@ -59,7 +59,7 @@ namespace UnityExplorer.Inspectors.Reflection
= new List<KeyValuePair<CachePaired, CachePaired>>();
internal readonly KeyValuePair<CachePaired, CachePaired>[] m_displayedEntries
= new KeyValuePair<CachePaired, CachePaired>[ModConfig.Instance.Default_Page_Limit];
= new KeyValuePair<CachePaired, CachePaired>[ExplorerConfig.Instance.Default_Page_Limit];
internal bool m_recacheWanted = true;
@ -296,7 +296,7 @@ namespace UnityExplorer.Inspectors.Reflection
var scrollGroup = m_listContent.GetComponent<VerticalLayoutGroup>();
scrollGroup.childForceExpandHeight = true;
scrollGroup.childControlHeight = true;
scrollGroup.SetChildControlHeight(true);
scrollGroup.spacing = 2;
scrollGroup.padding.top = 5;
scrollGroup.padding.left = 5;

View File

@ -4,10 +4,10 @@ using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveEnum : InteractiveValue
{
@ -47,13 +47,34 @@ namespace UnityExplorer.Inspectors.Reflection
var list = new List<KeyValuePair<int, string>>();
var set = new HashSet<string>();
foreach (var value in values)
{
var name = value.ToString();
if (set.Contains(name))
continue;
set.Add(name);
list.Add(new KeyValuePair<int, string>((int)value, name));
var backingType = Enum.GetUnderlyingType(type);
int intValue;
try
{
// this approach is necessary, a simple '(int)value' is not sufficient.
var unbox = Convert.ChangeType(value, backingType);
intValue = (int)Convert.ChangeType(unbox, typeof(int));
}
catch (Exception ex)
{
ExplorerCore.LogWarning("[InteractiveEnum] Could not Unbox underlying type " + backingType.Name + " from " + type.FullName);
ExplorerCore.Log(ex.ToString());
continue;
}
list.Add(new KeyValuePair<int, string>(intValue, name));
}
s_enumNamesCache.Add(type, list.ToArray());

View File

@ -6,12 +6,12 @@ using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Config;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Config;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
using UnityExplorer.UI.Shared;
using UnityExplorer.UI.Reusable;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveEnumerable : InteractiveValue
{
@ -46,7 +46,7 @@ namespace UnityExplorer.Inspectors.Reflection
internal readonly Type m_baseEntryType;
internal readonly List<CacheEnumerated> m_entries = new List<CacheEnumerated>();
internal readonly CacheEnumerated[] m_displayedEntries = new CacheEnumerated[ModConfig.Instance.Default_Page_Limit];
internal readonly CacheEnumerated[] m_displayedEntries = new CacheEnumerated[ExplorerConfig.Instance.Default_Page_Limit];
internal bool m_recacheWanted = true;
public override void OnValueUpdated()
@ -270,7 +270,7 @@ namespace UnityExplorer.Inspectors.Reflection
var scrollGroup = m_listContent.GetComponent<VerticalLayoutGroup>();
scrollGroup.childForceExpandHeight = true;
scrollGroup.childControlHeight = true;
scrollGroup.SetChildControlHeight(true);
scrollGroup.spacing = 2;
scrollGroup.padding.top = 5;
scrollGroup.padding.left = 5;

View File

@ -4,10 +4,10 @@ using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveFlags : InteractiveEnum
{
@ -98,8 +98,8 @@ namespace UnityExplorer.Inspectors.Reflection
var group = groupObj.GetComponent<VerticalLayoutGroup>();
group.childForceExpandHeight = true;
group.childForceExpandWidth = false;
group.childControlHeight = true;
group.childControlWidth = true;
group.SetChildControlHeight(true);
group.SetChildControlWidth(true);
group.padding.top = 3;
group.padding.left = 3;
group.padding.right = 3;

View File

@ -5,10 +5,12 @@ using System.Text;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
using UnityExplorer.Core;
using UnityExplorer.UI.Utility;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveNumber : InteractiveValue
{
@ -46,7 +48,7 @@ namespace UnityExplorer.Inspectors.Reflection
return;
}
m_baseLabel.text = UISyntaxHighlight.ParseFullSyntax(FallbackType, false);
m_baseLabel.text = SignatureHighlighter.ParseFullSyntax(FallbackType, false);
m_valueInput.text = Value.ToString();
var type = Value.GetType();
@ -84,7 +86,7 @@ namespace UnityExplorer.Inspectors.Reflection
}
catch (Exception e)
{
ExplorerCore.LogWarning("Could not parse input! " + ReflectionHelpers.ExceptionToString(e, true));
ExplorerCore.LogWarning("Could not parse input! " + ReflectionUtility.ReflectionExToString(e, true));
}
}

View File

@ -5,10 +5,11 @@ using System.Text;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
using UnityExplorer.UI.Utility;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveString : InteractiveValue
{
@ -109,7 +110,7 @@ namespace UnityExplorer.Inspectors.Reflection
base.ConstructUI(parent, subGroup);
GetDefaultLabel(false);
m_richValueType = UISyntaxHighlight.ParseFullSyntax(FallbackType, false);
m_richValueType = SignatureHighlighter.ParseFullSyntax(FallbackType, false);
m_labelLayout = m_baseLabel.gameObject.GetComponent<LayoutElement>();
@ -154,9 +155,9 @@ namespace UnityExplorer.Inspectors.Reflection
hiddenLayout.flexibleWidth = 9000;
var hiddenGroup = m_hiddenObj.AddComponent<HorizontalLayoutGroup>();
hiddenGroup.childForceExpandWidth = true;
hiddenGroup.childControlWidth = true;
hiddenGroup.SetChildControlWidth(true);
hiddenGroup.childForceExpandHeight = true;
hiddenGroup.childControlHeight = true;
hiddenGroup.SetChildControlHeight(true);
var inputObj = UIFactory.CreateInputField(m_hiddenObj, 14, 3);
var inputLayout = inputObj.AddComponent<LayoutElement>();

View File

@ -4,10 +4,10 @@ using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
#region IStructInfo helper

View File

@ -5,43 +5,64 @@ using System.Reflection;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core;
using UnityExplorer.Core.Unity;
using UnityExplorer.Core.Runtime;
using UnityExplorer.UI;
using UnityExplorer.UI.Utility;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class InteractiveValue
{
/// <summary>
/// Get the <see cref="InteractiveValue"/> subclass which supports the provided <paramref name="type"/>.
/// </summary>
/// <param name="type">The <see cref="Type"/> which you want the <see cref="InteractiveValue"/> Type for.</param>
/// <returns>The best subclass of <see cref="InteractiveValue"/> which supports the provided <paramref name="type"/>.</returns>
public static Type GetIValueForType(Type type)
{
// rather ugly but I couldn't think of a cleaner way that was worth it.
// switch-case doesn't really work here.
// arbitrarily check some types, fastest methods first.
if (type == typeof(bool))
return typeof(InteractiveBool);
else if (type == typeof(string))
return typeof(InteractiveString);
// if type is primitive then it must be a number if its not a bool
else if (type.IsPrimitive)
return typeof(InteractiveNumber);
// check for strings
else if (type == typeof(string))
return typeof(InteractiveString);
// check for enum/flags
else if (typeof(Enum).IsAssignableFrom(type))
{
if (type.GetCustomAttributes(typeof(FlagsAttribute), true) is object[] attributes && attributes.Length > 0)
// NET 3.5 doesn't have "GetCustomAttribute", gotta use the multiple version.
if (type.GetCustomAttributes(typeof(FlagsAttribute), true) is object[] fa && fa.Any())
return typeof(InteractiveFlags);
else
return typeof(InteractiveEnum);
}
// check for unity struct types
else if (InteractiveUnityStruct.SupportsType(type))
return typeof(InteractiveUnityStruct);
// check Transform, force InteractiveValue so they dont become InteractiveEnumerables.
else if (typeof(Transform).IsAssignableFrom(type))
return typeof(InteractiveValue);
else if (ReflectionHelpers.IsDictionary(type))
// check Dictionaries before Enumerables
else if (ReflectionUtility.IsDictionary(type))
return typeof(InteractiveDictionary);
else if (ReflectionHelpers.IsEnumerable(type))
// finally check for Enumerables
else if (ReflectionUtility.IsEnumerable(type))
return typeof(InteractiveEnumerable);
// fallback to default
else
return typeof(InteractiveValue);
}
public static InteractiveValue Create(object value, Type fallbackType)
{
var type = ReflectionHelpers.GetActualType(value) ?? fallbackType;
var type = ReflectionUtility.GetType(value) ?? fallbackType;
var iType = GetIValueForType(type);
return (InteractiveValue)Activator.CreateInstance(iType, new object[] { value, type });
@ -176,11 +197,15 @@ namespace UnityExplorer.Inspectors.Reflection
ConstructSubcontent();
}
internal MethodInfo m_toStringMethod;
internal MethodInfo m_toStringFormatMethod;
internal bool m_gotToStringMethods;
public string GetDefaultLabel(bool updateType = true)
{
var valueType = Value?.GetType() ?? this.FallbackType;
if (updateType)
m_richValueType = UISyntaxHighlight.ParseFullSyntax(valueType, true);
m_richValueType = SignatureHighlighter.ParseFullSyntax(valueType, true);
if (!Owner.HasEvaluated)
return m_defaultLabel = $"<i><color=grey>Not yet evaluated</color> ({m_richValueType})</i>";
@ -190,6 +215,7 @@ namespace UnityExplorer.Inspectors.Reflection
string label;
// Two dirty fixes for TextAsset and EventSystem, which can have very long ToString results.
if (Value is TextAsset textAsset)
{
label = textAsset.text;
@ -203,22 +229,46 @@ namespace UnityExplorer.Inspectors.Reflection
{
label = m_richValueType;
}
else
else // For everything else...
{
var toString = (string)valueType.GetMethod("ToString", new Type[0])?.Invoke(Value, null)
?? Value.ToString();
if (!m_gotToStringMethods)
{
m_gotToStringMethods = true;
var fullnametemp = valueType.ToString();
if (fullnametemp.StartsWith("Il2CppSystem"))
fullnametemp = fullnametemp.Substring(6, fullnametemp.Length - 6);
m_toStringMethod = valueType.GetMethod("ToString", new Type[0]);
m_toStringFormatMethod = valueType.GetMethod("ToString", new Type[] { typeof(string) });
var temp = toString.Replace(fullnametemp, "").Trim();
// test format method actually works
try
{
m_toStringFormatMethod.Invoke(Value, new object[] { "F3" });
}
catch
{
m_toStringFormatMethod = null;
}
}
if (string.IsNullOrEmpty(temp))
string toString;
if (m_toStringFormatMethod != null)
toString = (string)m_toStringFormatMethod.Invoke(Value, new object[] { "F3" });
else
toString = (string)m_toStringMethod.Invoke(Value, new object[0]);
toString = toString ?? "";
string typeName = valueType.FullName;
if (typeName.StartsWith("Il2CppSystem."))
typeName = typeName.Substring(6, typeName.Length - 6);
toString = ReflectionProvider.Instance.ProcessTypeNameInString(valueType, toString, ref typeName);
// If the ToString is just the type name, use our syntax highlighted type name instead.
if (toString == typeName)
{
label = m_richValueType;
}
else
else // Otherwise, parse the result and put our highlighted name in.
{
if (toString.Length > 200)
toString = toString.Substring(0, 200) + "...";
@ -258,9 +308,9 @@ namespace UnityExplorer.Inspectors.Reflection
mainRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 25);
var mainGroup = m_valueContent.GetComponent<HorizontalLayoutGroup>();
mainGroup.childForceExpandWidth = false;
mainGroup.childControlWidth = true;
mainGroup.SetChildControlWidth(true);
mainGroup.childForceExpandHeight = false;
mainGroup.childControlHeight = true;
mainGroup.SetChildControlHeight(true);
mainGroup.spacing = 4;
mainGroup.childAlignment = TextAnchor.UpperLeft;
var mainLayout = m_valueContent.AddComponent<LayoutElement>();
@ -303,7 +353,7 @@ namespace UnityExplorer.Inspectors.Reflection
void OnInspectClicked()
{
if (!Value.IsNullOrDestroyed(false))
InspectorManager.Instance.Inspect(this.Value);
InspectorManager.Instance.Inspect(this.Value, this.Owner);
}
m_inspectButton.SetActive(false);

View File

@ -0,0 +1,360 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityExplorer.Core.Unity;
using UnityEngine;
using UnityExplorer.Core.Inspectors.Reflection;
using UnityExplorer.UI.Reusable;
using System.Reflection;
using UnityExplorer.UI;
using UnityEngine.UI;
using UnityExplorer.Core.Config;
using UnityExplorer.Core;
using UnityExplorer.UI.Utility;
using UnityExplorer.UI.Main.Home.Inspectors;
namespace UnityExplorer.Core.Inspectors
{
public class ReflectionInspector : InspectorBase
{
#region STATIC
public static ReflectionInspector ActiveInstance { get; private set; }
static ReflectionInspector()
{
PanelDragger.OnFinishResize += OnContainerResized;
SceneExplorer.OnToggleShow += OnContainerResized;
}
private static void OnContainerResized()
{
if (ActiveInstance == null)
return;
ActiveInstance.ReflectionUI.m_widthUpdateWanted = true;
}
// Blacklists
private static readonly HashSet<string> bl_typeAndMember = new HashSet<string>
{
#if CPP
// these cause a crash in IL2CPP
"Type.DeclaringMethod",
"Rigidbody2D.Cast",
"Collider2D.Cast",
"Collider2D.Raycast",
"Texture2D.SetPixelDataImpl",
"Camera.CalculateProjectionMatrixFromPhysicalProperties",
#endif
};
private static readonly HashSet<string> bl_memberNameStartsWith = new HashSet<string>
{
// these are redundant
"get_",
"set_",
};
#endregion
#region INSTANCE
public override string TabLabel => m_targetTypeShortName;
internal CacheObjectBase ParentMember { get; set; }
internal ReflectionInspectorUI ReflectionUI;
internal readonly Type m_targetType;
internal readonly string m_targetTypeShortName;
// all cached members of the target
internal CacheMember[] m_allMembers;
// filtered members based on current filters
internal readonly List<CacheMember> m_membersFiltered = new List<CacheMember>();
// actual shortlist of displayed members
internal readonly CacheMember[] m_displayedMembers = new CacheMember[ExplorerConfig.Instance.Default_Page_Limit];
internal bool m_autoUpdate;
public ReflectionInspector(object target) : base(target)
{
if (this is StaticInspector)
m_targetType = target as Type;
else
m_targetType = ReflectionUtility.GetType(target);
m_targetTypeShortName = SignatureHighlighter.ParseFullSyntax(m_targetType, false);
ReflectionUI.ConstructUI();
CacheMembers(m_targetType);
FilterMembers();
}
public override void CreateUIModule()
{
BaseUI = ReflectionUI = new ReflectionInspectorUI(this);
}
public override void SetActive()
{
base.SetActive();
ActiveInstance = this;
}
public override void SetInactive()
{
base.SetInactive();
ActiveInstance = null;
}
public override void Destroy()
{
base.Destroy();
if (this.BaseUI.Content)
GameObject.Destroy(this.BaseUI.Content);
}
internal void OnPageTurned()
{
RefreshDisplay();
}
internal bool IsBlacklisted(string sig) => bl_typeAndMember.Any(it => sig.Contains(it));
internal bool IsBlacklisted(MethodInfo method) => bl_memberNameStartsWith.Any(it => method.Name.StartsWith(it));
internal string GetSig(MemberInfo member) => $"{member.DeclaringType.Name}.{member.Name}";
internal string AppendArgsToSig(ParameterInfo[] args)
{
string ret = " (";
foreach (var param in args)
ret += $"{param.ParameterType.Name} {param.Name}, ";
ret += ")";
return ret;
}
public void CacheMembers(Type type)
{
var list = new List<CacheMember>();
var cachedSigs = new HashSet<string>();
var types = ReflectionUtility.GetAllBaseTypes(type);
var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
if (this is InstanceInspector)
flags |= BindingFlags.Instance;
foreach (var declaringType in types)
{
var target = Target;
target = target.Cast(declaringType);
IEnumerable<MemberInfo> infos = declaringType.GetMethods(flags);
infos = infos.Concat(declaringType.GetProperties(flags));
infos = infos.Concat(declaringType.GetFields(flags));
foreach (var member in infos)
{
try
{
var sig = GetSig(member);
//ExplorerCore.Log($"Trying to cache member {sig}...");
//ExplorerCore.Log(member.DeclaringType.FullName + "." + member.Name);
var mi = member as MethodInfo;
var pi = member as PropertyInfo;
var fi = member as FieldInfo;
if (IsBlacklisted(sig) || (mi != null && IsBlacklisted(mi)))
continue;
var args = mi?.GetParameters() ?? pi?.GetIndexParameters();
if (args != null)
{
if (!CacheMember.CanProcessArgs(args))
continue;
sig += AppendArgsToSig(args);
}
if (cachedSigs.Contains(sig))
continue;
cachedSigs.Add(sig);
if (mi != null)
list.Add(new CacheMethod(mi, target, ReflectionUI.m_scrollContent));
else if (pi != null)
list.Add(new CacheProperty(pi, target, ReflectionUI.m_scrollContent));
else
list.Add(new CacheField(fi, target, ReflectionUI.m_scrollContent));
list.Last().ParentInspector = this;
}
catch (Exception e)
{
ExplorerCore.LogWarning($"Exception caching member {member.DeclaringType.FullName}.{member.Name}!");
ExplorerCore.Log(e.ToString());
}
}
}
var typeList = types.ToList();
var sorted = new List<CacheMember>();
sorted.AddRange(list.Where(it => it is CacheMethod)
.OrderBy(it => typeList.IndexOf(it.DeclaringType))
.ThenBy(it => it.NameForFiltering));
sorted.AddRange(list.Where(it => it is CacheProperty)
.OrderBy(it => typeList.IndexOf(it.DeclaringType))
.ThenBy(it => it.NameForFiltering));
sorted.AddRange(list.Where(it => it is CacheField)
.OrderBy(it => typeList.IndexOf(it.DeclaringType))
.ThenBy(it => it.NameForFiltering));
m_allMembers = sorted.ToArray();
}
public override void Update()
{
base.Update();
if (m_autoUpdate)
{
foreach (var member in m_displayedMembers)
{
if (member == null) break;
member.UpdateValue();
}
}
if (ReflectionUI.m_widthUpdateWanted)
{
if (!ReflectionUI.m_widthUpdateWaiting)
ReflectionUI.m_widthUpdateWaiting = true;
else
{
UpdateWidths();
ReflectionUI.m_widthUpdateWaiting = false;
ReflectionUI.m_widthUpdateWanted = false;
}
}
}
internal void OnMemberFilterClicked(MemberTypes type, Button button)
{
if (ReflectionUI.m_lastActiveMemButton)
{
var lastColors = ReflectionUI.m_lastActiveMemButton.colors;
lastColors.normalColor = new Color(0.2f, 0.2f, 0.2f);
ReflectionUI.m_lastActiveMemButton.colors = lastColors;
}
ReflectionUI.m_memberFilter = type;
ReflectionUI.m_lastActiveMemButton = button;
var colors = ReflectionUI.m_lastActiveMemButton.colors;
colors.normalColor = new Color(0.2f, 0.6f, 0.2f);
ReflectionUI.m_lastActiveMemButton.colors = colors;
FilterMembers(null, true);
ReflectionUI.m_sliderScroller.m_slider.value = 1f;
}
public void FilterMembers(string nameFilter = null, bool force = false)
{
int lastCount = m_membersFiltered.Count;
m_membersFiltered.Clear();
nameFilter = nameFilter?.ToLower() ?? ReflectionUI.m_nameFilterText.text.ToLower();
foreach (var mem in m_allMembers)
{
// membertype filter
if (ReflectionUI.m_memberFilter != MemberTypes.All && mem.MemInfo.MemberType != ReflectionUI.m_memberFilter)
continue;
if (this is InstanceInspector ii && ii.m_scopeFilter != MemberScopes.All)
{
if (mem.IsStatic && ii.m_scopeFilter != MemberScopes.Static)
continue;
else if (!mem.IsStatic && ii.m_scopeFilter != MemberScopes.Instance)
continue;
}
// name filter
if (!string.IsNullOrEmpty(nameFilter) && !mem.NameForFiltering.Contains(nameFilter))
continue;
m_membersFiltered.Add(mem);
}
if (force || lastCount != m_membersFiltered.Count)
RefreshDisplay();
}
public void RefreshDisplay()
{
var members = m_membersFiltered;
ReflectionUI.m_pageHandler.ListCount = members.Count;
// disable current members
for (int i = 0; i < m_displayedMembers.Length; i++)
{
var mem = m_displayedMembers[i];
if (mem != null)
mem.Disable();
else
break;
}
if (members.Count < 1)
return;
foreach (var itemIndex in ReflectionUI.m_pageHandler)
{
if (itemIndex >= members.Count)
break;
CacheMember member = members[itemIndex];
m_displayedMembers[itemIndex - ReflectionUI.m_pageHandler.StartIndex] = member;
member.Enable();
}
ReflectionUI.m_widthUpdateWanted = true;
}
internal void UpdateWidths()
{
float labelWidth = 125;
foreach (var cache in m_displayedMembers)
{
if (cache == null)
break;
var width = cache.GetMemberLabelWidth(ReflectionUI.m_scrollContentRect);
if (width > labelWidth)
labelWidth = width;
}
float valueWidth = ReflectionUI.m_scrollContentRect.rect.width - labelWidth - 20;
foreach (var cache in m_displayedMembers)
{
if (cache == null)
break;
cache.SetWidths(labelWidth, valueWidth);
}
}
#endregion // end instance
}
}

View File

@ -1,6 +1,6 @@
using System;
namespace UnityExplorer.Inspectors.Reflection
namespace UnityExplorer.Core.Inspectors.Reflection
{
public class StaticInspector : ReflectionInspector
{

View File

@ -0,0 +1,186 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using BF = System.Reflection.BindingFlags;
using UnityExplorer.Core.Runtime;
namespace UnityExplorer.Core
{
public static class ReflectionUtility
{
public static BF CommonFlags = BF.Public | BF.Instance | BF.NonPublic | BF.Static;
/// <summary>
/// Helper for IL2CPP to get the underlying true Type (Unhollowed) of the object.
/// </summary>
/// <param name="obj">The object to get the true Type for.</param>
/// <returns>The most accurate Type of the object which could be identified.</returns>
public static Type GetType(this object obj)
{
if (obj == null)
return null;
return ReflectionProvider.Instance.GetActualType(obj);
}
/// <summary>
/// Cast an object to its underlying Type.
/// </summary>
/// <param name="obj">The object to cast</param>
/// <returns>The object, cast to the underlying Type if possible, otherwise the original object.</returns>
public static object Cast(this object obj)
=> Cast(obj, GetType(obj));
/// <summary>
/// Cast an object to a Type, if possible.
/// </summary>
/// <param name="obj">The object to cast</param>
/// <param name="castTo">The Type to cast to </param>
/// <returns>The object, cast to the Type provided if possible, otherwise the original object.</returns>
public static object Cast(this object obj, Type castTo)
=> ReflectionProvider.Instance.Cast(obj, castTo);
/// <summary>
/// Check if the provided Type is assignable to IEnumerable.
/// </summary>
/// <param name="t">The Type to check</param>
/// <returns>True if the Type is assignable to IEnumerable, otherwise false.</returns>
public static bool IsEnumerable(this Type t)
=> ReflectionProvider.Instance.IsAssignableFrom(typeof(IEnumerable), t);
/// <summary>
/// Check if the provided Type is assignable to IDictionary.
/// </summary>
/// <param name="t">The Type to check</param>
/// <returns>True if the Type is assignable to IDictionary, otherwise false.</returns>
public static bool IsDictionary(this Type t)
=> ReflectionProvider.Instance.IsAssignableFrom(typeof(IDictionary), t);
public static bool LoadModule(string module)
=> ReflectionProvider.Instance.LoadModule(module);
// cache for GetTypeByName
internal static readonly Dictionary<string, Type> s_typesByName = new Dictionary<string, Type>();
/// <summary>
/// Find a <see cref="Type"/> in the current AppDomain whose <see cref="Type.FullName"/> matches the provided <paramref name="fullName"/>.
/// </summary>
/// <param name="fullName">The <see cref="Type.FullName"/> you want to search for - case sensitive and full matches only.</param>
/// <returns>The Type if found, otherwise null.</returns>
public static Type GetTypeByName(string fullName)
{
s_typesByName.TryGetValue(fullName, out Type ret);
if (ret != null)
return ret;
foreach (var type in from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.TryGetTypes()
select type)
{
if (type.FullName == fullName)
{
ret = type;
break;
}
}
if (s_typesByName.ContainsKey(fullName))
s_typesByName[fullName] = ret;
else
s_typesByName.Add(fullName, ret);
return ret;
}
// cache for GetBaseTypes
internal static readonly Dictionary<string, Type[]> s_cachedTypeInheritance = new Dictionary<string, Type[]>();
/// <summary>
/// Get all base types of the provided Type, including itself.
/// </summary>
public static Type[] GetAllBaseTypes(this object obj) => GetAllBaseTypes(GetType(obj));
/// <summary>
/// Get all base types of the provided Type, including itself.
/// </summary>
public static Type[] GetAllBaseTypes(this Type type)
{
if (type == null)
throw new ArgumentNullException("type");
var name = type.AssemblyQualifiedName;
if (s_cachedTypeInheritance.TryGetValue(name, out Type[] ret))
return ret;
List<Type> list = new List<Type>();
while (type != null)
{
list.Add(type);
type = type.BaseType;
}
ret = list.ToArray();
s_cachedTypeInheritance.Add(name, ret);
return ret;
}
/// <summary>
/// Safely get all valid Types inside an Assembly.
/// </summary>
/// <param name="asm">The Assembly to find Types in.</param>
/// <returns>All possible Types which could be retrieved from the Assembly, or an empty array.</returns>
public static IEnumerable<Type> TryGetTypes(this Assembly asm)
{
try
{
return asm.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
try
{
return asm.GetExportedTypes();
}
catch
{
return e.Types.Where(t => t != null);
}
}
catch
{
return Enumerable.Empty<Type>();
}
}
/// <summary>
/// Helper to display a simple "{ExceptionType}: {Message}" of the exception, and optionally use the inner-most exception.
/// </summary>
/// <param name="e">The Exception to convert to string.</param>
/// <param name="innerMost">Should the inner-most Exception of the stack be used? If false, the Exception you provided will be used directly.</param>
/// <returns>The exception to string.</returns>
public static string ReflectionExToString(this Exception e, bool innerMost = false)
{
if (innerMost)
{
while (e.InnerException != null)
{
#if CPP
if (e.InnerException is System.Runtime.CompilerServices.RuntimeWrappedException)
break;
#endif
e = e.InnerException;
}
}
return $"{e.GetType()}: {e.Message}";
}
}
}

View File

@ -6,9 +6,9 @@ using System.Text;
using UnhollowerBaseLib;
using UnhollowerRuntimeLib;
using UnityEngine;
using UnityExplorer.Helpers;
using UnityExplorer.Core.Runtime.Il2Cpp;
namespace UnityExplorer.Unstrip
namespace UnityExplorer
{
public class AssetBundle
{
@ -18,7 +18,7 @@ namespace UnityExplorer.Unstrip
public static AssetBundle LoadFromFile(string path)
{
var iCall = ICallHelper.GetICall<d_LoadFromFile>("UnityEngine.AssetBundle::LoadFromFile_Internal");
var iCall = ICallManager.GetICall<d_LoadFromFile>("UnityEngine.AssetBundle::LoadFromFile_Internal");
var ptr = iCall.Invoke(IL2CPP.ManagedStringToIl2Cpp(path), 0u, 0UL);
@ -29,7 +29,7 @@ namespace UnityExplorer.Unstrip
public static AssetBundle LoadFromMemory(byte[] binary, uint crc = 0)
{
var iCall = ICallHelper.GetICall<d_LoadFromMemory>("UnityEngine.AssetBundle::LoadFromMemory_Internal");
var iCall = ICallManager.GetICall<d_LoadFromMemory>("UnityEngine.AssetBundle::LoadFromMemory_Internal");
var ptr = iCall(((Il2CppStructArray<byte>) binary).Pointer, crc);
@ -48,7 +48,7 @@ namespace UnityExplorer.Unstrip
public UnityEngine.Object[] LoadAllAssets()
{
var iCall = ICallHelper.GetICall<d_LoadAssetWithSubAssets_Internal>("UnityEngine.AssetBundle::LoadAssetWithSubAssets_Internal");
var iCall = ICallManager.GetICall<d_LoadAssetWithSubAssets_Internal>("UnityEngine.AssetBundle::LoadAssetWithSubAssets_Internal");
var ptr = iCall.Invoke(m_bundlePtr, IL2CPP.ManagedStringToIl2Cpp(""), Il2CppType.Of<UnityEngine.Object>().Pointer);
if (ptr == IntPtr.Zero)
@ -63,7 +63,7 @@ namespace UnityExplorer.Unstrip
public T LoadAsset<T>(string name) where T : UnityEngine.Object
{
var iCall = ICallHelper.GetICall<d_LoadAsset_Internal>("UnityEngine.AssetBundle::LoadAsset_Internal");
var iCall = ICallManager.GetICall<d_LoadAsset_Internal>("UnityEngine.AssetBundle::LoadAsset_Internal");
var ptr = iCall.Invoke(m_bundlePtr, IL2CPP.ManagedStringToIl2Cpp(name), Il2CppType.Of<T>().Pointer);
if (ptr == IntPtr.Zero)

View File

@ -0,0 +1,43 @@
#if CPP
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace UnityExplorer.Core.Runtime.Il2Cpp
{
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "External methods")]
public static class ICallManager
{
private static readonly Dictionary<string, Delegate> iCallCache = new Dictionary<string, Delegate>();
/// <summary>
/// Helper to get and cache an iCall by providing the signature (eg. "UnityEngine.Resources::FindObjectsOfTypeAll").
/// </summary>
/// <typeparam name="T">The Type of Delegate to provide for the iCall.</typeparam>
/// <param name="signature">The signature of the iCall you want to get.</param>
/// <returns>The <typeparamref name="T"/> delegate if successful.</returns>
/// <exception cref="MissingMethodException">If the iCall could not be found.</exception>
public static T GetICall<T>(string signature) where T : Delegate
{
if (iCallCache.ContainsKey(signature))
return (T)iCallCache[signature];
IntPtr ptr = il2cpp_resolve_icall(signature);
if (ptr == IntPtr.Zero)
{
throw new MissingMethodException($"Could not resolve internal call by name '{signature}'!");
}
Delegate iCall = Marshal.GetDelegateForFunctionPointer(ptr, typeof(T));
iCallCache.Add(signature, iCall);
return (T)iCall;
}
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr il2cpp_resolve_icall([MarshalAs(UnmanagedType.LPStr)] string name);
}
}
#endif

View File

@ -0,0 +1,156 @@
#if CPP
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnhollowerBaseLib;
using UnityEngine;
// CREDIT HerpDerpenstine
// https://github.com/LavaGang/MelonLoader/blob/master/MelonLoader.Support.Il2Cpp/MelonCoroutines.cs
namespace UnityExplorer.Core.Runtime.Il2Cpp
{
public static class Il2CppCoroutine
{
private struct CoroTuple
{
public object WaitCondition;
public IEnumerator Coroutine;
}
private static readonly List<CoroTuple> ourCoroutinesStore = new List<CoroTuple>();
private static readonly List<IEnumerator> ourNextFrameCoroutines = new List<IEnumerator>();
private static readonly List<IEnumerator> ourWaitForFixedUpdateCoroutines = new List<IEnumerator>();
private static readonly List<IEnumerator> ourWaitForEndOfFrameCoroutines = new List<IEnumerator>();
private static readonly List<IEnumerator> tempList = new List<IEnumerator>();
internal static object Start(IEnumerator routine)
{
if (routine != null) ProcessNextOfCoroutine(routine);
return routine;
}
internal static void Stop(IEnumerator enumerator)
{
if (ourNextFrameCoroutines.Contains(enumerator)) // the coroutine is running itself
ourNextFrameCoroutines.Remove(enumerator);
else
{
int coroTupleIndex = ourCoroutinesStore.FindIndex(c => c.Coroutine == enumerator);
if (coroTupleIndex != -1) // the coroutine is waiting for a subroutine
{
object waitCondition = ourCoroutinesStore[coroTupleIndex].WaitCondition;
if (waitCondition is IEnumerator waitEnumerator)
Stop(waitEnumerator);
ourCoroutinesStore.RemoveAt(coroTupleIndex);
}
}
}
private static void ProcessCoroList(List<IEnumerator> target)
{
if (target.Count == 0) return;
// use a temp list to make sure waits made during processing are not handled by same processing invocation
// additionally, a temp list reduces allocations compared to an array
tempList.AddRange(target);
target.Clear();
foreach (var enumerator in tempList) ProcessNextOfCoroutine(enumerator);
tempList.Clear();
}
internal static void Process()
{
for (var i = ourCoroutinesStore.Count - 1; i >= 0; i--)
{
var tuple = ourCoroutinesStore[i];
if (tuple.WaitCondition is WaitForSeconds waitForSeconds)
{
if ((waitForSeconds.m_Seconds -= Time.deltaTime) <= 0)
{
ourCoroutinesStore.RemoveAt(i);
ProcessNextOfCoroutine(tuple.Coroutine);
}
}
}
ProcessCoroList(ourNextFrameCoroutines);
}
internal static void ProcessWaitForFixedUpdate() => ProcessCoroList(ourWaitForFixedUpdateCoroutines);
internal static void ProcessWaitForEndOfFrame() => ProcessCoroList(ourWaitForEndOfFrameCoroutines);
private static void ProcessNextOfCoroutine(IEnumerator enumerator)
{
try
{
if (!enumerator.MoveNext()) // Run the next step of the coroutine. If it's done, restore the parent routine
{
var indices = ourCoroutinesStore.Select((it, idx) => (idx, it)).Where(it => it.it.WaitCondition == enumerator).Select(it => it.idx).ToList();
for (var i = indices.Count - 1; i >= 0; i--)
{
var index = indices[i];
ourNextFrameCoroutines.Add(ourCoroutinesStore[index].Coroutine);
ourCoroutinesStore.RemoveAt(index);
}
return;
}
}
catch (Exception e)
{
ExplorerCore.LogError(e.ToString());
Stop(FindOriginalCoro(enumerator)); // We want the entire coroutine hierachy to stop when an error happen
}
var next = enumerator.Current;
switch (next)
{
case null:
ourNextFrameCoroutines.Add(enumerator);
return;
case WaitForFixedUpdate _:
ourWaitForFixedUpdateCoroutines.Add(enumerator);
return;
case WaitForEndOfFrame _:
ourWaitForEndOfFrameCoroutines.Add(enumerator);
return;
case WaitForSeconds _:
break; // do nothing, this one is supported in Process
case Il2CppObjectBase il2CppObjectBase:
var nextAsEnumerator = il2CppObjectBase.TryCast<Il2CppSystem.Collections.IEnumerator>();
if (nextAsEnumerator != null) // il2cpp IEnumerator also handles CustomYieldInstruction
next = new Il2CppEnumeratorWrapper(nextAsEnumerator);
else
ExplorerCore.LogWarning($"Unknown coroutine yield object of type {il2CppObjectBase} for coroutine {enumerator}");
break;
}
ourCoroutinesStore.Add(new CoroTuple { WaitCondition = next, Coroutine = enumerator });
if (next is IEnumerator nextCoro)
ProcessNextOfCoroutine(nextCoro);
}
private static IEnumerator FindOriginalCoro(IEnumerator enumerator)
{
int index = ourCoroutinesStore.FindIndex(ct => ct.WaitCondition == enumerator);
if (index == -1)
return enumerator;
return FindOriginalCoro(ourCoroutinesStore[index].Coroutine);
}
private class Il2CppEnumeratorWrapper : IEnumerator
{
private readonly Il2CppSystem.Collections.IEnumerator il2cppEnumerator;
public Il2CppEnumeratorWrapper(Il2CppSystem.Collections.IEnumerator il2CppEnumerator) => il2cppEnumerator = il2CppEnumerator;
public bool MoveNext() => il2cppEnumerator.MoveNext();
public void Reset() => il2cppEnumerator.Reset();
public object Current => il2cppEnumerator.Current;
}
}
}
#endif

View File

@ -0,0 +1,127 @@
#if CPP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BF = System.Reflection.BindingFlags;
using System.Text;
using UnhollowerBaseLib;
using UnhollowerRuntimeLib;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.UI;
namespace UnityExplorer.Core.Runtime.Il2Cpp
{
public class Il2CppProvider : RuntimeProvider
{
public override void Initialize()
{
Reflection = new Il2CppReflection();
TextureUtil = new Il2CppTextureUtil();
}
public override void SetupEvents()
{
try
{
//Application.add_logMessageReceived(new Action<string, string, LogType>(ExplorerCore.Instance.OnUnityLog));
var logType = ReflectionUtility.GetTypeByName("UnityEngine.Application+LogCallback");
var castMethod = logType.GetMethod("op_Implicit", new[] { typeof(Action<string, string, LogType>) });
var addMethod = typeof(Application).GetMethod("add_logMessageReceived", BF.Static | BF.Public, null, new[] { logType }, null);
addMethod.Invoke(null, new[]
{
castMethod.Invoke(null, new[] { new Action<string, string, LogType>(ExplorerCore.Instance.OnUnityLog) })
});
}
catch
{
ExplorerCore.LogWarning("Exception setting up Unity log listener, make sure Unity libraries have been unstripped!");
}
}
public override void StartConsoleCoroutine(IEnumerator routine)
{
Il2CppCoroutine.Start(routine);
}
internal delegate IntPtr d_LayerToName(int layer);
public override string LayerToName(int layer)
{
var iCall = ICallManager.GetICall<d_LayerToName>("UnityEngine.LayerMask::LayerToName");
return IL2CPP.Il2CppStringToManaged(iCall.Invoke(layer));
}
internal delegate IntPtr d_FindObjectsOfTypeAll(IntPtr type);
public override UnityEngine.Object[] FindObjectsOfTypeAll(Type type)
{
var iCall = ICallManager.GetICall<d_FindObjectsOfTypeAll>("UnityEngine.Resources::FindObjectsOfTypeAll");
var cppType = Il2CppType.From(type);
return new Il2CppReferenceArray<UnityEngine.Object>(iCall.Invoke(cppType.Pointer));
}
public override int GetSceneHandle(Scene scene)
=> scene.handle;
//Scene.GetRootGameObjects();
internal delegate void d_GetRootGameObjects(int handle, IntPtr list);
public override GameObject[] GetRootGameObjects(Scene scene) => GetRootGameObjects(scene.handle);
public static GameObject[] GetRootGameObjects(int handle)
{
if (handle == -1)
return new GameObject[0];
int count = GetRootCount(handle);
if (count < 1)
return new GameObject[0];
var list = new Il2CppSystem.Collections.Generic.List<GameObject>(count);
var iCall = ICallManager.GetICall<d_GetRootGameObjects>("UnityEngine.SceneManagement.Scene::GetRootGameObjectsInternal");
iCall.Invoke(handle, list.Pointer);
return list.ToArray();
}
//Scene.rootCount;
internal delegate int d_GetRootCountInternal(int handle);
public override int GetRootCount(Scene scene) => GetRootCount(scene.handle);
public static int GetRootCount(int handle)
{
return ICallManager.GetICall<d_GetRootCountInternal>("UnityEngine.SceneManagement.Scene::GetRootCountInternal")
.Invoke(handle);
}
}
}
public static class Il2CppExtensions
{
public static void AddListener(this UnityEvent action, Action listener)
{
action.AddListener(listener);
}
public static void AddListener<T>(this UnityEvent<T> action, Action<T> listener)
{
action.AddListener(listener);
}
public static void SetChildControlHeight(this HorizontalOrVerticalLayoutGroup group, bool value) => group.childControlHeight = value;
public static void SetChildControlWidth(this HorizontalOrVerticalLayoutGroup group, bool value) => group.childControlWidth = value;
}
#endif

View File

@ -0,0 +1,362 @@
#if CPP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnhollowerBaseLib;
using UnityExplorer.Core.Unity;
using UnhollowerRuntimeLib;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections;
using System.IO;
using System.Diagnostics.CodeAnalysis;
using UnityExplorer.Core;
using CppType = Il2CppSystem.Type;
using BF = System.Reflection.BindingFlags;
namespace UnityExplorer.Core.Runtime.Il2Cpp
{
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "External methods")]
public class Il2CppReflection : ReflectionProvider
{
public Il2CppReflection() : base()
{
Instance = this;
TryLoadGameModules();
}
public override object Cast(object obj, Type castTo)
{
return Il2CppCast(obj, castTo);
}
public override string ProcessTypeNameInString(Type type, string theString, ref string typeName)
{
if (!Il2CppTypeNotNull(type))
return theString;
var cppType = Il2CppType.From(type);
if (cppType != null && s_deobfuscatedTypeNames.ContainsKey(cppType.FullName))
{
typeName = s_deobfuscatedTypeNames[cppType.FullName];
theString = theString.Replace(cppType.FullName, typeName);
}
return theString;
}
public override Type GetActualType(object obj)
{
if (obj == null)
return null;
var type = obj.GetType();
if (obj is Il2CppSystem.Object cppObject)
{
// weird specific case - if the object is an Il2CppSystem.Type, then return so manually.
if (cppObject is CppType)
return typeof(CppType);
if (!string.IsNullOrEmpty(type.Namespace))
{
// Il2CppSystem-namespace objects should just return GetType,
// because using GetIl2CppType returns the System namespace type instead.
if (type.Namespace.StartsWith("System.") || type.Namespace.StartsWith("Il2CppSystem."))
return cppObject.GetType();
}
var cppType = cppObject.GetIl2CppType();
// check if type is injected
IntPtr classPtr = il2cpp_object_get_class(cppObject.Pointer);
if (RuntimeSpecificsStore.IsInjected(classPtr))
{
var typeByName = ReflectionUtility.GetTypeByName(cppType.FullName);
if (typeByName != null)
return typeByName;
}
// this should be fine for all other il2cpp objects
var getType = GetMonoType(cppType);
if (getType != null)
return getType;
}
return type;
}
// caching for GetMonoType
private static readonly Dictionary<string, Type> Il2CppToMonoType = new Dictionary<string, Type>();
// keep deobfuscated type name cache, used to display proper name.
internal static Dictionary<string, string> s_deobfuscatedTypeNames = new Dictionary<string, string>();
/// <summary>
/// Try to get the Mono (Unhollowed) Type representation of the provided <see cref="Il2CppSystem.Type"/>.
/// </summary>
/// <param name="cppType">The Cpp Type you want to convert to Mono.</param>
/// <returns>The Mono Type if found, otherwise null.</returns>
public static Type GetMonoType(CppType cppType)
{
string name = cppType.AssemblyQualifiedName;
if (Il2CppToMonoType.ContainsKey(name))
return Il2CppToMonoType[name];
Type ret = Type.GetType(name);
if (ret == null)
{
string baseName = cppType.FullName;
string baseAssembly = cppType.Assembly.GetName().name;
ret = AppDomain.CurrentDomain
.GetAssemblies()
.FirstOrDefault(a
=> a.GetName().Name == baseAssembly)?
.TryGetTypes()
.FirstOrDefault(t
=> t.CustomAttributes.Any(ca
=> ca.AttributeType.Name == "ObfuscatedNameAttribute"
&& (string)ca.ConstructorArguments[0].Value == baseName));
if (ret != null)
{
// deobfuscated type was found, add to cache.
s_deobfuscatedTypeNames.Add(cppType.FullName, ret.FullName);
}
}
Il2CppToMonoType.Add(name, ret);
return ret;
}
// cached class pointers for Il2CppCast
private static readonly Dictionary<string, IntPtr> s_cppClassPointers = new Dictionary<string, IntPtr>();
/// <summary>
/// Attempt to cast the object to its underlying type.
/// </summary>
/// <param name="obj">The object you want to cast.</param>
/// <returns>The object, as the underlying type if successful or the input value if not.</returns>
public static object Il2CppCast(object obj) => Il2CppCast(obj, Instance.GetActualType(obj));
/// <summary>
/// Attempt to cast the object to the provided type.
/// </summary>
/// <param name="obj">The object you want to cast.</param>
/// <param name="castTo">The Type you want to cast to.</param>
/// <returns>The object, as the type (or a normal C# object) if successful or the input value if not.</returns>
public static object Il2CppCast(object obj, Type castTo)
{
if (!(obj is Il2CppSystem.Object ilObj))
return obj;
if (!Il2CppTypeNotNull(castTo, out IntPtr castToPtr))
return obj;
IntPtr castFromPtr = il2cpp_object_get_class(ilObj.Pointer);
if (!il2cpp_class_is_assignable_from(castToPtr, castFromPtr))
return obj;
if (RuntimeSpecificsStore.IsInjected(castToPtr))
return UnhollowerBaseLib.Runtime.ClassInjectorBase.GetMonoObjectFromIl2CppPointer(ilObj.Pointer);
return Activator.CreateInstance(castTo, ilObj.Pointer);
}
/// <summary>
/// Get the Il2Cpp Class Pointer for the provided Mono (Unhollowed) Type.
/// </summary>
/// <param name="type">The Mono/Unhollowed Type you want the Il2Cpp Class Pointer for.</param>
/// <returns>True if successful, false if not.</returns>
public static bool Il2CppTypeNotNull(Type type) => Il2CppTypeNotNull(type, out _);
/// <summary>
/// Get the Il2Cpp Class Pointer for the provided Mono (Unhollowed) Type.
/// </summary>
/// <param name="type">The Mono/Unhollowed Type you want the Il2Cpp Class Pointer for.</param>
/// <param name="il2cppPtr">The IntPtr for the Il2Cpp class, or IntPtr.Zero if not found.</param>
/// <returns>True if successful, false if not.</returns>
public static bool Il2CppTypeNotNull(Type type, out IntPtr il2cppPtr)
{
if (s_cppClassPointers.TryGetValue(type.AssemblyQualifiedName, out il2cppPtr))
return il2cppPtr != IntPtr.Zero;
il2cppPtr = (IntPtr)typeof(Il2CppClassPointerStore<>)
.MakeGenericType(new Type[] { type })
.GetField("NativeClassPtr", BF.Public | BF.Static)
.GetValue(null);
s_cppClassPointers.Add(type.AssemblyQualifiedName, il2cppPtr);
return il2cppPtr != IntPtr.Zero;
}
// Extern C++ methods
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern bool il2cpp_class_is_assignable_from(IntPtr klass, IntPtr oklass);
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr il2cpp_object_get_class(IntPtr obj);
internal static IntPtr s_cppEnumerableClassPtr;
internal static IntPtr s_cppDictionaryClassPtr;
public override bool IsAssignableFrom(Type toAssignTo, Type toAssignFrom)
{
if (toAssignTo.IsAssignableFrom(toAssignFrom))
return true;
if (toAssignTo == typeof(IEnumerable))
{
try
{
if (s_cppEnumerableClassPtr == IntPtr.Zero)
Il2CppTypeNotNull(typeof(Il2CppSystem.Collections.IEnumerable), out s_cppEnumerableClassPtr);
if (s_cppEnumerableClassPtr != IntPtr.Zero
&& Il2CppTypeNotNull(toAssignFrom, out IntPtr assignFromPtr)
&& il2cpp_class_is_assignable_from(s_cppEnumerableClassPtr, assignFromPtr))
{
return true;
}
}
catch { }
}
else if (toAssignTo == typeof(IDictionary))
{
try
{
if (s_cppDictionaryClassPtr == IntPtr.Zero)
if (!Il2CppTypeNotNull(typeof(Il2CppSystem.Collections.IDictionary), out s_cppDictionaryClassPtr))
return false;
if (Il2CppTypeNotNull(toAssignFrom, out IntPtr classPtr))
{
if (il2cpp_class_is_assignable_from(s_cppDictionaryClassPtr, classPtr))
return true;
}
}
catch { }
}
return false;
}
public override bool IsReflectionSupported(Type type)
{
try
{
var gArgs = type.GetGenericArguments();
if (!gArgs.Any())
return true;
foreach (var gType in gArgs)
{
if (!Supported(gType))
return false;
}
return true;
bool Supported(Type t)
{
if (!typeof(Il2CppSystem.Object).IsAssignableFrom(t))
return true;
if (!Il2CppTypeNotNull(t, out IntPtr ptr))
return false;
return CppType.internal_from_handle(IL2CPP.il2cpp_class_get_type(ptr)) is CppType;
}
}
catch
{
return false;
}
}
// Helper for IL2CPP to try to make sure the Unhollowed game assemblies are actually loaded.
internal static void TryLoadGameModules()
{
Instance.LoadModule("Assembly-CSharp");
Instance.LoadModule("Assembly-CSharp-firstpass");
}
public override bool LoadModule(string module)
{
#if ML
var path = Path.Combine("MelonLoader", "Managed", $"{module}.dll");
#else
var path = Path.Combine("BepInEx", "unhollowed", $"{module}.dll");
#endif
return LoadModuleInternal(path);
}
internal static bool LoadModuleInternal(string fullPath)
{
if (!File.Exists(fullPath))
return false;
try
{
Assembly.Load(File.ReadAllBytes(fullPath));
return true;
}
catch (Exception e)
{
Console.WriteLine(e.GetType() + ", " + e.Message);
}
return false;
}
// ~~~~~~~~~~ not used ~~~~~~~~~~~~
// cached il2cpp unbox methods
internal static readonly Dictionary<string, MethodInfo> s_unboxMethods = new Dictionary<string, MethodInfo>();
/// <summary>
/// Attempt to unbox the object to the underlying struct type.
/// </summary>
/// <param name="obj">The object which is a struct underneath.</param>
/// <returns>The struct if successful, otherwise null.</returns>
public static object Unbox(object obj) => Unbox(obj, Instance.GetActualType(obj));
/// <summary>
/// Attempt to unbox the object to the struct type.
/// </summary>
/// <param name="obj">The object which is a struct underneath.</param>
/// <param name="type">The type of the struct you want to unbox to.</param>
/// <returns>The struct if successful, otherwise null.</returns>
public static object Unbox(object obj, Type type)
{
if (!type.IsValueType)
return null;
if (!(obj is Il2CppSystem.Object))
return obj;
var name = type.AssemblyQualifiedName;
if (!s_unboxMethods.ContainsKey(name))
{
s_unboxMethods.Add(name, typeof(Il2CppObjectBase)
.GetMethod("Unbox")
.MakeGenericMethod(type));
}
return s_unboxMethods[name].Invoke(obj, new object[0]);
}
}
}
#endif

View File

@ -0,0 +1,77 @@
#if CPP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnhollowerBaseLib;
using UnityEngine;
namespace UnityExplorer.Core.Runtime.Il2Cpp
{
public class Il2CppTextureUtil : TextureUtilProvider
{
public override Texture2D NewTexture2D(int width, int height)
=> new Texture2D((int)width, (int)height, TextureFormat.RGBA32, Texture.GenerateAllMips, false, IntPtr.Zero);
internal delegate void d_Blit2(IntPtr source, IntPtr dest);
public override void Blit(Texture2D tex, RenderTexture rt)
{
var iCall = ICallManager.GetICall<d_Blit2>("UnityEngine.Graphics::Blit2");
iCall.Invoke(tex.Pointer, rt.Pointer);
}
// byte[] ImageConversion.EncodeToPNG(this Texture2D image);
internal delegate IntPtr d_EncodeToPNG(IntPtr tex);
public override byte[] EncodeToPNG(Texture2D tex)
{
var iCall = ICallManager.GetICall<d_EncodeToPNG>("UnityEngine.ImageConversion::EncodeToPNG");
IntPtr ptr = iCall.Invoke(tex.Pointer);
if (ptr == IntPtr.Zero)
return null;
return new Il2CppStructArray<byte>(ptr);
}
// bool ImageConversion.LoadImage(this Texture2D tex, byte[] data, bool markNonReadable);
internal delegate bool d_LoadImage(IntPtr tex, IntPtr data, bool markNonReadable);
public override bool LoadImage(Texture2D tex, byte[] data, bool markNonReadable)
{
var il2cppArray = (Il2CppStructArray<byte>)data;
var iCall = ICallManager.GetICall<d_LoadImage>("UnityEngine.ImageConversion::LoadImage");
return iCall.Invoke(tex.Pointer, il2cppArray.Pointer, markNonReadable);
}
// Sprite Sprite.Create
public override Sprite CreateSprite(Texture2D texture)
{
return CreateSpriteImpl(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 100f, 0u, Vector4.zero);
}
internal delegate IntPtr d_CreateSprite(IntPtr texture, ref Rect rect, ref Vector2 pivot, float pixelsPerUnit,
uint extrude, int meshType, ref Vector4 border, bool generateFallbackPhysicsShape);
public static Sprite CreateSpriteImpl(Texture texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude, Vector4 border)
{
var iCall = ICallManager.GetICall<d_CreateSprite>("UnityEngine.Sprite::CreateSprite_Injected");
var ptr = iCall.Invoke(texture.Pointer, ref rect, ref pivot, pixelsPerUnit, extrude, 1, ref border, false);
if (ptr == IntPtr.Zero)
return null;
else
return new Sprite(ptr);
}
}
}
#endif

View File

@ -0,0 +1,89 @@
#if MONO
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityExplorer.Core;
using UnityExplorer.Core.CSharp;
namespace UnityExplorer.Core.Runtime.Mono
{
public class MonoProvider : RuntimeProvider
{
public override void Initialize()
{
Reflection = new MonoReflection();
TextureUtil = new MonoTextureUtil();
}
public override void SetupEvents()
{
Application.logMessageReceived += ExplorerCore.Instance.OnUnityLog;
//SceneManager.sceneLoaded += ExplorerCore.Instance.OnSceneLoaded1;
//SceneManager.activeSceneChanged += ExplorerCore.Instance.OnSceneLoaded2;
}
public override void StartConsoleCoroutine(IEnumerator routine)
{
DummyBehaviour.Instance.StartCoroutine(routine);
}
public override string LayerToName(int layer)
=> LayerMask.LayerToName(layer);
public override UnityEngine.Object[] FindObjectsOfTypeAll(Type type)
=> Resources.FindObjectsOfTypeAll(type);
private static readonly FieldInfo fi_Scene_handle = typeof(Scene).GetField("m_Handle", ReflectionUtility.CommonFlags);
public override int GetSceneHandle(Scene scene)
{
return (int)fi_Scene_handle.GetValue(scene);
}
public override GameObject[] GetRootGameObjects(Scene scene)
{
return scene.GetRootGameObjects();
}
public override int GetRootCount(Scene scene)
{
return scene.rootCount;
}
}
}
public static class MonoExtensions
{
public static void Clear(this StringBuilder sb)
{
sb.Remove(0, sb.Length);
}
private static PropertyInfo pi_childControlHeight;
public static void SetChildControlHeight(this HorizontalOrVerticalLayoutGroup group, bool value)
{
if (pi_childControlHeight == null)
pi_childControlHeight = group.GetType().GetProperty("childControlHeight");
pi_childControlHeight?.SetValue(group, value, null);
}
private static PropertyInfo pi_childControlWidth;
public static void SetChildControlWidth(this HorizontalOrVerticalLayoutGroup group, bool value)
{
if (pi_childControlWidth == null)
pi_childControlWidth = group.GetType().GetProperty("childControlWidth");
pi_childControlWidth?.SetValue(group, value, null);
}
}
#endif

View File

@ -0,0 +1,33 @@
#if MONO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnityExplorer.Core.Runtime.Mono
{
public class MonoReflection : ReflectionProvider
{
// Mono doesn't need to explicitly cast things.
public override object Cast(object obj, Type castTo)
=> obj;
// Vanilla GetType is fine for mono
public override Type GetActualType(object obj)
=> obj.GetType();
public override bool IsAssignableFrom(Type toAssignTo, Type toAssignFrom)
=> toAssignTo.IsAssignableFrom(toAssignFrom);
public override bool IsReflectionSupported(Type type)
=> true;
public override bool LoadModule(string module)
=> true;
public override string ProcessTypeNameInString(Type type, string theString, ref string typeName)
=> theString;
}
}
#endif

View File

@ -0,0 +1,66 @@
#if MONO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityExplorer.Core;
namespace UnityExplorer.Core.Runtime.Mono
{
public class MonoTextureUtil : TextureUtilProvider
{
public override void Blit(Texture2D tex, RenderTexture rt)
{
Graphics.Blit(tex, rt);
}
public override Sprite CreateSprite(Texture2D texture)
{
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
}
public override bool LoadImage(Texture2D tex, byte[] data, bool markNonReadable)
{
return tex.LoadImage(data, markNonReadable);
}
public override Texture2D NewTexture2D(int width, int height)
{
return new Texture2D(width, height);
}
public override byte[] EncodeToPNG(Texture2D tex)
{
return EncodeToPNGSafe(tex);
}
private static MethodInfo EncodeToPNGMethod => m_encodeToPNGMethod ?? GetEncodeToPNGMethod();
private static MethodInfo m_encodeToPNGMethod;
public static byte[] EncodeToPNGSafe(Texture2D tex)
{
var method = EncodeToPNGMethod;
if (method.IsStatic)
return (byte[])method.Invoke(null, new object[] { tex });
else
return (byte[])method.Invoke(tex, new object[0]);
}
private static MethodInfo GetEncodeToPNGMethod()
{
if (ReflectionUtility.GetTypeByName("UnityEngine.ImageConversion") is Type imageConversion)
return m_encodeToPNGMethod = imageConversion.GetMethod("EncodeToPNG", ReflectionUtility.CommonFlags);
var method = typeof(Texture2D).GetMethod("EncodeToPNG", ReflectionUtility.CommonFlags);
if (method != null)
return m_encodeToPNGMethod = method;
ExplorerCore.Log("ERROR: Cannot get any EncodeToPNG method!");
return null;
}
}
}
#endif

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnityExplorer.Core.Runtime
{
public abstract class ReflectionProvider
{
public static ReflectionProvider Instance;
public ReflectionProvider()
{
Instance = this;
}
public abstract Type GetActualType(object obj);
public abstract object Cast(object obj, Type castTo);
public abstract bool IsAssignableFrom(Type toAssignTo, Type toAssignFrom);
public abstract bool IsReflectionSupported(Type type);
public abstract string ProcessTypeNameInString(Type type, string theString, ref string typeName);
public abstract bool LoadModule(string module);
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace UnityExplorer.Core.Runtime
{
// Work in progress, this will be used to replace all the "if CPP / if MONO"
// pre-processor directives all over the codebase.
public abstract class RuntimeProvider
{
public static RuntimeProvider Instance;
public ReflectionProvider Reflection;
public TextureUtilProvider TextureUtil;
public RuntimeProvider()
{
Initialize();
SetupEvents();
}
public static void Init() =>
#if CPP
Instance = new Il2Cpp.Il2CppProvider();
#else
Instance = new Mono.MonoProvider();
#endif
public abstract void Initialize();
public abstract void SetupEvents();
public abstract void StartConsoleCoroutine(IEnumerator routine);
// Unity API handlers
public abstract string LayerToName(int layer);
public abstract UnityEngine.Object[] FindObjectsOfTypeAll(Type type);
public abstract int GetSceneHandle(Scene scene);
public abstract GameObject[] GetRootGameObjects(Scene scene);
public abstract int GetRootCount(Scene scene);
}
}

View File

@ -1,50 +1,32 @@
using System;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
#if CPP
using UnityExplorer.Unstrip;
#endif
using System.Linq;
using System.Text;
using UnityEngine;
namespace UnityExplorer.Helpers
namespace UnityExplorer.Core.Runtime
{
public static class Texture2DHelpers
public abstract class TextureUtilProvider
{
#if MONO
private static bool isNewEncodeMethod = false;
private static MethodInfo EncodeToPNGMethod => m_encodeToPNGMethod ?? GetEncodeToPNGMethod();
private static MethodInfo m_encodeToPNGMethod;
public static TextureUtilProvider Instance;
public static byte[] EncodeToPNGSafe(this Texture2D tex)
public TextureUtilProvider()
{
var method = EncodeToPNGMethod;
if (method.IsStatic)
return (byte[])method.Invoke(null, new object[] { tex });
else
return (byte[])method.Invoke(tex, new object[0]);
Instance = this;
}
private static MethodInfo GetEncodeToPNGMethod()
{
if (ReflectionHelpers.GetTypeByName("UnityEngine.ImageConversion") is Type imageConversion)
{
isNewEncodeMethod = true;
return m_encodeToPNGMethod = imageConversion.GetMethod("EncodeToPNG", ReflectionHelpers.CommonFlags);
}
public abstract byte[] EncodeToPNG(Texture2D tex);
var method = typeof(Texture2D).GetMethod("EncodeToPNG", ReflectionHelpers.CommonFlags);
if (method != null)
{
return m_encodeToPNGMethod = method;
}
public abstract Texture2D NewTexture2D(int width, int height);
ExplorerCore.Log("ERROR: Cannot get any EncodeToPNG method!");
return null;
}
#endif
public abstract void Blit(Texture2D tex, RenderTexture rt);
public static bool IsReadable(this Texture2D tex)
public abstract bool LoadImage(Texture2D tex, byte[] data, bool markNonReadable);
public abstract Sprite CreateSprite(Texture2D texture);
public static bool IsReadable(Texture2D tex)
{
try
{
@ -61,30 +43,30 @@ namespace UnityExplorer.Helpers
}
}
public static bool LoadImage(Texture2D tex, string filePath, bool markNonReadable)
{
if (!File.Exists(filePath))
return false;
return Instance.LoadImage(tex, File.ReadAllBytes(filePath), markNonReadable);
}
public static Texture2D Copy(Texture2D orig, Rect rect)
{
Color[] pixels;
if (!orig.IsReadable())
if (!IsReadable(orig))
orig = ForceReadTexture(orig);
pixels = orig.GetPixels((int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
// use full constructor for better compatibility
#if CPP
var _newTex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, Texture.GenerateAllMips, false, IntPtr.Zero);
#else
var _newTex = new Texture2D((int)rect.width, (int)rect.height);
#endif
_newTex.SetPixels(pixels);
Texture2D newTex = Instance.NewTexture2D((int)rect.width, (int)rect.height);
return _newTex;
newTex.SetPixels(pixels);
return newTex;
}
#if CPP
internal delegate void d_Blit2(IntPtr source, IntPtr dest);
#endif
public static Texture2D ForceReadTexture(Texture2D tex)
{
try
@ -96,12 +78,7 @@ namespace UnityExplorer.Helpers
rt.filterMode = FilterMode.Point;
RenderTexture.active = rt;
#if MONO
Graphics.Blit(tex, rt);
#else
var iCall = ICallHelper.GetICall<d_Blit2>("UnityEngine.Graphics::Blit2");
iCall.Invoke(tex.Pointer, rt.Pointer);
#endif
Instance.Blit(tex, rt);
var _newTex = new Texture2D(tex.width, tex.height, TextureFormat.ARGB32, false);
@ -129,7 +106,7 @@ namespace UnityExplorer.Helpers
string savepath = dir + @"\" + name + ".png";
// Make sure we can EncodeToPNG it.
if (tex.format != TextureFormat.ARGB32 || !tex.IsReadable())
if (tex.format != TextureFormat.ARGB32 || !IsReadable(tex))
{
tex = ForceReadTexture(tex);
}
@ -140,20 +117,9 @@ namespace UnityExplorer.Helpers
tex.Apply(false, false);
}
#if CPP
data = tex.EncodeToPNG();
#else
if (isNewEncodeMethod)
{
data = (byte[])EncodeToPNGMethod.Invoke(null, new object[] { tex });
}
else
{
data = (byte[])EncodeToPNGMethod.Invoke(tex, new object[0]);
}
#endif
data = Instance.EncodeToPNG(tex);
if (data == null || data.Length < 1)
if (data == null || !data.Any())
{
ExplorerCore.LogWarning("Couldn't get any data for the texture!");
}

206
src/Core/SceneExplorer.cs Normal file
View File

@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityExplorer.UI;
using UnityExplorer.UI.Main;
using UnityExplorer.UI.Reusable;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityExplorer.Core.Runtime;
using UnityExplorer.UI.Main.Home;
using UnityExplorer.Core.Config;
namespace UnityExplorer.Core.Inspectors
{
public class SceneExplorer
{
public static SceneExplorer Instance;
public static SceneExplorerUI UI;
internal static Action OnToggleShow;
public SceneExplorer()
{
Instance = this;
UI = new SceneExplorerUI();
UI.ConstructScenePane();
}
private const float UPDATE_INTERVAL = 1f;
private float m_timeOfLastSceneUpdate;
// private int m_currentSceneHandle = -1;
public static Scene DontDestroyScene => DontDestroyObject.scene;
internal Scene m_currentScene;
internal Scene[] m_currentScenes = new Scene[0];
internal GameObject[] m_allObjects = new GameObject[0];
internal GameObject m_selectedSceneObject;
internal int m_lastCount;
internal static GameObject DontDestroyObject
{
get
{
if (!s_dontDestroyObject)
{
s_dontDestroyObject = new GameObject("DontDestroyMe");
GameObject.DontDestroyOnLoad(s_dontDestroyObject);
}
return s_dontDestroyObject;
}
}
internal static GameObject s_dontDestroyObject;
public void Init()
{
RefreshSceneSelector();
if (ExplorerConfig.Instance.SceneExplorer_Hidden)
UI.ToggleShow();
}
public void Update()
{
if (UI.Hiding || Time.realtimeSinceStartup - m_timeOfLastSceneUpdate < UPDATE_INTERVAL)
return;
RefreshSceneSelector();
if (!m_selectedSceneObject)
{
if (m_currentScene != default)
{
var rootObjects = RuntimeProvider.Instance.GetRootGameObjects(m_currentScene);
SetSceneObjectList(rootObjects);
}
}
else
{
RefreshSelectedSceneObject();
}
}
private void RefreshSceneSelector()
{
var newNames = new List<string>();
var newScenes = new List<Scene>();
if (m_currentScenes == null)
m_currentScenes = new Scene[0];
bool anyChange = SceneManager.sceneCount != m_currentScenes.Length - 1;
for (int i = 0; i < SceneManager.sceneCount; i++)
{
Scene scene = SceneManager.GetSceneAt(i);
if (scene == default)
continue;
int handle = RuntimeProvider.Instance.GetSceneHandle(scene);
if (!anyChange && !m_currentScenes.Any(it => handle == RuntimeProvider.Instance.GetSceneHandle(it)))
anyChange = true;
newScenes.Add(scene);
newNames.Add(scene.name);
}
if (anyChange)
{
newNames.Add("DontDestroyOnLoad");
newScenes.Add(DontDestroyScene);
m_currentScenes = newScenes.ToArray();
UI.OnActiveScenesChanged(newNames);
SetTargetScene(newScenes[0]);
SearchPage.Instance.OnSceneChange();
}
}
public void SetTargetScene(int index)
=> SetTargetScene(m_currentScenes[index]);
public void SetTargetScene(Scene scene)
{
if (scene == default)
return;
m_currentScene = scene;
var rootObjs = RuntimeProvider.Instance.GetRootGameObjects(scene);
SetSceneObjectList(rootObjs);
m_selectedSceneObject = null;
UI.OnSceneSelected();
}
public void SetSceneObjectParent()
{
if (!m_selectedSceneObject || !m_selectedSceneObject.transform.parent?.gameObject)
{
m_selectedSceneObject = null;
SetTargetScene(m_currentScene);
}
else
{
SetTargetObject(m_selectedSceneObject.transform.parent.gameObject);
}
}
public void SetTargetObject(GameObject obj)
{
if (!obj)
return;
UI.OnGameObjectSelected(obj);
m_selectedSceneObject = obj;
RefreshSelectedSceneObject();
}
private void RefreshSelectedSceneObject()
{
GameObject[] list = new GameObject[m_selectedSceneObject.transform.childCount];
for (int i = 0; i < m_selectedSceneObject.transform.childCount; i++)
{
list[i] = m_selectedSceneObject.transform.GetChild(i).gameObject;
}
SetSceneObjectList(list);
}
private void SetSceneObjectList(GameObject[] objects)
{
m_allObjects = objects;
RefreshSceneObjectList();
}
internal void RefreshSceneObjectList()
{
m_timeOfLastSceneUpdate = Time.realtimeSinceStartup;
UI.RefreshSceneObjectList(m_allObjects, out int newCount);
m_lastCount = newCount;
}
internal static void InspectSelectedGameObject()
{
InspectorManager.Instance.Inspect(Instance.m_selectedSceneObject);
}
internal static void InvokeOnToggleShow()
{
OnToggleShow?.Invoke();
}
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnityExplorer.Search
{
internal enum ChildFilter
{
Any,
RootObject,
HasParent
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnityExplorer.Search
{
internal enum SceneFilter
{
Any,
Asset,
DontDestroyOnLoad,
Explicit,
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnityExplorer.Search
{
internal enum SearchContext
{
UnityObject,
GameObject,
Component,
Custom,
Singleton,
StaticClass
}
}

View File

@ -0,0 +1,227 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityExplorer.Core;
using UnityExplorer.Core.Runtime;
using UnityExplorer.UI.Main;
namespace UnityExplorer.Search
{
public static class SearchProvider
{
internal static object[] StaticClassSearch(string input)
{
var list = new List<Type>();
var nameFilter = "";
if (!string.IsNullOrEmpty(input))
nameFilter = input.ToLower();
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in asm.TryGetTypes().Where(it => it.IsSealed && it.IsAbstract))
{
if (!string.IsNullOrEmpty(nameFilter) && !type.FullName.ToLower().Contains(nameFilter))
continue;
list.Add(type);
}
}
return list.ToArray();
}
internal static string[] s_instanceNames = new string[]
{
"m_instance",
"m_Instance",
"s_instance",
"s_Instance",
"_instance",
"_Instance",
"instance",
"Instance",
"<Instance>k__BackingField",
"<instance>k__BackingField",
};
internal static object[] SingletonSearch(string input)
{
var instances = new List<object>();
var nameFilter = "";
if (!string.IsNullOrEmpty(input))
nameFilter = input.ToLower();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
// Search all non-static, non-enum classes.
foreach (var type in asm.TryGetTypes().Where(it => !(it.IsSealed && it.IsAbstract) && !it.IsEnum))
{
try
{
if (!string.IsNullOrEmpty(nameFilter) && !type.FullName.ToLower().Contains(nameFilter))
continue;
#if CPP
// Only look for Properties in IL2CPP, not for Mono.
PropertyInfo pi;
foreach (var name in s_instanceNames)
{
pi = type.GetProperty(name, flags);
if (pi != null)
{
var instance = pi.GetValue(null, null);
if (instance != null)
{
instances.Add(instance);
continue;
}
}
}
#endif
// Look for a typical Instance backing field.
FieldInfo fi;
foreach (var name in s_instanceNames)
{
fi = type.GetField(name, flags);
if (fi != null)
{
var instance = fi.GetValue(null);
if (instance != null)
{
instances.Add(instance);
break;
}
}
}
}
catch { }
}
}
return instances.ToArray();
}
internal static object[] UnityObjectSearch(string input, string customTypeInput, SearchContext context,
ChildFilter childFilter, SceneFilter sceneFilter)
{
Type searchType = null;
switch (context)
{
case SearchContext.GameObject:
searchType = typeof(GameObject); break;
case SearchContext.Component:
searchType = typeof(Component); break;
case SearchContext.Custom:
if (string.IsNullOrEmpty(customTypeInput))
{
ExplorerCore.LogWarning("Custom Type input must not be empty!");
return null;
}
if (ReflectionUtility.GetTypeByName(customTypeInput) is Type customType)
if (typeof(UnityEngine.Object).IsAssignableFrom(customType))
searchType = customType;
else
ExplorerCore.LogWarning($"Custom type '{customType.FullName}' is not assignable from UnityEngine.Object!");
else
ExplorerCore.LogWarning($"Could not find a type by the name '{customTypeInput}'!");
break;
default:
searchType = typeof(UnityEngine.Object); break;
}
if (searchType == null)
return null;
var allObjects = RuntimeProvider.Instance.FindObjectsOfTypeAll(searchType);
var results = new List<object>();
// perform filter comparers
string nameFilter = null;
if (!string.IsNullOrEmpty(input))
nameFilter = input.ToLower();
bool canGetGameObject = (sceneFilter != SceneFilter.Any || childFilter != ChildFilter.Any)
&& (context == SearchContext.GameObject || typeof(Component).IsAssignableFrom(searchType));
string sceneFilterString = null;
if (!canGetGameObject)
{
if (context != SearchContext.UnityObject && (sceneFilter != SceneFilter.Any || childFilter != ChildFilter.Any))
ExplorerCore.LogWarning($"Type '{searchType}' cannot have Scene or Child filters applied to it");
}
else
{
if (sceneFilter == SceneFilter.DontDestroyOnLoad)
sceneFilterString = "DontDestroyOnLoad";
else if (sceneFilter == SceneFilter.Explicit)
sceneFilterString = SearchPage.Instance.m_sceneDropdown.options[SearchPage.Instance.m_sceneDropdown.value].text;
}
foreach (var obj in allObjects)
{
// name check
if (!string.IsNullOrEmpty(nameFilter) && !obj.name.ToLower().Contains(nameFilter))
continue;
if (canGetGameObject)
{
#if MONO
var go = context == SearchContext.GameObject
? obj as GameObject
: (obj as Component).gameObject;
#else
var go = context == SearchContext.GameObject
? obj.TryCast<GameObject>()
: obj.TryCast<Component>().gameObject;
#endif
// scene check
if (sceneFilter != SceneFilter.Any)
{
if (!go)
continue;
switch (context)
{
case SearchContext.GameObject:
if (go.scene.name != sceneFilterString)
continue;
break;
case SearchContext.Custom:
case SearchContext.Component:
if (go.scene.name != sceneFilterString)
continue;
break;
}
}
if (childFilter != ChildFilter.Any)
{
if (!go)
continue;
// root object check (no parent)
if (childFilter == ChildFilter.HasParent && !go.transform.parent)
continue;
else if (childFilter == ChildFilter.RootObject && go.transform.parent)
continue;
}
}
results.Add(obj);
}
return results.ToArray();
}
}
}

290
src/Core/Tests/Tests.cs Normal file
View File

@ -0,0 +1,290 @@
//using System.Collections;
//using System.Collections.Generic;
//using UnityExplorer.UI;
//using UnityEngine;
//using System;
//using System.Runtime.InteropServices;
//using System.Text;
//using UnityExplorer.Core.Runtime;
//namespace UnityExplorer.Core.Tests
//{
// internal enum TestByteEnum : byte
// {
// One,
// Two,
// Three,
// TwoFiftyFive = 255,
// }
// public static class StaticTestClass
// {
// public static int StaticProperty => 5;
// public static int StaticField = 69;
// public static List<string> StaticList = new List<string>
// {
// "one",
// "two",
// "three",
// };
// public static void StaticMethod() { }
// }
// public class TestClass
// {
// internal static TestByteEnum testingByte = TestByteEnum.One;
// public string AAALongString = @"1
//2
//3
//4
//5";
// public Vector2 AATestVector2 = new Vector2(1, 2);
// public Vector3 AATestVector3 = new Vector3(1, 2, 3);
// public Vector4 AATestVector4 = new Vector4(1, 2, 3, 4);
// public Rect AATestRect = new Rect(1, 2, 3, 4);
// public Color AATestColor = new Color(0.1f, 0.2f, 0.3f, 0.4f);
// public bool ATestBoolMethod() => false;
// public bool this[int index]
// {
// get => index % 2 == 0;
// set => m_thisBool = value;
// }
// internal bool m_thisBool;
// static int testInt;
// public static List<string> ExceptionList
// {
// get
// {
// testInt++;
// if (testInt % 2 == 0)
// throw new Exception("its even");
// else
// return new List<string> { "one" };
// }
// }
// static bool abool;
// public static bool ATestExceptionBool
// {
// get
// {
// abool = !abool;
// if (!abool)
// throw new Exception("false");
// else
// return true;
// }
// }
// public static string ExceptionString => throw new NotImplementedException();
// public static string ANullString = null;
// public static float ATestFloat = 420.69f;
// public static int ATestInt = -1;
// public static string ATestString = "hello world";
// public static uint ATestUInt = 1u;
// public static byte ATestByte = 255;
// public static ulong AReadonlyUlong = 82934UL;
// public static TestClass Instance => m_instance ?? (m_instance = new TestClass());
// private static TestClass m_instance;
// public object AmbigObject;
// public List<List<List<string>>> ANestedNestedList = new List<List<List<string>>>
// {
// new List<List<string>>
// {
// new List<string>
// {
// "one",
// "two",
// },
// new List<string>
// {
// "three",
// "four"
// }
// },
// new List<List<string>>
// {
// new List<string>
// {
// "five",
// "six"
// }
// }
// };
// public static bool SetOnlyProperty
// {
// set => m_setOnlyProperty = value;
// }
// private static bool m_setOnlyProperty;
// public static bool ReadSetOnlyProperty => m_setOnlyProperty;
// public Texture2D TestTexture;
// public static Sprite TestSprite;
//#if CPP
// public static Il2CppSystem.Collections.Generic.HashSet<string> CppHashSetTest;
// public static Il2CppSystem.Collections.Generic.List<string> CppStringTest;
// public static Il2CppSystem.Collections.IList CppIList;
// //public static Il2CppSystem.Collections.Generic.Dictionary<string, string> CppDictTest;
// //public static Il2CppSystem.Collections.Generic.Dictionary<int, float> CppDictTest2;
//#endif
// public TestClass()
// {
// int a = 0;
// foreach (var list in ANestedNestedList)
// {
// foreach (var list2 in list)
// {
// for (int i = 0; i < 33; i++)
// list2.Add(a++.ToString());
// }
// }
//#if CPP
// //TextureSpriteTest();
// CppHashSetTest = new Il2CppSystem.Collections.Generic.HashSet<string>();
// CppHashSetTest.Add("1");
// CppHashSetTest.Add("2");
// CppHashSetTest.Add("3");
// CppStringTest = new Il2CppSystem.Collections.Generic.List<string>();
// CppStringTest.Add("1");
// CppStringTest.Add("2");
// //CppDictTest = new Il2CppSystem.Collections.Generic.Dictionary<string, string>();
// //CppDictTest.Add("key1", "value1");
// //CppDictTest.Add("key2", "value2");
// //CppDictTest.Add("key3", "value3");
// //CppDictTest2 = new Il2CppSystem.Collections.Generic.Dictionary<int, float>();
// //CppDictTest2.Add(0, 0.5f);
// //CppDictTest2.Add(1, 0.5f);
// //CppDictTest2.Add(2, 0.5f);
//#endif
// }
// //private void TextureSpriteTest()
// //{
// // TestTexture = new Texture2D(32, 32, TextureFormat.ARGB32, false)
// // {
// // name = "TestTexture"
// // };
// // TestSprite = TextureUtilProvider.Instance.CreateSprite(TestTexture);
// // GameObject.DontDestroyOnLoad(TestTexture);
// // GameObject.DontDestroyOnLoad(TestSprite);
// // // test loading a tex from file
// // if (System.IO.File.Exists(@"D:\Downloads\test.png"))
// // {
// // var dataToLoad = System.IO.File.ReadAllBytes(@"D:\Downloads\test.png");
// // ExplorerCore.Log($"Tex load success: {TestTexture.LoadImage(dataToLoad, false)}");
// // }
// //}
// //public static string TestRefInOutGeneric<T>(ref string arg0, in int arg1, out string arg2) where T : Component
// //{
// // arg2 = "this is arg2";
// // return $"T: '{typeof(T).FullName}', ref arg0: '{arg0}', in arg1: '{arg1}', out arg2: '{arg2}'";
// //}
// // test a non-generic dictionary
// public Hashtable TestNonGenericDict()
// {
// return new Hashtable
// {
// { "One", 1 },
// { "Two", 2 },
// { "Three", 3 },
// };
// }
// // test HashSets
// public static HashSet<string> HashSetTest = new HashSet<string>
// {
// "One",
// "Two",
// "Three"
// };
// // Test indexed parameter
// public string this[int arg0, string arg1]
// {
// get
// {
// return $"arg0: {arg0}, arg1: {arg1}";
// }
// }
// // Test basic list
// public static List<string> TestList = new List<string>
// {
// "1",
// "2",
// "3",
// "etc..."
// };
// // Test a nested dictionary
// public static Dictionary<int, Dictionary<string, int>> NestedDictionary = new Dictionary<int, Dictionary<string, int>>
// {
// {
// 1,
// new Dictionary<string, int>
// {
// {
// "Sub 1", 123
// },
// {
// "Sub 2", 456
// },
// }
// },
// {
// 2,
// new Dictionary<string, int>
// {
// {
// "Sub 3", 789
// },
// {
// "Sub 4", 000
// },
// }
// },
// };
// // Test a basic method
// public static Color TestMethod(float r, float g, float b, float a)
// {
// return new Color(r, g, b, a);
// }
// // A method with default arguments
// public static Vector3 TestDefaultArgs(float arg0, float arg1, float arg2 = 5.0f)
// {
// return new Vector3(arg0, arg1, arg2);
// }
// }
//}

View File

@ -1,9 +1,9 @@
using System.Globalization;
using UnityEngine;
namespace UnityExplorer.Unstrip
namespace UnityExplorer.Core.Unity
{
public static class ColorUtilityUnstrip
public static class ColorHelper
{
/// <summary>
/// Converts Color to 6-digit RGB hex code (without # symbol). Eg, RGBA(1,0,0,1) -> FF0000

View File

@ -1,8 +1,8 @@
using UnityEngine;
namespace UnityExplorer.Helpers
namespace UnityExplorer.Core.Unity
{
public static class UnityHelpers
public static class UnityHelper
{
private static Camera m_mainCamera;

View File

@ -1,42 +1,38 @@
using System;
using System.IO;
using System.Reflection;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityExplorer.Config;
using UnityExplorer.Input;
using UnityExplorer.Inspectors;
using UnityExplorer.Core.Config;
using UnityExplorer.Core.Unity;
using UnityExplorer.Core.Input;
using UnityExplorer.Core.Inspectors;
using UnityExplorer.Core.Runtime;
using UnityExplorer.UI;
using UnityExplorer.UI.Modules;
#if CPP
using UnityExplorer.Helpers;
#endif
using UnityExplorer.UI.Main;
using UnityExplorer.UI.Utility;
namespace UnityExplorer
{
public class ExplorerCore
{
public const string NAME = "UnityExplorer";
public const string VERSION = "3.1.5";
public const string VERSION = "3.2.10";
public const string AUTHOR = "Sinai";
public const string GUID = "com.sinai.unityexplorer";
#if ML
public const string EXPLORER_FOLDER = @"Mods\UnityExplorer";
#elif BIE
public static string EXPLORER_FOLDER = Path.Combine(BepInEx.Paths.ConfigPath, "UnityExplorer");
#endif
public static ExplorerCore Instance { get; private set; }
public static bool ShowMenu
{
get => s_showMenu;
set => SetShowMenu(value);
}
public static bool s_showMenu;
public static IExplorerLoader Loader =>
#if ML
ExplorerMelonMod.Instance;
#elif BIE
ExplorerBepInPlugin.Instance;
#elif STANDALONE
ExplorerStandalone.Instance;
#endif
private static bool s_doneUIInit;
private static float s_timeSinceStartup;
public static string EXPLORER_FOLDER => Loader.ExplorerFolder;
public ExplorerCore()
{
@ -48,102 +44,33 @@ namespace UnityExplorer
Instance = this;
#if CPP
ReflectionHelpers.TryLoadGameModules();
#endif
if (!Directory.Exists(EXPLORER_FOLDER))
Directory.CreateDirectory(EXPLORER_FOLDER);
ModConfig.OnLoad();
ExplorerConfig.OnLoad();
RuntimeProvider.Init();
InputManager.Init();
ForceUnlockCursor.Init();
SetupEvents();
CursorUnlocker.Init();
ShowMenu = true;
UIManager.ShowMenu = true;
Log($"{NAME} {VERSION} initialized.");
}
public static void Update()
{
if (!s_doneUIInit)
CheckUIInit();
UIManager.CheckUIInit();
if (MouseInspector.Enabled)
MouseInspector.UpdateInspect();
if (InspectUnderMouse.Enabled)
InspectUnderMouse.UpdateInspect();
else
{
if (InputManager.GetKeyDown(ModConfig.Instance.Main_Menu_Toggle))
ShowMenu = !ShowMenu;
if (ShowMenu && s_doneUIInit)
UIManager.Update();
}
UIManager.Update();
}
private static void CheckUIInit()
{
s_timeSinceStartup += Time.deltaTime;
if (s_timeSinceStartup > 0.1f)
{
s_doneUIInit = true;
try
{
UIManager.Init();
Log("Initialized UnityExplorer UI.");
// InspectorManager.Instance.Inspect(Tests.TestClass.Instance);
}
catch (Exception e)
{
LogWarning($"Exception setting up UI: {e}");
}
}
}
private void SetupEvents()
{
#if CPP
try
{
Application.add_logMessageReceived(new Action<string, string, LogType>(OnUnityLog));
SceneManager.add_sceneLoaded(new Action<Scene, LoadSceneMode>((Scene a, LoadSceneMode b) => { OnSceneLoaded(); }));
SceneManager.add_activeSceneChanged(new Action<Scene, Scene>((Scene a, Scene b) => { OnSceneLoaded(); }));
}
catch { }
#else
Application.logMessageReceived += OnUnityLog;
SceneManager.sceneLoaded += (Scene a, LoadSceneMode b) => { OnSceneLoaded(); };
SceneManager.activeSceneChanged += (Scene a, Scene b) => { OnSceneLoaded(); };
#endif
}
internal void OnSceneLoaded()
{
UIManager.OnSceneChange();
}
private static void SetShowMenu(bool show)
{
s_showMenu = show;
if (UIManager.CanvasRoot)
{
UIManager.CanvasRoot.SetActive(show);
if (show)
ForceUnlockCursor.SetEventSystem();
else
ForceUnlockCursor.ReleaseEventSystem();
}
ForceUnlockCursor.UpdateCursorControl();
}
private void OnUnityLog(string message, string stackTrace, LogType type)
public void OnUnityLog(string message, string stackTrace, LogType type)
{
if (!DebugConsole.LogUnity)
return;
@ -173,11 +100,7 @@ namespace UnityExplorer
if (unity)
return;
#if ML
MelonLoader.MelonLogger.Log(message?.ToString());
#else
ExplorerBepInPlugin.Logging?.LogMessage(message?.ToString());
#endif
Loader.OnLogMessage(message);
}
public static void LogWarning(object message, bool unity = false)
@ -187,11 +110,7 @@ namespace UnityExplorer
if (unity)
return;
#if ML
MelonLoader.MelonLogger.LogWarning(message?.ToString());
#else
ExplorerBepInPlugin.Logging?.LogWarning(message?.ToString());
#endif
Loader.OnLogWarning(message);
}
public static void LogError(object message, bool unity = false)
@ -201,22 +120,7 @@ namespace UnityExplorer
if (unity)
return;
#if ML
MelonLoader.MelonLogger.LogError(message?.ToString());
#else
ExplorerBepInPlugin.Logging?.LogError(message?.ToString());
#endif
}
public static string RemoveInvalidFilenameChars(string s)
{
var invalid = System.IO.Path.GetInvalidFileNameChars();
foreach (var c in invalid)
{
s = s.Replace(c.ToString(), "");
}
return s;
Loader.OnLogError(message);
}
}
}

View File

@ -1,29 +0,0 @@
#if ML
using System;
using MelonLoader;
namespace UnityExplorer
{
public class ExplorerMelonMod : MelonMod
{
public static ExplorerMelonMod Instance;
public override void OnApplicationStart()
{
Instance = this;
new ExplorerCore();
}
public override void OnUpdate()
{
ExplorerCore.Update();
}
public override void OnLevelWasLoaded(int level)
{
ExplorerCore.Instance.OnSceneLoaded();
}
}
}
#endif

View File

@ -1,33 +0,0 @@
#if CPP
using System;
using UnityEngine.Events;
namespace UnityExplorer.Helpers
{
// Possibly temporary, just so Il2Cpp can do the same style "AddListener" as Mono.
// Just saves me having a preprocessor directive for every single AddListener.
public static class EventHelper
{
public static void AddListener(this UnityEvent action, Action listener)
{
action.AddListener(listener);
}
public static void AddListener<T>(this UnityEvent<T> action, Action<T> listener)
{
action.AddListener(listener);
}
public static void AddListener<T0, T1>(this UnityEvent<T0, T1> action, Action<T0, T1> listener)
{
action.AddListener(listener);
}
public static void AddListener<T0, T1, T2>(this UnityEvent<T0, T1, T2> action, Action<T0, T1, T2> listener)
{
action.AddListener(listener);
}
}
}
#endif

View File

@ -1,36 +0,0 @@
#if CPP
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace UnityExplorer.Helpers
{
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "External methods")]
public static class ICallHelper
{
private static readonly Dictionary<string, Delegate> iCallCache = new Dictionary<string, Delegate>();
public static T GetICall<T>(string iCallName) where T : Delegate
{
if (iCallCache.ContainsKey(iCallName))
return (T)iCallCache[iCallName];
IntPtr ptr = il2cpp_resolve_icall(iCallName);
if (ptr == IntPtr.Zero)
{
throw new MissingMethodException($"Could not resolve internal call by name '{iCallName}'!");
}
Delegate iCall = Marshal.GetDelegateForFunctionPointer(ptr, typeof(T));
iCallCache.Add(iCallName, iCall);
return (T)iCall;
}
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr il2cpp_resolve_icall([MarshalAs(UnmanagedType.LPStr)] string name);
}
}
#endif

View File

@ -1,330 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
using BF = System.Reflection.BindingFlags;
using System.Diagnostics.CodeAnalysis;
#if CPP
using CppType = Il2CppSystem.Type;
using UnhollowerBaseLib;
using UnhollowerRuntimeLib;
using System.Runtime.InteropServices;
#endif
namespace UnityExplorer.Helpers
{
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "External methods")]
public static class ReflectionHelpers
{
public static BF CommonFlags = BF.Public | BF.Instance | BF.NonPublic | BF.Static;
public static Type GetTypeByName(string fullName)
{
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in asm.TryGetTypes())
{
if (type.FullName == fullName)
{
return type;
}
}
}
return null;
}
public static Type[] GetAllBaseTypes(object obj) => GetAllBaseTypes(GetActualType(obj));
public static Type[] GetAllBaseTypes(Type type)
{
List<Type> list = new List<Type>();
while (type != null)
{
list.Add(type);
type = type.BaseType;
}
return list.ToArray();
}
public static Type GetActualType(this object obj)
{
if (obj == null)
return null;
var type = obj.GetType();
#if CPP
if (obj is Il2CppSystem.Object ilObject)
{
if (ilObject is CppType)
return typeof(CppType);
if (!string.IsNullOrEmpty(type.Namespace))
{
// Il2CppSystem-namespace objects should just return GetType,
// because using GetIl2CppType returns the System namespace type instead.
if (type.Namespace.StartsWith("System.") || type.Namespace.StartsWith("Il2CppSystem."))
return ilObject.GetType();
}
var il2cppType = ilObject.GetIl2CppType();
// check if type is injected
IntPtr classPtr = il2cpp_object_get_class(ilObject.Pointer);
if (RuntimeSpecificsStore.IsInjected(classPtr))
{
var typeByName = GetTypeByName(il2cppType.FullName);
if (typeByName != null)
return typeByName;
}
// this should be fine for all other il2cpp objects
var getType = GetMonoType(il2cppType);
if (getType != null)
return getType;
}
#endif
return type;
}
#if CPP
private static readonly Dictionary<CppType, Type> Il2CppToMonoType = new Dictionary<CppType, Type>();
public static Type GetMonoType(CppType cppType)
{
if (Il2CppToMonoType.ContainsKey(cppType))
return Il2CppToMonoType[cppType];
var getType = Type.GetType(cppType.AssemblyQualifiedName);
Il2CppToMonoType.Add(cppType, getType);
return getType;
}
private static readonly Dictionary<Type, IntPtr> CppClassPointers = new Dictionary<Type, IntPtr>();
/// <summary>
/// Attempt to cast the object to its underlying type.
/// </summary>
/// <param name="obj">The object you want to cast.</param>
/// <returns>The object, as the underlying type if successful or the input value if not.</returns>
public static object Il2CppCast(this object obj) => Il2CppCast(obj, GetActualType(obj));
/// <summary>
/// Attempt to cast the object to the provided type.
/// </summary>
/// <param name="obj">The object you want to cast.</param>
/// <param name="castTo">The Type you want to cast to.</param>
/// <returns>The object, as the type (or a normal C# object) if successful or the input value if not.</returns>
public static object Il2CppCast(this object obj, Type castTo)
{
if (!(obj is Il2CppSystem.Object ilObj))
return obj;
if (!Il2CppTypeNotNull(castTo, out IntPtr castToPtr))
return obj;
IntPtr castFromPtr = il2cpp_object_get_class(ilObj.Pointer);
if (!il2cpp_class_is_assignable_from(castToPtr, castFromPtr))
return obj;
if (RuntimeSpecificsStore.IsInjected(castToPtr))
return UnhollowerBaseLib.Runtime.ClassInjectorBase.GetMonoObjectFromIl2CppPointer(ilObj.Pointer);
return Activator.CreateInstance(castTo, ilObj.Pointer);
}
internal static readonly Dictionary<Type, MethodInfo> s_unboxMethods = new Dictionary<Type, MethodInfo>();
/// <summary>
/// Attempt to unbox the object to the underlying struct type.
/// </summary>
/// <param name="obj">The object which is a struct underneath.</param>
/// <returns>The struct if successful, otherwise null.</returns>
public static object Unbox(this object obj) => Unbox(obj, GetActualType(obj));
/// <summary>
/// Attempt to unbox the object to the struct type.
/// </summary>
/// <param name="obj">The object which is a struct underneath.</param>
/// <param name="type">The type of the struct you want to unbox to.</param>
/// <returns>The struct if successful, otherwise null.</returns>
public static object Unbox(this object obj, Type type)
{
if (!type.IsValueType)
return null;
if (!(obj is Il2CppSystem.Object))
return obj;
if (!s_unboxMethods.ContainsKey(type))
{
s_unboxMethods.Add(type, typeof(Il2CppObjectBase)
.GetMethod("Unbox")
.MakeGenericMethod(type));
}
return s_unboxMethods[type].Invoke(obj, new object[0]);
}
public static bool Il2CppTypeNotNull(Type type) => Il2CppTypeNotNull(type, out _);
public static bool Il2CppTypeNotNull(Type type, out IntPtr il2cppPtr)
{
if (!CppClassPointers.ContainsKey(type))
{
il2cppPtr = (IntPtr)typeof(Il2CppClassPointerStore<>)
.MakeGenericType(new Type[] { type })
.GetField("NativeClassPtr", BF.Public | BF.Static)
.GetValue(null);
CppClassPointers.Add(type, il2cppPtr);
}
else
il2cppPtr = CppClassPointers[type];
return il2cppPtr != IntPtr.Zero;
}
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern bool il2cpp_class_is_assignable_from(IntPtr klass, IntPtr oklass);
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr il2cpp_object_get_class(IntPtr obj);
#endif
public static IEnumerable<Type> TryGetTypes(this Assembly asm)
{
try
{
return asm.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
try
{
return asm.GetExportedTypes();
}
catch
{
return e.Types.Where(t => t != null);
}
}
catch
{
return Enumerable.Empty<Type>();
}
}
#if CPP
internal static void TryLoadGameModules()
{
LoadModule("Assembly-CSharp");
LoadModule("Assembly-CSharp-firstpass");
}
public static bool LoadModule(string module)
{
#if ML
var path = $@"MelonLoader\Managed\{module}.dll";
#else
var path = $@"BepInEx\unhollowed\{module}.dll";
#endif
return LoadModuleInternal(path);
}
internal static bool LoadModuleInternal(string fullPath)
{
if (!File.Exists(fullPath))
return false;
try
{
Assembly.Load(File.ReadAllBytes(fullPath));
return true;
}
catch (Exception e)
{
Console.WriteLine(e.GetType() + ", " + e.Message);
}
return false;
}
#else
public static bool LoadModule(string module) => true;
#endif
#if CPP
internal static IntPtr s_cppEnumerableClassPtr;
#endif
public static bool IsEnumerable(Type t)
{
if (typeof(IEnumerable).IsAssignableFrom(t))
return true;
#if CPP
try
{
if (s_cppEnumerableClassPtr == IntPtr.Zero)
Il2CppTypeNotNull(typeof(Il2CppSystem.Collections.IEnumerable), out s_cppEnumerableClassPtr);
if (s_cppEnumerableClassPtr != IntPtr.Zero
&& Il2CppTypeNotNull(t, out IntPtr classPtr)
&& il2cpp_class_is_assignable_from(s_cppEnumerableClassPtr, classPtr))
{
return true;
}
}
catch { }
#endif
return false;
}
#if CPP
internal static IntPtr s_cppDictionaryClassPtr;
#endif
public static bool IsDictionary(Type t)
{
if (typeof(IDictionary).IsAssignableFrom(t))
return true;
#if CPP
try
{
if (s_cppDictionaryClassPtr == IntPtr.Zero)
if (!Il2CppTypeNotNull(typeof(Il2CppSystem.Collections.IDictionary), out s_cppDictionaryClassPtr))
return false;
if (Il2CppTypeNotNull(t, out IntPtr classPtr))
{
if (il2cpp_class_is_assignable_from(s_cppDictionaryClassPtr, classPtr))
return true;
}
}
catch { }
#endif
return false;
}
public static string ExceptionToString(Exception e, bool innerMost = false)
{
while (innerMost && e.InnerException != null)
{
#if CPP
if (e.InnerException is System.Runtime.CompilerServices.RuntimeWrappedException runtimeEx)
break;
#endif
e = e.InnerException;
}
return e.GetType() + ", " + e.Message;
}
}
}

View File

@ -1,138 +0,0 @@
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.UI;
namespace UnityExplorer.Inspectors
{
public abstract class InspectorBase
{
public object Target;
public abstract string TabLabel { get; }
public bool IsActive { get; private set; }
public abstract GameObject Content { get; set; }
public Button tabButton;
public Text tabText;
internal bool m_pendingDestroy;
public InspectorBase(object target)
{
Target = target;
if (Target.IsNullOrDestroyed(false))
{
Destroy();
return;
}
AddInspectorTab();
}
public virtual void SetActive()
{
this.IsActive = true;
Content?.SetActive(true);
}
public virtual void SetInactive()
{
this.IsActive = false;
Content?.SetActive(false);
}
public virtual void Update()
{
if (Target.IsNullOrDestroyed(false))
{
Destroy();
return;
}
tabText.text = TabLabel;
}
public virtual void Destroy()
{
m_pendingDestroy = true;
GameObject tabGroup = tabButton?.transform.parent.gameObject;
if (tabGroup)
{
GameObject.Destroy(tabGroup);
}
int thisIndex = -1;
if (InspectorManager.Instance.m_currentInspectors.Contains(this))
{
thisIndex = InspectorManager.Instance.m_currentInspectors.IndexOf(this);
InspectorManager.Instance.m_currentInspectors.Remove(this);
}
if (ReferenceEquals(InspectorManager.Instance.m_activeInspector, this))
{
InspectorManager.Instance.UnsetInspectorTab();
if (InspectorManager.Instance.m_currentInspectors.Count > 0)
{
var prevTab = InspectorManager.Instance.m_currentInspectors[thisIndex > 0 ? thisIndex - 1 : 0];
InspectorManager.Instance.SetInspectorTab(prevTab);
}
}
}
#region UI CONSTRUCTION
public void AddInspectorTab()
{
var tabContent = InspectorManager.Instance.m_tabBarContent;
var tabGroupObj = UIFactory.CreateHorizontalGroup(tabContent);
var tabGroup = tabGroupObj.GetComponent<HorizontalLayoutGroup>();
tabGroup.childForceExpandWidth = true;
tabGroup.childControlWidth = true;
var tabLayout = tabGroupObj.AddComponent<LayoutElement>();
tabLayout.minWidth = 185;
tabLayout.flexibleWidth = 0;
tabGroupObj.AddComponent<Mask>();
var targetButtonObj = UIFactory.CreateButton(tabGroupObj);
targetButtonObj.AddComponent<Mask>();
var targetButtonLayout = targetButtonObj.AddComponent<LayoutElement>();
targetButtonLayout.minWidth = 165;
targetButtonLayout.flexibleWidth = 0;
tabText = targetButtonObj.GetComponentInChildren<Text>();
tabText.horizontalOverflow = HorizontalWrapMode.Overflow;
tabText.alignment = TextAnchor.MiddleLeft;
tabButton = targetButtonObj.GetComponent<Button>();
tabButton.onClick.AddListener(() => { InspectorManager.Instance.SetInspectorTab(this); });
var closeBtnObj = UIFactory.CreateButton(tabGroupObj);
var closeBtnLayout = closeBtnObj.AddComponent<LayoutElement>();
closeBtnLayout.minWidth = 20;
closeBtnLayout.flexibleWidth = 0;
var closeBtnText = closeBtnObj.GetComponentInChildren<Text>();
closeBtnText.text = "X";
closeBtnText.color = new Color(1, 0, 0, 1);
var closeBtn = closeBtnObj.GetComponent<Button>();
closeBtn.onClick.AddListener(Destroy);
var closeColors = closeBtn.colors;
closeColors.normalColor = new Color(0.2f, 0.2f, 0.2f, 1);
closeBtn.colors = closeColors;
}
#endregion
}
}

View File

@ -1,230 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Input;
using UnityExplorer.UI;
using UnityExplorer.Unstrip;
namespace UnityExplorer.Inspectors
{
public class MouseInspector
{
public enum MouseInspectMode
{
World,
UI
}
public static bool Enabled { get; set; }
public static MouseInspectMode Mode { get; set; }
internal static Text s_objNameLabel;
internal static Text s_objPathLabel;
internal static Text s_mousePosLabel;
private static GameObject s_lastHit;
private static Vector3 s_lastMousePos;
internal static GameObject s_UIContent;
public static void StartInspect()
{
Enabled = true;
MainMenu.Instance.MainPanel.SetActive(false);
s_UIContent.SetActive(true);
// recache Graphic Raycasters each time we start
var casters = ResourcesUnstrip.FindObjectsOfTypeAll(typeof(GraphicRaycaster));
m_gCasters = new GraphicRaycaster[casters.Length];
for (int i = 0; i < casters.Length; i++)
{
#if CPP
m_gCasters[i] = casters[i].TryCast<GraphicRaycaster>();
#else
m_gCasters[i] = casters[i] as GraphicRaycaster;
#endif
}
}
public static void StopInspect()
{
Enabled = false;
MainMenu.Instance.MainPanel.SetActive(true);
s_UIContent.SetActive(false);
ClearHitData();
}
internal static GraphicRaycaster[] m_gCasters;
public static void UpdateInspect()
{
if (InputManager.GetKeyDown(KeyCode.Escape))
{
StopInspect();
return;
}
var mousePos = InputManager.MousePosition;
if (mousePos != s_lastMousePos)
UpdatePosition(mousePos);
if (!UnityHelpers.MainCamera)
return;
// actual inspect raycast
switch (Mode)
{
case MouseInspectMode.UI:
RaycastUI(mousePos); break;
case MouseInspectMode.World:
RaycastWorld(mousePos); break;
}
}
internal static void OnHitGameObject(GameObject obj)
{
if (obj != s_lastHit)
{
s_lastHit = obj;
s_objNameLabel.text = $"<b>Click to Inspect:</b> <color=cyan>{obj.name}</color>";
s_objPathLabel.text = $"Path: {obj.transform.GetTransformPath(true)}";
}
if (InputManager.GetMouseButtonDown(0))
{
StopInspect();
InspectorManager.Instance.Inspect(obj);
}
}
internal static void RaycastWorld(Vector2 mousePos)
{
var ray = UnityHelpers.MainCamera.ScreenPointToRay(mousePos);
Physics.Raycast(ray, out RaycastHit hit, 1000f);
if (hit.transform)
{
var obj = hit.transform.gameObject;
OnHitGameObject(obj);
}
else
{
if (s_lastHit)
ClearHitData();
}
}
internal static void RaycastUI(Vector2 mousePos)
{
var ped = new PointerEventData(null)
{
position = mousePos
};
#if MONO
var list = new List<RaycastResult>();
#else
var list = new Il2CppSystem.Collections.Generic.List<RaycastResult>();
#endif
foreach (var gr in m_gCasters)
{
gr.Raycast(ped, list);
if (list.Count > 0)
{
foreach (var hit in list)
{
if (hit.gameObject)
{
var obj = hit.gameObject;
OnHitGameObject(obj);
break;
}
}
}
else
{
if (s_lastHit)
ClearHitData();
}
}
}
internal static void UpdatePosition(Vector2 mousePos)
{
s_lastMousePos = mousePos;
var inversePos = UIManager.CanvasRoot.transform.InverseTransformPoint(mousePos);
s_mousePosLabel.text = $"<color=grey>Mouse Position:</color> {mousePos.ToString()}";
float yFix = mousePos.y < 120 ? 80 : -80;
s_UIContent.transform.localPosition = new Vector3(inversePos.x, inversePos.y + yFix, 0);
}
internal static void ClearHitData()
{
s_lastHit = null;
s_objNameLabel.text = "No hits...";
s_objPathLabel.text = "";
}
#region UI Construction
internal static void ConstructUI()
{
s_UIContent = UIFactory.CreatePanel(UIManager.CanvasRoot, "MouseInspect", out GameObject content);
s_UIContent.AddComponent<Mask>();
var baseRect = s_UIContent.GetComponent<RectTransform>();
var half = new Vector2(0.5f, 0.5f);
baseRect.anchorMin = half;
baseRect.anchorMax = half;
baseRect.pivot = half;
baseRect.sizeDelta = new Vector2(700, 150);
var group = content.GetComponent<VerticalLayoutGroup>();
group.childForceExpandHeight = true;
// Title text
var titleObj = UIFactory.CreateLabel(content, TextAnchor.MiddleCenter);
var titleText = titleObj.GetComponent<Text>();
titleText.text = "<b>Mouse Inspector</b> (press <b>ESC</b> to cancel)";
var mousePosObj = UIFactory.CreateLabel(content, TextAnchor.MiddleCenter);
s_mousePosLabel = mousePosObj.GetComponent<Text>();
s_mousePosLabel.text = "Mouse Position:";
var hitLabelObj = UIFactory.CreateLabel(content, TextAnchor.MiddleLeft);
s_objNameLabel = hitLabelObj.GetComponent<Text>();
s_objNameLabel.text = "No hits...";
s_objNameLabel.horizontalOverflow = HorizontalWrapMode.Overflow;
var pathLabelObj = UIFactory.CreateLabel(content, TextAnchor.MiddleLeft);
s_objPathLabel = pathLabelObj.GetComponent<Text>();
s_objPathLabel.fontStyle = FontStyle.Italic;
s_objPathLabel.horizontalOverflow = HorizontalWrapMode.Wrap;
var pathLayout = pathLabelObj.AddComponent<LayoutElement>();
pathLayout.minHeight = 75;
pathLayout.flexibleHeight = 0;
s_UIContent.SetActive(false);
}
#endregion
}
}

View File

@ -1,612 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityExplorer.Helpers;
using UnityEngine;
using UnityExplorer.Inspectors.Reflection;
using UnityExplorer.UI.Shared;
using System.Reflection;
using UnityExplorer.UI;
using UnityEngine.UI;
using UnityExplorer.Config;
namespace UnityExplorer.Inspectors
{
public class ReflectionInspector : InspectorBase
{
#region STATIC
public static ReflectionInspector ActiveInstance { get; private set; }
static ReflectionInspector()
{
PanelDragger.OnFinishResize += OnContainerResized;
SceneExplorer.OnToggleShow += OnContainerResized;
}
private static void OnContainerResized()
{
if (ActiveInstance == null)
return;
ActiveInstance.m_widthUpdateWanted = true;
}
// Blacklists
private static readonly HashSet<string> bl_typeAndMember = new HashSet<string>
{
#if CPP
// these cause a crash in IL2CPP
"Type.DeclaringMethod",
"Rigidbody2D.Cast",
"Collider2D.Cast",
"Collider2D.Raycast",
"Texture2D.SetPixelDataImpl",
#endif
};
private static readonly HashSet<string> bl_memberNameStartsWith = new HashSet<string>
{
// these are redundant
"get_",
"set_",
};
#endregion
#region INSTANCE
public override string TabLabel => m_targetTypeShortName;
internal readonly Type m_targetType;
internal readonly string m_targetTypeShortName;
// all cached members of the target
internal CacheMember[] m_allMembers;
// filtered members based on current filters
internal readonly List<CacheMember> m_membersFiltered = new List<CacheMember>();
// actual shortlist of displayed members
internal readonly CacheMember[] m_displayedMembers = new CacheMember[ModConfig.Instance.Default_Page_Limit];
internal bool m_autoUpdate;
// UI members
private GameObject m_content;
public override GameObject Content
{
get => m_content;
set => m_content = value;
}
internal Text m_nameFilterText;
internal MemberTypes m_memberFilter;
internal Button m_lastActiveMemButton;
internal PageHandler m_pageHandler;
internal SliderScrollbar m_sliderScroller;
internal GameObject m_scrollContent;
internal RectTransform m_scrollContentRect;
internal bool m_widthUpdateWanted;
internal bool m_widthUpdateWaiting;
public ReflectionInspector(object target) : base(target)
{
if (this is StaticInspector)
m_targetType = target as Type;
else
m_targetType = ReflectionHelpers.GetActualType(target);
m_targetTypeShortName = UISyntaxHighlight.ParseFullSyntax(m_targetType, false);
ConstructUI();
CacheMembers(m_targetType);
FilterMembers();
}
public override void SetActive()
{
base.SetActive();
ActiveInstance = this;
}
public override void SetInactive()
{
base.SetInactive();
ActiveInstance = null;
}
public override void Destroy()
{
base.Destroy();
if (this.Content)
GameObject.Destroy(this.Content);
}
private void OnPageTurned()
{
RefreshDisplay();
}
internal bool IsBlacklisted(string sig) => bl_typeAndMember.Any(it => sig.Contains(it));
internal bool IsBlacklisted(MethodInfo method) => bl_memberNameStartsWith.Any(it => method.Name.StartsWith(it));
internal string GetSig(MemberInfo member) => $"{member.DeclaringType.Name}.{member.Name}";
internal string AppendArgsToSig(ParameterInfo[] args)
{
string ret = " (";
foreach (var param in args)
ret += $"{param.ParameterType.Name} {param.Name}, ";
ret += ")";
return ret;
}
public void CacheMembers(Type type)
{
var list = new List<CacheMember>();
var cachedSigs = new HashSet<string>();
var types = ReflectionHelpers.GetAllBaseTypes(type);
var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
if (this is InstanceInspector)
flags |= BindingFlags.Instance;
foreach (var declaringType in types)
{
var target = Target;
#if CPP
target = target.Il2CppCast(declaringType);
#endif
IEnumerable<MemberInfo> infos = declaringType.GetMethods(flags);
infos = infos.Concat(declaringType.GetProperties(flags));
infos = infos.Concat(declaringType.GetFields(flags));
foreach (var member in infos)
{
try
{
//ExplorerCore.Log($"Trying to cache member {sig}...");
//ExplorerCore.Log(member.DeclaringType.FullName + "." + member.Name);
var sig = GetSig(member);
var mi = member as MethodInfo;
var pi = member as PropertyInfo;
var fi = member as FieldInfo;
if (IsBlacklisted(sig) || (mi != null && IsBlacklisted(mi)))
continue;
var args = mi?.GetParameters() ?? pi?.GetIndexParameters();
if (args != null)
{
if (!CacheMember.CanProcessArgs(args))
continue;
sig += AppendArgsToSig(args);
}
if (cachedSigs.Contains(sig))
continue;
cachedSigs.Add(sig);
if (mi != null)
list.Add(new CacheMethod(mi, target, m_scrollContent));
else if (pi != null)
list.Add(new CacheProperty(pi, target, m_scrollContent));
else
list.Add(new CacheField(fi, target, m_scrollContent));
}
catch (Exception e)
{
ExplorerCore.LogWarning($"Exception caching member {member.DeclaringType.FullName}.{member.Name}!");
ExplorerCore.Log(e.ToString());
}
}
}
var typeList = types.ToList();
var sorted = new List<CacheMember>();
sorted.AddRange(list.Where(it => it is CacheMethod)
.OrderBy(it => typeList.IndexOf(it.DeclaringType))
.ThenBy(it => it.NameForFiltering));
sorted.AddRange(list.Where(it => it is CacheProperty)
.OrderBy(it => typeList.IndexOf(it.DeclaringType))
.ThenBy(it => it.NameForFiltering));
sorted.AddRange(list.Where(it => it is CacheField)
.OrderBy(it => typeList.IndexOf(it.DeclaringType))
.ThenBy(it => it.NameForFiltering));
m_allMembers = sorted.ToArray();
}
public override void Update()
{
base.Update();
if (m_autoUpdate)
{
foreach (var member in m_displayedMembers)
{
if (member == null) break;
member.UpdateValue();
}
}
if (m_widthUpdateWanted)
{
if (!m_widthUpdateWaiting)
m_widthUpdateWaiting = true;
else
{
UpdateWidths();
m_widthUpdateWaiting = false;
m_widthUpdateWanted = false;
}
}
}
private void OnMemberFilterClicked(MemberTypes type, Button button)
{
if (m_lastActiveMemButton)
{
var lastColors = m_lastActiveMemButton.colors;
lastColors.normalColor = new Color(0.2f, 0.2f, 0.2f);
m_lastActiveMemButton.colors = lastColors;
}
m_memberFilter = type;
m_lastActiveMemButton = button;
var colors = m_lastActiveMemButton.colors;
colors.normalColor = new Color(0.2f, 0.6f, 0.2f);
m_lastActiveMemButton.colors = colors;
FilterMembers(null, true);
m_sliderScroller.m_slider.value = 1f;
}
public void FilterMembers(string nameFilter = null, bool force = false)
{
int lastCount = m_membersFiltered.Count;
m_membersFiltered.Clear();
nameFilter = nameFilter?.ToLower() ?? m_nameFilterText.text.ToLower();
foreach (var mem in m_allMembers)
{
// membertype filter
if (m_memberFilter != MemberTypes.All && mem.MemInfo.MemberType != m_memberFilter)
continue;
if (this is InstanceInspector ii && ii.m_scopeFilter != MemberScopes.All)
{
if (mem.IsStatic && ii.m_scopeFilter != MemberScopes.Static)
continue;
else if (!mem.IsStatic && ii.m_scopeFilter != MemberScopes.Instance)
continue;
}
// name filter
if (!string.IsNullOrEmpty(nameFilter) && !mem.NameForFiltering.Contains(nameFilter))
continue;
m_membersFiltered.Add(mem);
}
if (force || lastCount != m_membersFiltered.Count)
RefreshDisplay();
}
public void RefreshDisplay()
{
var members = m_membersFiltered;
m_pageHandler.ListCount = members.Count;
// disable current members
for (int i = 0; i < m_displayedMembers.Length; i++)
{
var mem = m_displayedMembers[i];
if (mem != null)
mem.Disable();
else
break;
}
if (members.Count < 1)
return;
foreach (var itemIndex in m_pageHandler)
{
if (itemIndex >= members.Count)
break;
CacheMember member = members[itemIndex];
m_displayedMembers[itemIndex - m_pageHandler.StartIndex] = member;
member.Enable();
}
m_widthUpdateWanted = true;
}
internal void UpdateWidths()
{
float labelWidth = 125;
foreach (var cache in m_displayedMembers)
{
if (cache == null)
break;
var width = cache.GetMemberLabelWidth(m_scrollContentRect);
if (width > labelWidth)
labelWidth = width;
}
float valueWidth = m_scrollContentRect.rect.width - labelWidth - 20;
foreach (var cache in m_displayedMembers)
{
if (cache == null)
break;
cache.SetWidths(labelWidth, valueWidth);
}
}
#region UI CONSTRUCTION
internal GameObject m_filterAreaObj;
internal GameObject m_updateRowObj;
internal GameObject m_memberListObj;
internal void ConstructUI()
{
var parent = InspectorManager.Instance.m_inspectorContent;
this.Content = UIFactory.CreateVerticalGroup(parent, new Color(0.15f, 0.15f, 0.15f));
var mainGroup = Content.GetComponent<VerticalLayoutGroup>();
mainGroup.childForceExpandHeight = false;
mainGroup.childForceExpandWidth = true;
mainGroup.childControlHeight = true;
mainGroup.childControlWidth = true;
mainGroup.spacing = 5;
mainGroup.padding.top = 4;
mainGroup.padding.left = 4;
mainGroup.padding.right = 4;
mainGroup.padding.bottom = 4;
ConstructTopArea();
ConstructMemberList();
}
internal void ConstructTopArea()
{
var nameRowObj = UIFactory.CreateHorizontalGroup(Content, new Color(1, 1, 1, 0));
var nameRow = nameRowObj.GetComponent<HorizontalLayoutGroup>();
nameRow.childForceExpandWidth = true;
nameRow.childForceExpandHeight = true;
nameRow.childControlHeight = true;
nameRow.childControlWidth = true;
nameRow.padding.top = 2;
var nameRowLayout = nameRowObj.AddComponent<LayoutElement>();
nameRowLayout.minHeight = 25;
nameRowLayout.flexibleHeight = 0;
nameRowLayout.minWidth = 200;
nameRowLayout.flexibleWidth = 5000;
var typeLabel = UIFactory.CreateLabel(nameRowObj, TextAnchor.MiddleLeft);
var typeLabelText = typeLabel.GetComponent<Text>();
typeLabelText.text = "Type:";
typeLabelText.horizontalOverflow = HorizontalWrapMode.Overflow;
var typeLabelTextLayout = typeLabel.AddComponent<LayoutElement>();
typeLabelTextLayout.minWidth = 40;
typeLabelTextLayout.flexibleWidth = 0;
typeLabelTextLayout.minHeight = 25;
var typeDisplayObj = UIFactory.CreateLabel(nameRowObj, TextAnchor.MiddleLeft);
var typeDisplayText = typeDisplayObj.GetComponent<Text>();
typeDisplayText.text = UISyntaxHighlight.ParseFullSyntax(m_targetType, true);
var typeDisplayLayout = typeDisplayObj.AddComponent<LayoutElement>();
typeDisplayLayout.minHeight = 25;
typeDisplayLayout.flexibleWidth = 5000;
// Helper tools
if (this is InstanceInspector)
{
(this as InstanceInspector).ConstructInstanceHelpers();
}
ConstructFilterArea();
ConstructUpdateRow();
}
internal void ConstructFilterArea()
{
// Filters
var filterAreaObj = UIFactory.CreateVerticalGroup(Content, new Color(0.1f, 0.1f, 0.1f));
var filterLayout = filterAreaObj.AddComponent<LayoutElement>();
filterLayout.minHeight = 60;
var filterGroup = filterAreaObj.GetComponent<VerticalLayoutGroup>();
filterGroup.childForceExpandWidth = true;
filterGroup.childForceExpandHeight = true;
filterGroup.childControlWidth = true;
filterGroup.childControlHeight = true;
filterGroup.spacing = 4;
filterGroup.padding.left = 4;
filterGroup.padding.right = 4;
filterGroup.padding.top = 4;
filterGroup.padding.bottom = 4;
m_filterAreaObj = filterAreaObj;
// name filter
var nameFilterRowObj = UIFactory.CreateHorizontalGroup(filterAreaObj, new Color(1, 1, 1, 0));
var nameFilterGroup = nameFilterRowObj.GetComponent<HorizontalLayoutGroup>();
nameFilterGroup.childForceExpandHeight = false;
nameFilterGroup.childForceExpandWidth = false;
nameFilterGroup.childControlWidth = true;
nameFilterGroup.childControlHeight = true;
nameFilterGroup.spacing = 5;
var nameFilterLayout = nameFilterRowObj.AddComponent<LayoutElement>();
nameFilterLayout.minHeight = 25;
nameFilterLayout.flexibleHeight = 0;
nameFilterLayout.flexibleWidth = 5000;
var nameLabelObj = UIFactory.CreateLabel(nameFilterRowObj, TextAnchor.MiddleLeft);
var nameLabelLayout = nameLabelObj.AddComponent<LayoutElement>();
nameLabelLayout.minWidth = 100;
nameLabelLayout.minHeight = 25;
nameLabelLayout.flexibleWidth = 0;
var nameLabelText = nameLabelObj.GetComponent<Text>();
nameLabelText.text = "Filter names:";
nameLabelText.color = Color.grey;
var nameInputObj = UIFactory.CreateInputField(nameFilterRowObj, 14, (int)TextAnchor.MiddleLeft, (int)HorizontalWrapMode.Overflow);
var nameInputLayout = nameInputObj.AddComponent<LayoutElement>();
nameInputLayout.flexibleWidth = 5000;
nameInputLayout.minWidth = 100;
nameInputLayout.minHeight = 25;
var nameInput = nameInputObj.GetComponent<InputField>();
nameInput.onValueChanged.AddListener((string val) => { FilterMembers(val); });
m_nameFilterText = nameInput.textComponent;
// membertype filter
var memberFilterRowObj = UIFactory.CreateHorizontalGroup(filterAreaObj, new Color(1, 1, 1, 0));
var memFilterGroup = memberFilterRowObj.GetComponent<HorizontalLayoutGroup>();
memFilterGroup.childForceExpandHeight = false;
memFilterGroup.childForceExpandWidth = false;
memFilterGroup.childControlWidth = true;
memFilterGroup.childControlHeight = true;
memFilterGroup.spacing = 5;
var memFilterLayout = memberFilterRowObj.AddComponent<LayoutElement>();
memFilterLayout.minHeight = 25;
memFilterLayout.flexibleHeight = 0;
memFilterLayout.flexibleWidth = 5000;
var memLabelObj = UIFactory.CreateLabel(memberFilterRowObj, TextAnchor.MiddleLeft);
var memLabelLayout = memLabelObj.AddComponent<LayoutElement>();
memLabelLayout.minWidth = 100;
memLabelLayout.minHeight = 25;
memLabelLayout.flexibleWidth = 0;
var memLabelText = memLabelObj.GetComponent<Text>();
memLabelText.text = "Filter members:";
memLabelText.color = Color.grey;
AddFilterButton(memberFilterRowObj, MemberTypes.All);
AddFilterButton(memberFilterRowObj, MemberTypes.Method);
AddFilterButton(memberFilterRowObj, MemberTypes.Property, true);
AddFilterButton(memberFilterRowObj, MemberTypes.Field);
// Instance filters
if (this is InstanceInspector)
{
(this as InstanceInspector).ConstructInstanceFilters(filterAreaObj);
}
}
private void AddFilterButton(GameObject parent, MemberTypes type, bool setEnabled = false)
{
var btnObj = UIFactory.CreateButton(parent, new Color(0.2f, 0.2f, 0.2f));
var btnLayout = btnObj.AddComponent<LayoutElement>();
btnLayout.minHeight = 25;
btnLayout.minWidth = 70;
var text = btnObj.GetComponentInChildren<Text>();
text.text = type.ToString();
var btn = btnObj.GetComponent<Button>();
btn.onClick.AddListener(() => { OnMemberFilterClicked(type, btn); });
var colors = btn.colors;
colors.highlightedColor = new Color(0.3f, 0.7f, 0.3f);
if (setEnabled)
{
colors.normalColor = new Color(0.2f, 0.6f, 0.2f);
m_memberFilter = type;
m_lastActiveMemButton = btn;
}
btn.colors = colors;
}
internal void ConstructUpdateRow()
{
var optionsRowObj = UIFactory.CreateHorizontalGroup(Content, new Color(1, 1, 1, 0));
var optionsLayout = optionsRowObj.AddComponent<LayoutElement>();
optionsLayout.minHeight = 25;
var optionsGroup = optionsRowObj.GetComponent<HorizontalLayoutGroup>();
optionsGroup.childForceExpandHeight = true;
optionsGroup.childForceExpandWidth = false;
optionsGroup.childAlignment = TextAnchor.MiddleLeft;
optionsGroup.spacing = 10;
m_updateRowObj = optionsRowObj;
// update button
var updateButtonObj = UIFactory.CreateButton(optionsRowObj, new Color(0.2f, 0.2f, 0.2f));
var updateBtnLayout = updateButtonObj.AddComponent<LayoutElement>();
updateBtnLayout.minWidth = 110;
updateBtnLayout.flexibleWidth = 0;
var updateText = updateButtonObj.GetComponentInChildren<Text>();
updateText.text = "Update Values";
var updateBtn = updateButtonObj.GetComponent<Button>();
updateBtn.onClick.AddListener(() =>
{
bool orig = m_autoUpdate;
m_autoUpdate = true;
Update();
if (!orig) m_autoUpdate = orig;
});
// auto update
var autoUpdateObj = UIFactory.CreateToggle(optionsRowObj, out Toggle autoUpdateToggle, out Text autoUpdateText);
var autoUpdateLayout = autoUpdateObj.AddComponent<LayoutElement>();
autoUpdateLayout.minWidth = 150;
autoUpdateLayout.minHeight = 25;
autoUpdateText.text = "Auto-update?";
autoUpdateToggle.isOn = false;
autoUpdateToggle.onValueChanged.AddListener((bool val) => { m_autoUpdate = val; });
}
internal void ConstructMemberList()
{
var scrollobj = UIFactory.CreateScrollView(Content, out m_scrollContent, out m_sliderScroller, new Color(0.05f, 0.05f, 0.05f));
m_memberListObj = scrollobj;
m_scrollContentRect = m_scrollContent.GetComponent<RectTransform>();
var scrollGroup = m_scrollContent.GetComponent<VerticalLayoutGroup>();
scrollGroup.spacing = 3;
scrollGroup.padding.left = 0;
scrollGroup.padding.right = 0;
scrollGroup.childForceExpandHeight = true;
m_pageHandler = new PageHandler(m_sliderScroller);
m_pageHandler.ConstructUI(Content);
m_pageHandler.OnPageChanged += OnPageTurned;
}
#endregion // end UI
#endregion // end instance
}
}

View File

@ -0,0 +1,41 @@
#if BIE5
using System;
using System.IO;
using System.Reflection;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
namespace UnityExplorer
{
[BepInPlugin(ExplorerCore.GUID, "UnityExplorer", ExplorerCore.VERSION)]
public class ExplorerBepInPlugin : BaseUnityPlugin, IExplorerLoader
{
public static ExplorerBepInPlugin Instance;
public static ManualLogSource Logging => Instance?.Logger;
public Harmony HarmonyInstance => s_harmony;
private static readonly Harmony s_harmony = new Harmony(ExplorerCore.GUID);
public string ExplorerFolder => Path.Combine(Paths.PluginPath, ExplorerCore.NAME);
public string ConfigFolder => Path.Combine(Paths.ConfigPath, ExplorerCore.NAME);
public Action<object> OnLogMessage => (object log) => { Logging?.LogMessage(log?.ToString() ?? ""); };
public Action<object> OnLogWarning => (object log) => { Logging?.LogWarning(log?.ToString() ?? ""); };
public Action<object> OnLogError => (object log) => { Logging?.LogError(log?.ToString() ?? ""); };
internal void Awake()
{
Instance = this;
new ExplorerCore();
}
internal void Update()
{
ExplorerCore.Update();
}
}
}
#endif

View File

@ -1,4 +1,4 @@
#if BIE
#if BIE6
using System;
using System.IO;
using System.Reflection;
@ -8,7 +8,7 @@ using HarmonyLib;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityExplorer.UI.Modules;
using UnityExplorer.UI.Main;
#if CPP
using UnhollowerRuntimeLib;
using BepInEx.IL2CPP;
@ -18,21 +18,27 @@ namespace UnityExplorer
{
#if MONO
[BepInPlugin(ExplorerCore.GUID, "UnityExplorer", ExplorerCore.VERSION)]
public class ExplorerBepInPlugin : BaseUnityPlugin
public class ExplorerBepInPlugin : BaseUnityPlugin, IExplorerLoader
{
public static ExplorerBepInPlugin Instance;
public static ManualLogSource Logging => Instance?.Logger;
public static readonly Harmony HarmonyInstance = new Harmony(ExplorerCore.GUID);
public Harmony HarmonyInstance => s_harmony;
private static readonly Harmony s_harmony = new Harmony(ExplorerCore.GUID);
public string ExplorerFolder => Path.Combine(Paths.PluginPath, ExplorerCore.NAME);
public string ConfigFolder => Path.Combine(Paths.ConfigPath, ExplorerCore.NAME);
public Action<object> OnLogMessage => (object log) => { Logging?.LogMessage(log?.ToString() ?? ""); };
public Action<object> OnLogWarning => (object log) => { Logging?.LogWarning(log?.ToString() ?? ""); };
public Action<object> OnLogError => (object log) => { Logging?.LogError(log?.ToString() ?? ""); };
internal void Awake()
{
Instance = this;
new ExplorerCore();
// HarmonyInstance.PatchAll();
}
internal void Update()
@ -44,13 +50,21 @@ namespace UnityExplorer
#if CPP
[BepInPlugin(ExplorerCore.GUID, "UnityExplorer", ExplorerCore.VERSION)]
public class ExplorerBepInPlugin : BasePlugin
public class ExplorerBepInPlugin : BasePlugin, IExplorerLoader
{
public static ExplorerBepInPlugin Instance;
public static ManualLogSource Logging => Instance?.Log;
public static readonly Harmony HarmonyInstance = new Harmony(ExplorerCore.GUID);
public Harmony HarmonyInstance => s_harmony;
private static readonly Harmony s_harmony = new Harmony(ExplorerCore.GUID);
public string ExplorerFolder => Path.Combine(Paths.PluginPath, ExplorerCore.NAME);
public string ConfigFolder => Path.Combine(Paths.ConfigPath, ExplorerCore.NAME);
public Action<object> OnLogMessage => (object log) => { Logging?.LogMessage(log?.ToString() ?? ""); };
public Action<object> OnLogWarning => (object log) => { Logging?.LogWarning(log?.ToString() ?? ""); };
public Action<object> OnLogError => (object log) => { Logging?.LogError(log?.ToString() ?? ""); };
// Init
public override void Load()
@ -67,8 +81,6 @@ namespace UnityExplorer
GameObject.DontDestroyOnLoad(obj);
new ExplorerCore();
// HarmonyInstance.PatchAll();
}
// BepInEx Il2Cpp mod class doesn't have monobehaviour methods yet, so wrap them in a dummy.

View File

@ -0,0 +1,43 @@
#if ML
using System;
using System.IO;
using MelonLoader;
using UnityExplorer;
[assembly: MelonInfo(typeof(ExplorerMelonMod), ExplorerCore.NAME, ExplorerCore.VERSION, ExplorerCore.AUTHOR)]
[assembly: MelonGame(null, null)]
namespace UnityExplorer
{
public class ExplorerMelonMod : MelonMod, IExplorerLoader
{
public static ExplorerMelonMod Instance;
public string ExplorerFolder => Path.Combine("Mods", ExplorerCore.NAME);
public string ConfigFolder => ExplorerFolder;
public Action<object> OnLogMessage => (object log) => { MelonLogger.Msg(log?.ToString() ?? ""); };
public Action<object> OnLogWarning => (object log) => { MelonLogger.Warning(log?.ToString() ?? ""); };
public Action<object> OnLogError => (object log) => { MelonLogger.Error(log?.ToString() ?? ""); };
public Harmony.HarmonyInstance HarmonyInstance => Instance.Harmony;
public override void OnApplicationStart()
{
Instance = this;
new ExplorerCore();
}
public override void OnUpdate()
{
ExplorerCore.Update();
}
//public override void OnSceneWasLoaded(int buildIndex, string sceneName)
//{
// ExplorerCore.Instance.OnSceneLoaded();
//}
}
}
#endif

View File

@ -0,0 +1,105 @@
#if STANDALONE
using HarmonyLib;
using System;
using System.IO;
using System.Reflection;
using UnityEngine;
#if CPP
using UnhollowerRuntimeLib;
#endif
namespace UnityExplorer
{
public class ExplorerStandalone : IExplorerLoader
{
/// <summary>
/// Call this to initialize UnityExplorer. Optionally, also subscribe to the 'OnLog' event to handle logging.
/// </summary>
/// <returns>The new (or active, if one exists) instance of ExplorerStandalone.</returns>
public static ExplorerStandalone CreateInstance()
{
if (Instance != null)
return Instance;
return new ExplorerStandalone();
}
private ExplorerStandalone()
{
Init();
}
public static ExplorerStandalone Instance { get; private set; }
/// <summary>
/// Invoked whenever Explorer logs something. Subscribe to this to handle logging.
/// </summary>
public static event Action<string, LogType> OnLog;
public Harmony HarmonyInstance => s_harmony;
public static readonly Harmony s_harmony = new Harmony(ExplorerCore.GUID);
public string ExplorerFolder
{
get
{
if (s_explorerFolder == null)
{
s_explorerFolder =
Path.Combine(
Path.GetDirectoryName(
Uri.UnescapeDataString(new Uri(Assembly.GetExecutingAssembly().CodeBase)
.AbsolutePath)),
"UnityExplorer");
if (!Directory.Exists(s_explorerFolder))
Directory.CreateDirectory(s_explorerFolder);
}
return s_explorerFolder;
}
}
private static string s_explorerFolder;
public string ConfigFolder => ExplorerFolder;
Action<object> IExplorerLoader.OnLogMessage => (object log) => { OnLog?.Invoke(log?.ToString() ?? "", LogType.Log); };
Action<object> IExplorerLoader.OnLogWarning => (object log) => { OnLog?.Invoke(log?.ToString() ?? "", LogType.Warning); };
Action<object> IExplorerLoader.OnLogError => (object log) => { OnLog?.Invoke(log?.ToString() ?? "", LogType.Error); };
private void Init()
{
Instance = this;
#if CPP
ClassInjector.RegisterTypeInIl2Cpp<ExplorerBehaviour>();
var obj = new GameObject(
"ExplorerBehaviour",
new Il2CppSystem.Type[] { Il2CppType.Of<ExplorerBehaviour>() }
);
#else
var obj = new GameObject(
"ExplorerBehaviour",
new Type[] { typeof(ExplorerBehaviour) }
);
#endif
obj.hideFlags = HideFlags.HideAndDontSave;
GameObject.DontDestroyOnLoad(obj);
new ExplorerCore();
}
public class ExplorerBehaviour : MonoBehaviour
{
#if CPP
public ExplorerBehaviour(IntPtr ptr) : base(ptr) { }
#endif
internal void Update()
{
ExplorerCore.Update();
}
}
}
}
#endif

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnityExplorer
{
public interface IExplorerLoader
{
string ExplorerFolder { get; }
string ConfigFolder { get; }
Action<object> OnLogMessage { get; }
Action<object> OnLogWarning { get; }
Action<object> OnLogError { get; }
#if ML
Harmony.HarmonyInstance HarmonyInstance { get; }
#else
HarmonyLib.Harmony HarmonyInstance { get; }
#endif
}
}

View File

@ -2,13 +2,6 @@
using System.Runtime.InteropServices;
using UnityExplorer;
#if ML
using MelonLoader;
[assembly: MelonInfo(typeof(ExplorerMelonMod), "UnityExplorer", ExplorerCore.VERSION, ExplorerCore.AUTHOR)]
[assembly: MelonGame(null, null)]
#endif
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

Binary file not shown.

View File

@ -1,284 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityExplorer.UI;
using UnityEngine;
using System;
using System.Runtime.InteropServices;
using System.Text;
using UnityExplorer.Unstrip;
#if CPP
using UnhollowerBaseLib;
using UnityExplorer.Helpers;
#endif
namespace UnityExplorer.Tests
{
public static class StaticTestClass
{
public static int StaticProperty => 5;
public static int StaticField = 69;
public static List<string> StaticList = new List<string>
{
"one",
"two",
"three",
};
public static void StaticMethod() { }
}
public class TestClass
{
public string AAALongString = @"1
2
3
4
5";
public Vector2 AATestVector2 = new Vector2(1, 2);
public Vector3 AATestVector3 = new Vector3(1, 2, 3);
public Vector4 AATestVector4 = new Vector4(1, 2, 3, 4);
public Rect AATestRect = new Rect(1, 2, 3, 4);
public Color AATestColor = new Color(0.1f, 0.2f, 0.3f, 0.4f);
public bool ATestBoolMethod() => false;
public bool this[int index]
{
get => index % 2 == 0;
set => m_thisBool = value;
}
internal bool m_thisBool;
static int testInt;
public static List<string> ExceptionList
{
get
{
testInt++;
if (testInt % 2 == 0)
throw new Exception("its even");
else
return new List<string> { "one" };
}
}
static bool abool;
public static bool ATestExceptionBool
{
get
{
abool = !abool;
if (!abool)
throw new Exception("false");
else
return true;
}
}
public static string ExceptionString => throw new NotImplementedException();
public static string ANullString = null;
public static float ATestFloat = 420.69f;
public static int ATestInt = -1;
public static string ATestString = "hello world";
public static uint ATestUInt = 1u;
public static byte ATestByte = 255;
public static ulong AReadonlyUlong = 82934UL;
public static TestClass Instance => m_instance ?? (m_instance = new TestClass());
private static TestClass m_instance;
public object AmbigObject;
public List<List<List<string>>> ANestedNestedList = new List<List<List<string>>>
{
new List<List<string>>
{
new List<string>
{
"one",
"two",
},
new List<string>
{
"three",
"four"
}
},
new List<List<string>>
{
new List<string>
{
"five",
"six"
}
}
};
public static bool SetOnlyProperty
{
set => m_setOnlyProperty = value;
}
private static bool m_setOnlyProperty;
public static bool ReadSetOnlyProperty => m_setOnlyProperty;
public Texture2D TestTexture;
public static Sprite TestSprite;
#if CPP
public static Il2CppSystem.Collections.Generic.HashSet<string> CppHashSetTest;
public static Il2CppSystem.Collections.Generic.List<string> CppStringTest;
public static Il2CppSystem.Collections.IList CppIList;
//public static Il2CppSystem.Collections.Generic.Dictionary<string, string> CppDictTest;
//public static Il2CppSystem.Collections.Generic.Dictionary<int, float> CppDictTest2;
#endif
public TestClass()
{
int a = 0;
foreach (var list in ANestedNestedList)
{
foreach (var list2 in list)
{
for (int i = 0; i < 33; i++)
list2.Add(a++.ToString());
}
}
#if CPP
TextureSpriteTest();
CppHashSetTest = new Il2CppSystem.Collections.Generic.HashSet<string>();
CppHashSetTest.Add("1");
CppHashSetTest.Add("2");
CppHashSetTest.Add("3");
CppStringTest = new Il2CppSystem.Collections.Generic.List<string>();
CppStringTest.Add("1");
CppStringTest.Add("2");
//CppDictTest = new Il2CppSystem.Collections.Generic.Dictionary<string, string>();
//CppDictTest.Add("key1", "value1");
//CppDictTest.Add("key2", "value2");
//CppDictTest.Add("key3", "value3");
//CppDictTest2 = new Il2CppSystem.Collections.Generic.Dictionary<int, float>();
//CppDictTest2.Add(0, 0.5f);
//CppDictTest2.Add(1, 0.5f);
//CppDictTest2.Add(2, 0.5f);
#endif
}
private void TextureSpriteTest()
{
TestTexture = new Texture2D(32, 32, TextureFormat.ARGB32, false)
{
name = "TestTexture"
};
TestSprite = ImageConversionUnstrip.CreateSprite(TestTexture);
GameObject.DontDestroyOnLoad(TestTexture);
GameObject.DontDestroyOnLoad(TestSprite);
// test loading a tex from file
if (System.IO.File.Exists(@"D:\Downloads\test.png"))
{
var dataToLoad = System.IO.File.ReadAllBytes(@"D:\Downloads\test.png");
ExplorerCore.Log($"Tex load success: {TestTexture.LoadImage(dataToLoad, false)}");
}
}
public static string TestRefInOutGeneric<T>(ref string arg0, in int arg1, out string arg2) where T : Component
{
arg2 = "this is arg2";
return $"T: '{typeof(T).FullName}', ref arg0: '{arg0}', in arg1: '{arg1}', out arg2: '{arg2}'";
}
// test a non-generic dictionary
public Hashtable TestNonGenericDict()
{
return new Hashtable
{
{ "One", 1 },
{ "Two", 2 },
{ "Three", 3 },
};
}
// test HashSets
public static HashSet<string> HashSetTest = new HashSet<string>
{
"One",
"Two",
"Three"
};
// Test indexed parameter
public string this[int arg0, string arg1]
{
get
{
return $"arg0: {arg0}, arg1: {arg1}";
}
}
// Test basic list
public static List<string> TestList = new List<string>
{
"1",
"2",
"3",
"etc..."
};
// Test a nested dictionary
public static Dictionary<int, Dictionary<string, int>> NestedDictionary = new Dictionary<int, Dictionary<string, int>>
{
{
1,
new Dictionary<string, int>
{
{
"Sub 1", 123
},
{
"Sub 2", 456
},
}
},
{
2,
new Dictionary<string, int>
{
{
"Sub 3", 789
},
{
"Sub 4", 000
},
}
},
};
// Test a basic method
public static Color TestMethod(float r, float g, float b, float a)
{
return new Color(r, g, b, a);
}
// A method with default arguments
public static Vector3 TestDefaultArgs(float arg0, float arg1, float arg2 = 5.0f)
{
return new Vector3(arg0, arg1, arg2);
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace UnityExplorer.UI.Main
{
public abstract class BaseMenuPage
{
public abstract string Name { get; }
public GameObject Content;
public Button RefNavbarButton { get; set; }
public bool Enabled
{
get => Content?.activeSelf ?? false;
set => Content?.SetActive(true);
}
public abstract bool Init();
public abstract void Update();
}
}

View File

@ -4,11 +4,12 @@ using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityExplorer.Helpers;
using UnityExplorer.Core.CSharp;
using UnityExplorer.Core.Unity;
using UnityExplorer.UI;
using UnityExplorer.UI.Modules;
using UnityExplorer.UI.Main;
namespace UnityExplorer.CSConsole
namespace UnityExplorer.UI.Main.CSConsole
{
public class AutoCompleter
{
@ -45,7 +46,7 @@ namespace UnityExplorer.CSConsole
return;
}
if (!CodeEditor.EnableAutocompletes)
if (!CSharpConsole.EnableAutocompletes)
{
if (m_mainObj.activeSelf)
{
@ -132,7 +133,7 @@ namespace UnityExplorer.CSConsole
{
try
{
var editor = CSConsolePage.Instance.m_codeEditor;
var editor = CSharpConsole.Instance;
if (!editor.InputField.isFocused)
return;
@ -164,7 +165,7 @@ namespace UnityExplorer.CSConsole
public static void CheckAutocomplete()
{
var m_codeEditor = CSConsolePage.Instance.m_codeEditor;
var m_codeEditor = CSharpConsole.Instance;
string input = m_codeEditor.InputField.text;
int caretIndex = m_codeEditor.InputField.caretPosition;
@ -192,9 +193,9 @@ namespace UnityExplorer.CSConsole
public static void ClearAutocompletes()
{
if (CodeEditor.AutoCompletes.Any())
if (CSharpConsole.AutoCompletes.Any())
{
CodeEditor.AutoCompletes.Clear();
CSharpConsole.AutoCompletes.Clear();
}
}
@ -203,8 +204,8 @@ namespace UnityExplorer.CSConsole
try
{
// Credit ManylMarco
CodeEditor.AutoCompletes.Clear();
string[] completions = CSConsolePage.Instance.m_evaluator.GetCompletions(input, out string prefix);
CSharpConsole.AutoCompletes.Clear();
string[] completions = CSharpConsole.Instance.Evaluator.GetCompletions(input, out string prefix);
if (completions != null)
{
if (prefix == null)
@ -212,7 +213,7 @@ namespace UnityExplorer.CSConsole
prefix = input;
}
CodeEditor.AutoCompletes.AddRange(completions
CSharpConsole.AutoCompletes.AddRange(completions
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => new Suggestion(x, prefix, Suggestion.Contexts.Other))
);
@ -231,7 +232,7 @@ namespace UnityExplorer.CSConsole
x.Substring(0, trimmed.Length),
Suggestion.Contexts.Namespace));
CodeEditor.AutoCompletes.AddRange(namespaces);
CSharpConsole.AutoCompletes.AddRange(namespaces);
IEnumerable<Suggestion> keywords = Suggestion.Keywords
.Where(x => x.StartsWith(trimmed) && x.Length > trimmed.Length)
@ -240,7 +241,7 @@ namespace UnityExplorer.CSConsole
x.Substring(0, trimmed.Length),
Suggestion.Contexts.Keyword));
CodeEditor.AutoCompletes.AddRange(keywords);
CSharpConsole.AutoCompletes.AddRange(keywords);
}
catch (Exception ex)
{
@ -268,8 +269,8 @@ namespace UnityExplorer.CSConsole
mainRect.offsetMax = Vector2.zero;
var mainGroup = content.GetComponent<VerticalLayoutGroup>();
mainGroup.childControlHeight = false;
mainGroup.childControlWidth = true;
mainGroup.SetChildControlHeight(false);
mainGroup.SetChildControlWidth(true);
mainGroup.childForceExpandHeight = false;
mainGroup.childForceExpandWidth = true;
@ -301,7 +302,7 @@ namespace UnityExplorer.CSConsole
void UseAutocompleteButton()
{
CSConsolePage.Instance.m_codeEditor.UseAutocomplete(hiddenText.text);
CSharpConsole.Instance.UseAutocomplete(hiddenText.text);
}
m_suggestionButtons.Add(buttonObj);

View File

@ -1,9 +1,9 @@
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityExplorer.CSConsole.Lexer;
using UnityExplorer.UI.Main.CSConsole.Lexer;
namespace UnityExplorer.CSConsole
namespace UnityExplorer.UI.Main.CSConsole
{
public struct LexerMatchInfo
{
@ -18,7 +18,7 @@ namespace UnityExplorer.CSConsole
End,
};
public class CSharpLexer
public class CSLexerHighlighter
{
private string inputString;
private readonly Matcher[] matchers;
@ -53,20 +53,15 @@ namespace UnityExplorer.CSConsole
"else", "equals", "false", "finally", "float", "for", "foreach", "from", "global", "goto", "group",
"if", "in", "int", "into", "is", "join", "let", "lock", "long", "new", "null", "object", "on", "orderby", "out",
"ref", "remove", "return", "sbyte", "select", "short", "sizeof", "stackalloc", "string",
"switch", "throw", "true", "try", "typeof", "uint", "ulong", "ushort", "var", "where", "while", "yield" }
};
public static KeywordMatch invalidKeywordMatcher = new KeywordMatch()
{
highlightColor = new Color(0.95f, 0.10f, 0.10f, 1.0f),
Keywords = new[] { "abstract", "async", "base", "class", "delegate", "enum", "explicit", "extern", "fixed", "get",
"implicit", "interface", "internal", "namespace", "operator", "override", "params", "private", "protected", "public",
"using", "partial", "readonly", "sealed", "set", "static", "struct", "this", "unchecked", "unsafe", "value", "virtual", "volatile", "void" }
"switch", "throw", "true", "try", "typeof", "uint", "ulong", "ushort", "var", "where", "while", "yield",
"abstract", "async", "base", "class", "delegate", "enum", "explicit", "extern", "fixed", "get",
"implicit", "interface", "internal", "namespace", "operator", "override", "params", "private", "protected", "public",
"using", "partial", "readonly", "sealed", "set", "static", "struct", "this", "unchecked", "unsafe", "value", "virtual", "volatile", "void"}
};
// ~~~~~~~ ctor ~~~~~~~
public CSharpLexer()
public CSLexerHighlighter()
{
startDelimiters = new HashSet<char>(delimiters);
endDelimiters = new HashSet<char>(delimiters);
@ -78,7 +73,6 @@ namespace UnityExplorer.CSConsole
numberMatcher,
stringMatcher,
validKeywordMatcher,
invalidKeywordMatcher,
};
foreach (Matcher lexer in matchers)

View File

@ -1,24 +1,153 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UnityExplorer.Input;
using UnityExplorer.CSConsole.Lexer;
using UnityExplorer.Core.CSharp;
using System.Linq;
using UnityExplorer.Core.Input;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityExplorer.UI;
using UnityExplorer.UI.Modules;
using System.Collections.Generic;
using System.Reflection;
using UnityExplorer.UI.Shared;
using UnityExplorer.Helpers;
using UnityExplorer.UI.Reusable;
using UnityExplorer.UI.Main.CSConsole;
using UnityExplorer.Core;
using UnityExplorer.Core.Unity;
#if CPP
using UnityExplorer.Core.Runtime.Il2Cpp;
#endif
namespace UnityExplorer.CSConsole
namespace UnityExplorer.UI.Main.CSConsole
{
// Handles most of the UI side of the C# console, including syntax highlighting.
public class CodeEditor
public class CSharpConsole : BaseMenuPage
{
public override string Name => "C# Console";
public static CSharpConsole Instance { get; private set; }
public ScriptEvaluator Evaluator;
internal StringBuilder m_evalLogBuilder;
public static List<string> UsingDirectives;
public static readonly string[] DefaultUsing = new string[]
{
"System",
"System.Linq",
"System.Collections",
"System.Collections.Generic",
"System.Reflection",
"UnityEngine",
#if CPP
"UnhollowerBaseLib",
"UnhollowerRuntimeLib",
#endif
};
public override bool Init()
{
Instance = this;
try
{
InitConsole();
AutoCompleter.Init();
#if MONO
DummyBehaviour.Setup();
#endif
ResetConsole(false);
// Make sure compiler is supported on this platform
Evaluator.Compile("");
return true;
}
catch (Exception e)
{
string info = "The C# Console has been disabled because";
if (e is NotSupportedException && e.TargetSite?.Name == "DefineDynamicAssembly")
info += " Reflection.Emit is not supported.";
else
info += $" of an unknown error.\r\n({e.ReflectionExToString()})";
ExplorerCore.LogWarning(info);
return false;
}
}
public void ResetConsole(bool log = true)
{
if (Evaluator != null)
Evaluator.Dispose();
m_evalLogBuilder = new StringBuilder();
Evaluator = new ScriptEvaluator(new StringWriter(m_evalLogBuilder)) { InteractiveBaseClass = typeof(ScriptInteraction) };
UsingDirectives = new List<string>();
foreach (string use in DefaultUsing)
AddUsing(use);
if (log)
ExplorerCore.Log($"C# Console reset. Using directives:\r\n{Evaluator.GetUsing()}");
}
public override void Update()
{
UpdateConsole();
AutoCompleter.Update();
#if CPP
Il2CppCoroutine.Process();
#endif
}
public void AddUsing(string asm)
{
if (!UsingDirectives.Contains(asm))
{
Evaluate($"using {asm};", true);
UsingDirectives.Add(asm);
}
}
public void Evaluate(string code, bool supressLog = false)
{
try
{
Evaluator.Run(code);
string output = ScriptEvaluator._textWriter.ToString();
var outputSplit = output.Split('\n');
if (outputSplit.Length >= 2)
output = outputSplit[outputSplit.Length - 2];
m_evalLogBuilder.Clear();
if (ScriptEvaluator._reportPrinter.ErrorsCount > 0)
throw new FormatException($"Unable to compile the code. Evaluator's last output was:\r\n{output}");
if (!supressLog)
ExplorerCore.Log("Code executed successfully.");
}
catch (FormatException fex)
{
if (!supressLog)
ExplorerCore.LogWarning(fex.Message);
}
catch (Exception ex)
{
if (!supressLog)
ExplorerCore.LogWarning(ex);
}
}
// =================================================================================================
// UI stuff
public InputField InputField { get; internal set; }
public Text InputText { get; internal set; }
public int CurrentIndent { get; private set; }
@ -31,8 +160,7 @@ namespace UnityExplorer.CSConsole
public string HighlightedText => inputHighlightText.text;
private Text inputHighlightText;
private readonly CSharpLexer highlightLexer;
private readonly StringBuilder sbHighlight;
private CSLexerHighlighter highlightLexer;
internal int m_lastCaretPos;
internal int m_fixCaretPos;
@ -51,6 +179,8 @@ The following helper methods are available:
* <color=#add490>Log(""message"")</color> logs a message to the debug console
* <color=#add490>StartCoroutine(IEnumerator routine)</color> start the IEnumerator as a UnityEngine.Coroutine
* <color=#add490>CurrentTarget()</color> returns the currently inspected target on the Home page
* <color=#add490>AllTargets()</color> returns an object[] array containing all inspected instances
@ -66,18 +196,33 @@ The following helper methods are available:
* <color=#add490>Reset()</color> resets all using directives and variables
";
public CodeEditor()
public void InitConsole()
{
sbHighlight = new StringBuilder();
highlightLexer = new CSharpLexer();
highlightLexer = new CSLexerHighlighter();
ConstructUI();
InputField.onValueChanged.AddListener((string s) => { OnInputChanged(s); });
}
public void Update()
internal static bool IsUserCopyPasting()
{
return (InputManager.GetKey(KeyCode.LeftControl) || InputManager.GetKey(KeyCode.RightControl))
&& InputManager.GetKeyDown(KeyCode.V);
}
public void UpdateConsole()
{
if (s_copyPasteBuffer != null)
{
if (!IsUserCopyPasting())
{
OnInputChanged(s_copyPasteBuffer);
s_copyPasteBuffer = null;
}
}
if (EnableCtrlRShortcut)
{
if ((InputManager.GetKey(KeyCode.LeftControl) || InputManager.GetKey(KeyCode.RightControl))
@ -86,7 +231,7 @@ The following helper methods are available:
var text = InputField.text.Trim();
if (!string.IsNullOrEmpty(text))
{
CSConsolePage.Instance.Evaluate(text);
Evaluate(text);
return;
}
}
@ -106,7 +251,7 @@ The following helper methods are available:
if (!m_fixwanted)
{
EventSystem.current.SetSelectedGameObject(InputField.gameObject, null);
m_fixwanted = true;
m_fixwanted = true;
}
else
{
@ -149,18 +294,27 @@ The following helper methods are available:
AutoCompleter.ClearAutocompletes();
}
public void OnInputChanged(string newInput, bool forceUpdate = false)
{
string newText = newInput;
internal static string s_copyPasteBuffer;
UpdateIndent(newInput);
public void OnInputChanged(string newText, bool forceUpdate = false)
{
if (IsUserCopyPasting())
{
//Console.WriteLine("Copy+Paste detected!");
s_copyPasteBuffer = newText;
return;
}
if (EnableAutoIndent)
UpdateIndent(newText);
if (!forceUpdate && string.IsNullOrEmpty(newText))
inputHighlightText.text = string.Empty;
else
inputHighlightText.text = SyntaxHighlightContent(newText);
UpdateAutocompletes();
if (EnableAutocompletes)
UpdateAutocompletes();
}
private void UpdateIndent(string newText)
@ -187,9 +341,9 @@ The following helper methods are available:
if (character == '"')
stringState = !stringState;
else if (!stringState && character == CSharpLexer.indentOpen)
else if (!stringState && character == CSLexerHighlighter.indentOpen)
CurrentIndent++;
else if (!stringState && character == CSharpLexer.indentClose)
else if (!stringState && character == CSLexerHighlighter.indentClose)
CurrentIndent--;
}
@ -203,35 +357,29 @@ The following helper methods are available:
{
int offset = 0;
sbHighlight.Length = 0;
//Console.WriteLine("Highlighting input text:\r\n" + inputText);
string ret = "";
foreach (LexerMatchInfo match in highlightLexer.GetMatches(inputText))
{
for (int i = offset; i < match.startIndex; i++)
{
sbHighlight.Append(inputText[i]);
}
ret += inputText[i];
sbHighlight.Append($"{match.htmlColor}");
ret += $"{match.htmlColor}";
for (int i = match.startIndex; i < match.endIndex; i++)
{
sbHighlight.Append(inputText[i]);
}
ret += inputText[i];
sbHighlight.Append(CLOSE_COLOR_TAG);
ret += CLOSE_COLOR_TAG;
offset = match.endIndex;
}
for (int i = offset; i < inputText.Length; i++)
{
sbHighlight.Append(inputText[i]);
}
ret += inputText[i];
inputText = sbHighlight.ToString();
return inputText;
return ret;
}
private void AutoIndentCaret()
@ -262,8 +410,8 @@ The following helper methods are available:
}
// check if should add auto-close }
int numOpen = InputField.text.Where(x => x == CSharpLexer.indentOpen).Count();
int numClose = InputField.text.Where(x => x == CSharpLexer.indentClose).Count();
int numOpen = InputField.text.Where(x => x == CSLexerHighlighter.indentOpen).Count();
int numClose = InputField.text.Where(x => x == CSLexerHighlighter.indentClose).Count();
if (numOpen > numClose)
{
@ -308,23 +456,23 @@ The following helper methods are available:
public void ConstructUI()
{
CSConsolePage.Instance.Content = UIFactory.CreateUIObject("C# Console", MainMenu.Instance.PageViewport);
Content = UIFactory.CreateUIObject("C# Console", MainMenu.Instance.PageViewport);
var mainLayout = CSConsolePage.Instance.Content.AddComponent<LayoutElement>();
var mainLayout = Content.AddComponent<LayoutElement>();
mainLayout.preferredHeight = 500;
mainLayout.flexibleHeight = 9000;
var mainGroup = CSConsolePage.Instance.Content.AddComponent<VerticalLayoutGroup>();
mainGroup.childControlHeight = true;
mainGroup.childControlWidth = true;
var mainGroup = Content.AddComponent<VerticalLayoutGroup>();
mainGroup.SetChildControlHeight(true);
mainGroup.SetChildControlWidth(true);
mainGroup.childForceExpandHeight = true;
mainGroup.childForceExpandWidth = true;
#region TOP BAR
#region TOP BAR
// Main group object
var topBarObj = UIFactory.CreateHorizontalGroup(CSConsolePage.Instance.Content);
var topBarObj = UIFactory.CreateHorizontalGroup(Content);
LayoutElement topBarLayout = topBarObj.AddComponent<LayoutElement>();
topBarLayout.minHeight = 50;
topBarLayout.flexibleHeight = 0;
@ -337,8 +485,8 @@ The following helper methods are available:
topBarGroup.spacing = 10;
topBarGroup.childForceExpandHeight = true;
topBarGroup.childForceExpandWidth = true;
topBarGroup.childControlWidth = true;
topBarGroup.childControlHeight = true;
topBarGroup.SetChildControlWidth(true);
topBarGroup.SetChildControlHeight(true);
topBarGroup.childAlignment = TextAnchor.LowerCenter;
var topBarLabel = UIFactory.CreateLabel(topBarObj, TextAnchor.MiddleLeft);
@ -396,13 +544,13 @@ The following helper methods are available:
autoIndentLayout.flexibleWidth = 0;
autoIndentLayout.minHeight = 25;
#endregion
#endregion
#region CONSOLE INPUT
#region CONSOLE INPUT
int fontSize = 16;
var inputObj = UIFactory.CreateSrollInputField(CSConsolePage.Instance.Content, out InputFieldScroller consoleScroll, fontSize);
var inputObj = UIFactory.CreateSrollInputField(Content, out InputFieldScroller consoleScroll, fontSize);
var inputField = consoleScroll.inputField;
@ -429,9 +577,38 @@ The following helper methods are available:
#endregion
#region COMPILE BUTTON
#region COMPILE BUTTON BAR
var compileBtnObj = UIFactory.CreateButton(CSConsolePage.Instance.Content);
var horozGroupObj = UIFactory.CreateHorizontalGroup(Content, new Color(1, 1, 1, 0));
var horozGroup = horozGroupObj.GetComponent<HorizontalLayoutGroup>();
horozGroup.padding.left = 2;
horozGroup.padding.top = 2;
horozGroup.padding.right = 2;
horozGroup.padding.bottom = 2;
var resetBtnObj = UIFactory.CreateButton(horozGroupObj);
var resetBtnLayout = resetBtnObj.AddComponent<LayoutElement>();
resetBtnLayout.preferredWidth = 80;
resetBtnLayout.flexibleWidth = 0;
resetBtnLayout.minHeight = 45;
resetBtnLayout.flexibleHeight = 0;
var resetButton = resetBtnObj.GetComponent<Button>();
var resetBtnColors = resetButton.colors;
resetBtnColors.normalColor = "666666".ToColor();
resetButton.colors = resetBtnColors;
var resetBtnText = resetBtnObj.GetComponentInChildren<Text>();
resetBtnText.text = "Reset";
resetBtnText.fontSize = 18;
resetBtnText.color = Color.white;
// Set compile button callback now that we have the Input Field reference
resetButton.onClick.AddListener(ResetCallback);
void ResetCallback()
{
ResetConsole();
}
var compileBtnObj = UIFactory.CreateButton(horozGroupObj);
var compileBtnLayout = compileBtnObj.AddComponent<LayoutElement>();
compileBtnLayout.preferredWidth = 80;
compileBtnLayout.flexibleWidth = 0;
@ -452,7 +629,7 @@ The following helper methods are available:
{
if (!string.IsNullOrEmpty(inputField.text))
{
CSConsolePage.Instance.Evaluate(inputField.text.Trim());
Evaluate(inputField.text.Trim());
}
}
@ -477,5 +654,15 @@ The following helper methods are available:
this.InputText = mainTextInput;
this.inputHighlightText = highlightTextInput;
}
// ================================================================================================
private class VoidType
{
public static readonly VoidType Value = new VoidType();
private VoidType() { }
}
}
}

View File

@ -1,7 +1,7 @@
using System.Collections.Generic;
using UnityEngine;
namespace UnityExplorer.CSConsole.Lexer
namespace UnityExplorer.UI.Main.CSConsole.Lexer
{
public class CommentMatch : Matcher
{
@ -12,9 +12,9 @@ namespace UnityExplorer.CSConsole.Lexer
public override Color HighlightColor => new Color(0.34f, 0.65f, 0.29f, 1.0f);
public override IEnumerable<char> StartChars => new char[] { lineCommentStart[0], blockCommentStart[0] };
public override IEnumerable<char> EndChars => new char[] { blockCommentEnd[0] };
public override bool IsImplicitMatch(CSharpLexer lexer) => IsMatch(lexer, lineCommentStart) || IsMatch(lexer, blockCommentStart);
public override bool IsImplicitMatch(CSLexerHighlighter lexer) => IsMatch(lexer, lineCommentStart) || IsMatch(lexer, blockCommentStart);
private bool IsMatch(CSharpLexer lexer, string commentType)
private bool IsMatch(CSLexerHighlighter lexer, string commentType)
{
if (!string.IsNullOrEmpty(commentType))
{
@ -41,6 +41,6 @@ namespace UnityExplorer.CSConsole.Lexer
return false;
}
private bool IsEndLineOrEndFile(CSharpLexer lexer, char character) => lexer.EndOfStream || character == '\n' || character == '\r';
private bool IsEndLineOrEndFile(CSLexerHighlighter lexer, char character) => lexer.EndOfStream || character == '\n' || character == '\r';
}
}

View File

@ -1,7 +1,7 @@
using System.Collections.Generic;
using UnityEngine;
namespace UnityExplorer.CSConsole.Lexer
namespace UnityExplorer.UI.Main.CSConsole.Lexer
{
// I use two different KeywordMatch instances (valid and invalid).
// This class just contains common implementations.
@ -15,7 +15,7 @@ namespace UnityExplorer.CSConsole.Lexer
private readonly HashSet<string> shortlist = new HashSet<string>();
private readonly Stack<string> removeList = new Stack<string>();
public override bool IsImplicitMatch(CSharpLexer lexer)
public override bool IsImplicitMatch(CSLexerHighlighter lexer)
{
if (!char.IsWhiteSpace(lexer.Previous) &&
!lexer.IsSpecialSymbol(lexer.Previous, DelimiterType.End))

View File

@ -1,9 +1,9 @@
using System.Collections.Generic;
using UnityExplorer.Unstrip;
using UnityEngine;
using System.Linq;
using UnityExplorer.Core.Unity;
namespace UnityExplorer.CSConsole.Lexer
namespace UnityExplorer.UI.Main.CSConsole.Lexer
{
public abstract class Matcher
{
@ -15,9 +15,9 @@ namespace UnityExplorer.CSConsole.Lexer
public virtual IEnumerable<char> StartChars => Enumerable.Empty<char>();
public virtual IEnumerable<char> EndChars => Enumerable.Empty<char>();
public abstract bool IsImplicitMatch(CSharpLexer lexer);
public abstract bool IsImplicitMatch(CSLexerHighlighter lexer);
public bool IsMatch(CSharpLexer lexer)
public bool IsMatch(CSLexerHighlighter lexer)
{
if (IsImplicitMatch(lexer))
{

View File

@ -1,12 +1,12 @@
using UnityEngine;
namespace UnityExplorer.CSConsole.Lexer
namespace UnityExplorer.UI.Main.CSConsole.Lexer
{
public class NumberMatch : Matcher
{
public override Color HighlightColor => new Color(0.58f, 0.33f, 0.33f, 1.0f);
public override bool IsImplicitMatch(CSharpLexer lexer)
public override bool IsImplicitMatch(CSLexerHighlighter lexer)
{
if (!char.IsWhiteSpace(lexer.Previous) &&
!lexer.IsSpecialSymbol(lexer.Previous, DelimiterType.End))

View File

@ -1,7 +1,7 @@
using System.Collections.Generic;
using UnityEngine;
namespace UnityExplorer.CSConsole.Lexer
namespace UnityExplorer.UI.Main.CSConsole.Lexer
{
public class StringMatch : Matcher
{
@ -10,7 +10,7 @@ namespace UnityExplorer.CSConsole.Lexer
public override IEnumerable<char> StartChars => new[] { '"' };
public override IEnumerable<char> EndChars => new[] { '"' };
public override bool IsImplicitMatch(CSharpLexer lexer)
public override bool IsImplicitMatch(CSLexerHighlighter lexer)
{
if (lexer.ReadNext() == '"')
{
@ -21,6 +21,6 @@ namespace UnityExplorer.CSConsole.Lexer
return false;
}
private bool IsClosingQuoteOrEndFile(CSharpLexer lexer, char character) => lexer.EndOfStream || character == '"';
private bool IsClosingQuoteOrEndFile(CSLexerHighlighter lexer, char character) => lexer.EndOfStream || character == '"';
}
}

View File

@ -2,7 +2,7 @@
using System.Linq;
using UnityEngine;
namespace UnityExplorer.CSConsole.Lexer
namespace UnityExplorer.UI.Main.CSConsole.Lexer
{
public class SymbolMatch : Matcher
{
@ -21,7 +21,7 @@ namespace UnityExplorer.CSConsole.Lexer
public override IEnumerable<char> StartChars => symbols.Select(s => s[0]);
public override IEnumerable<char> EndChars => symbols.Select(s => s[0]);
public override bool IsImplicitMatch(CSharpLexer lexer)
public override bool IsImplicitMatch(CSLexerHighlighter lexer)
{
if (lexer == null)
return false;

Some files were not shown because too many files have changed in this diff Show More