mirror of
https://github.com/sinai-dev/UnityExplorer.git
synced 2025-06-23 00:52:31 +08:00
Compare commits
535 Commits
Author | SHA1 | Date | |
---|---|---|---|
3b71b40843 | |||
1292affe6d | |||
6614762fe8 | |||
d81d6d034b | |||
5dfe3bbf0c | |||
dc81451ce5 | |||
d7ab0a23c6 | |||
1a01c740e2 | |||
040fb1f11a | |||
e44ff9e207 | |||
b5c69fc1ea | |||
4fdb2aacd8 | |||
48e688cb75 | |||
647b0d353d | |||
2b715f3dbe | |||
938a991594 | |||
f00134b283 | |||
3b6b9768fb | |||
5fbfa1b7aa | |||
7d26965c12 | |||
862523399a | |||
0afccadc64 | |||
0e37e8030c | |||
621a9cd72e | |||
56be5414f9 | |||
b8c4be473f | |||
b6966f8836 | |||
ad8c5293a0 | |||
a7165c849c | |||
79f2514109 | |||
4e76eca73a | |||
2f0876466c | |||
fdefc3d567 | |||
64193ff1b0 | |||
a90292f47f | |||
d0bccae50c | |||
bdf08f014f | |||
df8522963e | |||
f6d0acab7b | |||
d4fbc89158 | |||
9e49f09a79 | |||
b9a3ab7439 | |||
03661cdd0b | |||
10f2b7e849 | |||
4602f07c34 | |||
18bcfed434 | |||
c7d2ce6d36 | |||
f961add7f4 | |||
798b881dcb | |||
c90f339882 | |||
c351ce5a6d | |||
9985ed0fd8 | |||
f35232bb64 | |||
49cc1f7df3 | |||
9f78c50854 | |||
bc64a04339 | |||
7d961ce8ad | |||
c7d7569f71 | |||
ee8f33a754 | |||
a95d91c824 | |||
177b78f4e7 | |||
3804d0aab0 | |||
97a82c1661 | |||
96a1cc69fb | |||
589abe6193 | |||
91bb58b020 | |||
d67507ead2 | |||
d730fbe49c | |||
9e0784ce54 | |||
67c602b32f | |||
8fb7d87ca6 | |||
c740c3c54d | |||
ea7b91f7fd | |||
c79223f537 | |||
aae248bf69 | |||
a73e992a0c | |||
3984550bb6 | |||
7928363aeb | |||
12758606fa | |||
c927ac54be | |||
9f1df11940 | |||
62354b6aa2 | |||
44e57c32c3 | |||
274352d665 | |||
7b477a8b0e | |||
e585fc6da0 | |||
0dd19345ed | |||
0050cff185 | |||
5f1d635eb3 | |||
e0f7fad00e | |||
f92c215a88 | |||
d58a5df82c | |||
12dd85ecfd | |||
03fb165967 | |||
834f4b7c4c | |||
3415eb8e77 | |||
6c1a5b8ae2 | |||
3334549902 | |||
077a2b434a | |||
8123ec2412 | |||
3f31db8dd8 | |||
9c1d459655 | |||
2cb510a82e | |||
6aa9b3aa15 | |||
587842f46b | |||
b9c641f170 | |||
1e68529430 | |||
e84e96a63c | |||
ec8c88ab9b | |||
0eae78eeb2 | |||
a07ead2142 | |||
b93567c7ea | |||
957d80c7ec | |||
d530d10798 | |||
66daabf770 | |||
9fe998aa22 | |||
28b6db80f9 | |||
22effbb399 | |||
50f0c31e98 | |||
911522457e | |||
d5d1841109 | |||
239534e09c | |||
bc5d16051f | |||
f81822f219 | |||
f159cf5ea7 | |||
1e6bacb32b | |||
a80cef4c1d | |||
450bb77f2e | |||
0479102db6 | |||
93181f02be | |||
371054d6df | |||
427f23b80a | |||
a0d5ab8792 | |||
297034e38b | |||
57f59d1295 | |||
fbdb84eefa | |||
6989ea1b19 | |||
fcdfeb2dec | |||
a1d0b6432e | |||
0b84405e57 | |||
c31e0949d3 | |||
5f0495a7ea | |||
28de6779d8 | |||
fae85c2968 | |||
fc8fa9aa7a | |||
bcf9a801a9 | |||
20298aa47b | |||
e2c1c186c3 | |||
9ce6508828 | |||
506e75c5fe | |||
a2f22051f0 | |||
4e3203a91b | |||
a411ce2dba | |||
48132b3d46 | |||
e49ed3028f | |||
31dd54d25c | |||
3cfdd6fa43 | |||
1fa1283a68 | |||
afa4135b67 | |||
48d1cf574d | |||
df0abbc847 | |||
5c9dcb1d43 | |||
602770d980 | |||
f26371f95f | |||
a673c39f4a | |||
40583cae3d | |||
20018a9ba9 | |||
dabf92a1a5 | |||
b7e275f02c | |||
f393e0d706 | |||
ab8acc9e84 | |||
66c30ee70e | |||
ddd271c00d | |||
30fe9e4dde | |||
fa3a436037 | |||
ca27d2b20f | |||
4315e0c547 | |||
3e19e74329 | |||
5a3ffebadc | |||
6e6b6239d8 | |||
03c8e5a8bd | |||
44f7209843 | |||
734e45cf9f | |||
97838e0b3a | |||
304b47f898 | |||
3d1fcbcd9f | |||
36fc17aa43 | |||
adfa29e63c | |||
3ffdcea73b | |||
dfd55260a8 | |||
29c78dc5a6 | |||
bf59d9d6cd | |||
bb0c59534a | |||
802bb722bc | |||
9ca992b0d7 | |||
5f3b3a6870 | |||
f5bce439cb | |||
e2b2c9038a | |||
fbefccd6b7 | |||
271c91f0d0 | |||
eb221bd868 | |||
5b516eb4cc | |||
601567f9d2 | |||
7ff508b874 | |||
09a7cd35cf | |||
db4a338d26 | |||
c08e02057c | |||
362fcdc51a | |||
73bd172e4d | |||
454d3bd0b4 | |||
f815a13d9a | |||
65c4d49274 | |||
d99137526e | |||
92447b55cd | |||
87d5d5a2de | |||
08cff3386b | |||
6033200579 | |||
94ec1c4908 | |||
7a400e762c | |||
67f9f744bb | |||
7a59f9a2a1 | |||
9b42eef1b9 | |||
830000b019 | |||
34910ab273 | |||
86b036095e | |||
b57e5be2e6 | |||
2d8ae45814 | |||
66dc262a68 | |||
4342901206 | |||
58b7c72a5c | |||
623dc7b7be | |||
e6f4939cc9 | |||
7a539ba78b | |||
0d10f94eb5 | |||
91671bf243 | |||
a72877befb | |||
16335c1bc4 | |||
8fab9e6268 | |||
fdd9039cca | |||
dcca980635 | |||
bfcab8248e | |||
97c20144f1 | |||
aaab10a0a0 | |||
b42a8dbe6a | |||
d7008db22e | |||
8c1913fe80 | |||
8d8c9ac7c9 | |||
f35beeaf58 | |||
d150ff3455 | |||
c4fa0d6bcd | |||
a5f56cf5a3 | |||
8c822b2ee9 | |||
4681b7e192 | |||
97093733d8 | |||
615f77979f | |||
ba3cf970d9 | |||
b2fb571b18 | |||
67ce6f946a | |||
1b82ccb49f | |||
480eb5afd5 | |||
88ea2a09c9 | |||
a678aa4d78 | |||
eaf478e314 | |||
d391968b32 | |||
70349ad7c7 | |||
78f2d1070f | |||
51307563ab | |||
185d1aaa0f | |||
3d6e8fcbf8 | |||
1daf4fade4 | |||
d92fb3f83f | |||
fe24b68fe2 | |||
6bf92b9a96 | |||
9f1cab019d | |||
a131404ac7 | |||
773900d749 | |||
342fc6bdb8 | |||
e85ea6ac3a | |||
af889e64cb | |||
0274022ce4 | |||
211576e0f8 | |||
3e42d7479f | |||
df4dea20c1 | |||
ece0c43067 | |||
6311c8d09a | |||
04739d0be8 | |||
a46acba265 | |||
5515b2eae4 | |||
9992029e28 | |||
14105785f0 | |||
365269b0dd | |||
0b973393d1 | |||
701d4431ae | |||
bfa73bcb55 | |||
b0bbeb3cf8 | |||
1a26623080 | |||
041f2938f7 | |||
9e7bb1a625 | |||
36f23b7cdc | |||
b51b743df4 | |||
805aff07cc | |||
bcdaf3b97e | |||
cb8e947fdf | |||
c8899be3ae | |||
cd5c69c965 | |||
5427312f18 | |||
eb7e80d910 | |||
a54888ae3a | |||
4f0553d293 | |||
9f0f7f9b57 | |||
383c6f19e8 | |||
428fab28f9 | |||
760b2981ad | |||
eee7d6bcc4 | |||
e270f205a1 | |||
084aee617c | |||
d0e508727a | |||
a9a53ba924 | |||
3cd9819790 | |||
5abfa3da67 | |||
e5d2d29a47 | |||
6a47e542e5 | |||
f1b83e7c9e | |||
44c6503ae2 | |||
6970dcbbc7 | |||
ac9c2d5286 | |||
496a5de55e | |||
b062924af7 | |||
5aef8ddc99 | |||
c134c1752e | |||
e4615aff84 | |||
8c5640dd12 | |||
76f71d9f3d | |||
82e9c08ae6 | |||
019e589947 | |||
d7b0fff949 | |||
7dbf694642 | |||
2fc9657560 | |||
fb6e413153 | |||
ca65affb5c | |||
f4e473f8e6 | |||
8c5e7678a6 | |||
32ad61baea | |||
df330420a3 | |||
5af9d3104d | |||
6977f1a31c | |||
26fb53f183 | |||
cccd02255f | |||
83f15c7168 | |||
bf8f838f01 | |||
a915e1028f | |||
8b1379f17e | |||
0c7d8f8435 | |||
72c3af3dd7 | |||
54f78ac10b | |||
2a9c4972dd | |||
e93edc5b19 | |||
c25abfe3ff | |||
8c3603baa0 | |||
021db69409 | |||
1c216c0d86 | |||
12fe19ba8e | |||
89022db5fc | |||
ccd08c3a63 | |||
843d7ed451 | |||
3e44317861 | |||
70d66f93a5 | |||
275225a284 | |||
b61020fe67 | |||
ada239c828 | |||
fedecb80a0 | |||
97738b00c1 | |||
59cbeec103 | |||
a9f6ed8729 | |||
7241247d05 | |||
ec215a0006 | |||
6e9bb83099 | |||
712bf7b669 | |||
b4b96134c4 | |||
d3b942065d | |||
9ea50e232c | |||
4128f8519d | |||
53e1e6bf22 | |||
b67ac145d4 | |||
586c63b668 | |||
65323e3b16 | |||
cfeb5ba018 | |||
8a15c11289 | |||
4019af5936 | |||
34c8ad3646 | |||
617d68f7e9 | |||
2efce9eb0e | |||
18d2518231 | |||
cef4c2f3fb | |||
1d24af5666 | |||
4f50afdddc | |||
caad39bb9a | |||
06122fe8c9 | |||
e6b253fed9 | |||
7b700cbe55 | |||
c04a864b74 | |||
c828d9b642 | |||
26052621e5 | |||
d101e7e35c | |||
57aace26d3 | |||
3d94b51d40 | |||
d34aeb81b3 | |||
d8f532d913 | |||
4931117b1e | |||
1f996f52fe | |||
00c28f781a | |||
f080379e8a | |||
2977fd4df5 | |||
56875e0641 | |||
8534c08f49 | |||
1ee10c2507 | |||
9e8a18a5e1 | |||
6c7acf7690 | |||
e70a1e96da | |||
22435176bf | |||
e4ff86259b | |||
961ff80c6d | |||
a89d66cf81 | |||
302ff29e36 | |||
8d9d8f76c2 | |||
3dc458ab1b | |||
f5c0b339ae | |||
ad61ff243a | |||
bfaba56b76 | |||
1c5306b7c8 | |||
15ec64b106 | |||
ab8b736f7e | |||
ea1e183c4a | |||
d6cde68a44 | |||
d76bc1f812 | |||
74ff1d8f01 | |||
2378925a8b | |||
8080129d58 | |||
4b8298fd2e | |||
ad055b4383 | |||
23483a6108 | |||
0bc14b2f76 | |||
dba9bdbdc2 | |||
a2a2b09d33 | |||
324d3afa5b | |||
99e11b41a3 | |||
b0d54b1d80 | |||
a2ff37e36d | |||
07ddba3c3d | |||
73cde0f91f | |||
af3ee07143 | |||
9f8d53f55a | |||
5a0c2390ce | |||
f3cd84804d | |||
fda5afae46 | |||
7f6a4514e4 | |||
1487372832 | |||
6d4cc66079 | |||
0cf8309a82 | |||
38bd19c243 | |||
bda286ddae | |||
5f2f3fe1c6 | |||
59156492e7 | |||
ebb89b1b8b | |||
30f847dc23 | |||
7ffaf62895 | |||
f509a985e7 | |||
eb58ab5327 | |||
feb86a77fd | |||
012994ed02 | |||
212d9a4d5e | |||
a4f774b6b2 | |||
bd6de84f93 | |||
0d385c9cb8 | |||
fdfadcefc1 | |||
fc26452f64 | |||
31fa786574 | |||
29b453dc91 | |||
837d5792be | |||
1a8c2499fa | |||
e1e40950f8 | |||
edbb9a2882 | |||
0a9639f8a9 | |||
b32675e3b1 | |||
ff7c822d69 | |||
a619df8e01 | |||
300b35c2d3 | |||
7a253fa0a0 | |||
8b5e385c28 | |||
bcc89455a7 | |||
2e5fb72716 | |||
876cffd864 | |||
7cb4faa596 | |||
c8f3a7f430 | |||
6cd7029ffc | |||
225a07bc1b | |||
085c79441b | |||
40d32e1919 | |||
480a8cb31c | |||
9bdcccaaa1 | |||
0f69833283 | |||
1769a4ed8d | |||
c8a64c39b1 | |||
c1d3aab8e3 | |||
9a9048bcd8 | |||
dec113d2ee | |||
b03349a3e0 | |||
896da0157d | |||
a58e2a0fad | |||
b13aa74fa1 | |||
8ef6df043c | |||
f89455549e | |||
a6ff9e02e2 | |||
51f5c68598 | |||
5bb612cb5a | |||
a3fcac1acb | |||
d1d7572945 | |||
7eb4b1bc77 | |||
a6c24f91e4 | |||
9e4c335a05 | |||
a1c2dfbe50 | |||
a5a07a0a23 | |||
e0fd682c81 | |||
7426bd1dd6 | |||
b39b044f79 | |||
7a2b4aa257 | |||
3762d14bdb | |||
3628f3db31 | |||
d39fea69c3 | |||
95e8b3aa58 | |||
b68145385c | |||
2310f2f7ce | |||
2cc403ad17 | |||
c2d9b9b59e | |||
c748be7bcc |
3
.github/FUNDING.yml
vendored
Normal file
3
.github/FUNDING.yml
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
ko_fi: sinaidev
|
60
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
Normal file
60
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
Normal file
@ -0,0 +1,60 @@
|
||||
name: Bug Report
|
||||
description: File a bug or crash report
|
||||
title: "[Bug]: "
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for submitting a bug report, please fill out as much detail as possible.
|
||||
- type: checkboxes
|
||||
id: latestversion
|
||||
attributes:
|
||||
label: Are you on the latest version of UnityExplorer?
|
||||
description: If not, you must update first.
|
||||
options:
|
||||
- label: Yes, I'm on the latest version of UnityExplorer.
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: version
|
||||
attributes:
|
||||
label: Which release are you using?
|
||||
description: Please select your environment for UnityExplorer.
|
||||
options:
|
||||
- BepInEx IL2CPP
|
||||
- BepInEx 6.X Mono
|
||||
- BepInEx 5.X Mono
|
||||
- MelonLoader IL2CPP
|
||||
- MelonLoader Mono
|
||||
- Standalone IL2CPP
|
||||
- Standalone Mono
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: game
|
||||
attributes:
|
||||
label: Which game did this occur on?
|
||||
description: Please tell us the name of the game. If it's a personal or private project, just let us know the Unity version.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: what-happened
|
||||
attributes:
|
||||
label: Describe the issue.
|
||||
description: What happened? Should something else have happened instead? Please provide steps to reproduce the issue if possible.
|
||||
placeholder: Tell us what you see!
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant log output
|
||||
description: |
|
||||
Please copy and paste any relevant logs and stack traces.
|
||||
* Unity log: `%userprofile%\AppData\LocalLow\{Company}\{Game}\Player.log` or `output_log.txt`
|
||||
* BepInEx: `BepInEx\LogOutput.log`
|
||||
* MelonLoader: `MelonLoader\latest.log`
|
||||
* Standalone: `{DLL_Location}\UnityExplorer\Logs\` (pick the most recent one)
|
||||
render: shell
|
||||
validations:
|
||||
required: false
|
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
18
.github/ISSUE_TEMPLATE/enhancement.yaml
vendored
Normal file
18
.github/ISSUE_TEMPLATE/enhancement.yaml
vendored
Normal file
@ -0,0 +1,18 @@
|
||||
name: New feature or enhancement
|
||||
description: Suggest or discuss a feature or enhancement for UnityExplorer
|
||||
title: "[Enhancement]: "
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for taking the time to discuss UnityExplorer, please provide as much detail as possible.
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Describe the new feature or enhancement
|
||||
description: |
|
||||
Please go into as much detail as necessary in describing the new feature or enhancement.
|
||||
If providing examples or suggestions for the required C# code, please use syntax-highlighted code blocks.
|
||||
validations:
|
||||
required: true
|
13
.github/ISSUE_TEMPLATE/other.yaml
vendored
Normal file
13
.github/ISSUE_TEMPLATE/other.yaml
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
name: Other
|
||||
description: Something else?
|
||||
title: "[Other]: "
|
||||
labels: [Other]
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Describe the issue
|
||||
description: |
|
||||
Please describe the issue in as much detail as possible.
|
||||
validations:
|
||||
required: true
|
95
.github/workflows/dotnet.yml
vendored
Normal file
95
.github/workflows/dotnet.yml
vendored
Normal file
@ -0,0 +1,95 @@
|
||||
name: Build UnityExplorer
|
||||
|
||||
# Controls when the action will run.
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
if: "!contains(github.event.head_commit.message, '-noci')"
|
||||
|
||||
steps:
|
||||
# Checkout latest with submodules
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
# Setup tools
|
||||
- name: Setup msbuild
|
||||
uses: microsoft/setup-msbuild@v1
|
||||
|
||||
- name: Setup nuget
|
||||
uses: nuget/setup-nuget@v1
|
||||
with:
|
||||
nuget-api-key: ${{ secrets.NuGetAPIKey }}
|
||||
nuget-version: '5.x'
|
||||
|
||||
# Build mcs
|
||||
- run: nuget restore lib\mcs-unity\mcs.sln
|
||||
- run: msbuild lib\mcs-unity\mcs\mcs.csproj -t:Restore -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release
|
||||
|
||||
# Build UnityExplorer releases, and upload artifacts
|
||||
|
||||
- run: dotnet nuget add source https://nuget.bepinex.dev/v3/index.json
|
||||
- run: nuget restore src\UnityExplorer.sln
|
||||
|
||||
# BepInEx Il2Cpp
|
||||
- run: msbuild src\UnityExplorer.csproj -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release_BIE_Cpp
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: UnityExplorer.BepInEx.Il2Cpp
|
||||
path: ./Release/UnityExplorer.BepInEx.Il2Cpp/*
|
||||
|
||||
# BepInEx 5 Mono
|
||||
- run: msbuild src\UnityExplorer.csproj -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release_BIE5_Mono
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: UnityExplorer.BepInEx5.Mono
|
||||
path: ./Release/UnityExplorer.BepInEx5.Mono/*
|
||||
|
||||
# BepInEx 6 Mono
|
||||
- run: msbuild src\UnityExplorer.csproj -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release_BIE6_Mono
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: UnityExplorer.BepInEx6.Mono
|
||||
path: ./Release/UnityExplorer.BepInEx6.Mono/*
|
||||
|
||||
# MelonLoader Il2Cpp
|
||||
- run: msbuild src\UnityExplorer.csproj -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release_ML_Cpp
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: UnityExplorer.MelonLoader.Il2Cpp
|
||||
path: ./Release/UnityExplorer.MelonLoader.Il2Cpp/*
|
||||
|
||||
# MelonLoader Mono
|
||||
- run: msbuild src\UnityExplorer.csproj -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release_ML_Mono
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: UnityExplorer.MelonLoader.Mono
|
||||
path: ./Release/UnityExplorer.MelonLoader.Mono/*
|
||||
|
||||
# Standalone Il2Cpp
|
||||
- run: msbuild src\UnityExplorer.csproj -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release_STANDALONE_Cpp
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: UnityExplorer.Standalone.Il2Cpp
|
||||
path: ./Release/UnityExplorer.Standalone.Il2Cpp/*
|
||||
|
||||
# Standalone Mono
|
||||
- run: msbuild src\UnityExplorer.csproj -t:Rebuild -p:Platform="AnyCPU" -p:Configuration=Release_STANDALONE_Mono
|
||||
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: UnityExplorer.Standalone.Mono
|
||||
path: ./Release/UnityExplorer.Standalone.Mono/*
|
||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -9,7 +9,6 @@
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
*/mcs-unity*
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
[submodule "lib/mcs-unity"]
|
||||
path = lib/mcs-unity
|
||||
url = https://github.com/sinai-dev/mcs-unity
|
183
README.md
183
README.md
@ -3,72 +3,70 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
An in-game explorer and a suite of debugging tools for <a href="https://docs.unity3d.com/Manual/IL2CPP.html">IL2CPP</a> and <b>Mono</b> Unity games, to aid with modding development.
|
||||
🔍 An in-game UI for exploring, debugging and modifying Unity games.
|
||||
</p>
|
||||
<p align="center">
|
||||
✔️ Supports most Unity versions from 5.2 to 2021+ (IL2CPP and Mono).
|
||||
</p>
|
||||
<p align="center">
|
||||
✨ Powered by <a href="https://github.com/sinai-dev/UniverseLib">UniverseLib</a>
|
||||
</p>
|
||||
|
||||
## Releases [](../../releases/latest) [](../../releases) [](../../releases/latest)
|
||||
# Releases [](../../releases)
|
||||
|
||||
| Mod Loader | IL2CPP | Mono |
|
||||
| ----------- | ------ | ---- |
|
||||
| [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) |
|
||||
[](../../releases/latest) [](https://github.com/sinai-dev/UnityExplorer/actions) [](../../releases/latest)
|
||||
|
||||
## How to install
|
||||
⚡ Thunderstore releases: [BepInEx Mono](https://thunderstore.io/package/sinai-dev/UnityExplorer) | [BepInEx IL2CPP](https://gtfo.thunderstore.io/package/sinai-dev/UnityExplorer_IL2CPP) | [MelonLoader IL2CPP](https://boneworks.thunderstore.io/package/sinai-dev/UnityExplorer_IL2CPP_ML)
|
||||
|
||||
### BepInEx
|
||||
## BepInEx
|
||||
|
||||
1. Install [BepInEx](https://github.com/BepInEx/BepInEx) for your game. 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).
|
||||
2. Download the UnityExplorer release for BepInEx IL2CPP or Mono above.
|
||||
3. Take the `UnityExplorer.BIE.___.dll` file and put it in `[GameFolder]\BepInEx\plugins\`
|
||||
4. In IL2CPP, you will need to download the [Unity libs](https://github.com/LavaGang/Unity-Runtime-Libraries) for the game's Unity version and put them in the `BepInEx\unity-libs\` folder.
|
||||
| Release | IL2CPP | Mono |
|
||||
| ------- | ------ | ---- |
|
||||
| BIE 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) |
|
||||
| BIE 5.X | ✖️ n/a | ✅ [link](https://github.com/sinai-dev/UnityExplorer/releases/latest/download/UnityExplorer.BepInEx5.Mono.zip) |
|
||||
|
||||
### MelonLoader
|
||||
1. Take the `UnityExplorer.BIE.[version].dll` and the `UniverseLib.[version].dll` files and put them in `BepInEx\plugins\`
|
||||
|
||||
1. Install [MelonLoader](https://github.com/HerpDerpinstine/MelonLoader) 0.3+ for your game. Version 0.3 is currently in pre-release, so you must "Enable ALPHA Releases" in your MelonLoader Installer settings to see the option for it.
|
||||
2. Download the UnityExplorer release for MelonLoader IL2CPP or Mono above.
|
||||
3. Take the `UnityExplorer.ML.___.dll` file and put it in the `[GameFolder]\Mods\` folder.
|
||||
<i>Note: BepInEx 6 is obtainable via [BepisBuilds](https://builds.bepis.io/projects/bepinex_be)</i>
|
||||
|
||||
### Standalone
|
||||
## MelonLoader
|
||||
|
||||
The standalone release requires you to also load `0Harmony.dll` (HarmonyX, from the `lib\` folder) to function properly, and the IL2CPP also requires `UnhollowerBaseLib.dll` as well. The Mono release should be fairly easy to use with any loader, but the IL2CPP one may be tricky, I'd recommend just using BepInEx or MelonLoader for IL2CPP.
|
||||
| Release | IL2CPP | Mono |
|
||||
| ------- | ------ | ---- |
|
||||
| ML 0.4+ | ✅ [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) |
|
||||
|
||||
1. Load the UnityExplorer DLL from your mod or inject it, as well as `0Harmony.dll` and `UnhollowerBaseLib.dll` as required.
|
||||
2. Create an instance of Unity Explorer with `UnityExplorer.ExplorerStandalone.CreateInstance();`
|
||||
3. Optionally subscribe to the `ExplorerStandalone.OnLog` event to handle logging if you wish.
|
||||
1. Take the `UnityExplorer.ML.[version].dll` file and put them in the `Mods\` folder created by MelonLoader, and then put the `UniverseLib.[version].dll` file in the `UserLibs\` folder.
|
||||
|
||||
## Issues and contributions
|
||||
## Standalone
|
||||
|
||||
Both issue reports and PR contributions are welcome in this repository.
|
||||
| IL2CPP | Mono |
|
||||
| ------ | ---- |
|
||||
| ✅ [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) |
|
||||
|
||||
### Issue reporting
|
||||
The standalone release can be used with any injector or loader of your choice, but it requires you to load the dependencies manually.
|
||||
|
||||
To report an issue with UnityExplorer, please use the following template (as well as any other information / images you can provide).
|
||||
1. Ensure the required libs are loaded - UniverseLib, HarmonyX and MonoMod
|
||||
2. For IL2CPP, load Il2CppAssemblyUnhollower and start an [Il2CppAssemblyUnhollower runtime](https://github.com/knah/Il2CppAssemblyUnhollower#required-external-setup)
|
||||
2. Load the UnityExplorer DLL
|
||||
3. Create an instance of Unity Explorer with `UnityExplorer.ExplorerStandalone.CreateInstance();`
|
||||
4. Optionally subscribe to the `ExplorerStandalone.OnLog` event to handle logging if you wish
|
||||
|
||||
Template:
|
||||
# Common issues and solutions
|
||||
|
||||
```
|
||||
* Game issue occurs on:
|
||||
* UnityExplorer version: (eg BIE.IL2CPP v3.3.3, etc)
|
||||
Although UnityExplorer should work out of the box for most Unity games, in some cases you may need to tweak the settings for it to work properly.
|
||||
|
||||
* Description of issue:
|
||||
To adjust the settings, open the config file:
|
||||
* BepInEx: `BepInEx\config\com.sinai.unityexplorer.cfg`
|
||||
* MelonLoader: `UserData\MelonPreferences.cfg`
|
||||
* Standalone: `UnityExplorer\config.cfg`
|
||||
|
||||
* Unity log link:
|
||||
* Mod Loader log link:
|
||||
```
|
||||
Try adjusting the following settings and see if it fixes your issues:
|
||||
* `Startup_Delay_Time` - increase to 5-10 seconds (or more as needed), can fix issues with UnityExplorer being destroyed or corrupted during startup.
|
||||
* `Disable_EventSystem_Override` - if input is not working properly, try setting this to `true`.
|
||||
|
||||
Please upload your Unity log file to [Pastebin](https://pastebin.com/) (or equivalent service) and provide a link to the paste.
|
||||
If these fixes do not work, please create an issue in this repo and I'll do my best to look into it.
|
||||
|
||||
* The log should be found at `%userprofile%\AppData\LocalLow\[Company]\[Game]\` unless redirected by your Mod Loader.
|
||||
* The file will be called either `output_log.txt` or `Player.log`
|
||||
|
||||
As well as the Unity log, please upload your Mod Loader's log:
|
||||
|
||||
* BepInEx: `BepInEx\LogOutput.log`
|
||||
* MelonLoader: `MelonLoader\Latest.log`
|
||||
|
||||
## Features
|
||||
# Features
|
||||
|
||||
<p align="center">
|
||||
<a href="https://raw.githubusercontent.com/sinai-dev/UnityExplorer/master/img/preview.png">
|
||||
@ -76,69 +74,78 @@ As well as the Unity log, please upload your Mod Loader's log:
|
||||
</a>
|
||||
</p>
|
||||
|
||||
* <b>Scene Explorer</b>: Simple menu to traverse the Transform heirarchy of the scene.
|
||||
* <b>GameObject Inspector</b>: Various helpful tools to see and manipulate the GameObject, similar to what you can do in the Editor.
|
||||
* <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. There's also a UI mode to inspect UI objects.
|
||||
### Object Explorer
|
||||
|
||||
### C# Console Tips
|
||||
* Use the <b>Scene Explorer</b> tab to traverse the active scenes, as well as the DontDestroyOnLoad and HideAndDontSave objects.
|
||||
* The "HideAndDontSave" scene contains objects with that flag, as well as Assets and Resources which are not in any scene but behave the same way.
|
||||
* You can use the Scene Loader to easily load any of the scenes in the build (may not work for Unity 5.X games)
|
||||
* Use the <b>Object Search</b> tab to search for Unity objects (including GameObjects, Components, etc), C# Singletons or Static Classes.
|
||||
* Use the UnityObject search to look for any objects which derive from `UnityEngine.Object`, with optional filters
|
||||
* The singleton search will look for any classes with a typical "Instance" field, and check it for a current value. This may cause unexpected behaviour in some IL2CPP games as we cannot distinguish between true properties and field-properties, so some property accessors will be invoked.
|
||||
|
||||
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.
|
||||
### Inspector
|
||||
|
||||
For example, you could run this code to define a temporary class (it will be visible within the console until you run `Reset();`).
|
||||
The inspector is used to see detailed information on objects of any type and manipulate their values, as well as to inspect C# Classes with static reflection.
|
||||
|
||||
```csharp
|
||||
public class MyClass
|
||||
{
|
||||
public static void Method()
|
||||
{
|
||||
UnityExplorer.ExplorerCore.Log("hello");
|
||||
}
|
||||
}
|
||||
```
|
||||
* The <b>GameObject Inspector</b> (tab prefix `[G]`) is used to inspect a `GameObject`, and to see and manipulate its Transform and Components.
|
||||
* You can edit any of the input fields in the inspector (excluding readonly fields) and press <b>Enter</b> to apply your changes. You can also do this to the GameObject path as a way to change the GameObject's parent. Press the <b>Escape</b> key to cancel your edits.
|
||||
* <i>note: When inspecting a GameObject with a Canvas, the transform controls may be overridden by the RectTransform anchors.</i>
|
||||
* The <b>Reflection Inspectors</b> (tab prefix `[R]` and `[S]`) are used for everything else
|
||||
* Automatic updating is not enabled by default, and you must press Apply for any changes you make to take effect.
|
||||
* Press the `▼` button to expand certain values such as strings, enums, lists, dictionaries, some structs, etc
|
||||
* Use the filters at the top to quickly find the members you are looking for
|
||||
* For `Texture2D` objects, there is a `View Texture` button at the top of the inspector which lets you view it and save it as a PNG file. Currently there are no other similar helpers yet, but I may add more at some point for Mesh, Sprite, Material, etc
|
||||
|
||||
You could then delete or comment out the class and run the following expression to run that method:
|
||||
### C# Console
|
||||
|
||||
```csharp
|
||||
MyClass.Method();
|
||||
```
|
||||
* The C# Console uses the `Mono.CSharp.Evaluator` to define temporary classes or run immediate REPL code.
|
||||
* You can execute a script automatically on startup by naming it `startup.cs` and placing it in the `UnityExplorer\Scripts\` folder (this folder will be created where you placed the DLL file).
|
||||
* See the "Help" dropdown in the C# console menu for more detailed information.
|
||||
|
||||
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.
|
||||
### Hook Manager
|
||||
|
||||
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.
|
||||
* The Hooks panel allows you to hook methods at the click of a button for debugging purposes.
|
||||
* Simply enter any class (generic types not yet supported) and hook the methods you want from the menu.
|
||||
* You can edit the source code of the generated hook with the "Edit Hook Source" button. Accepted method names are `Prefix` (which can return `bool` or `void`), `Postfix`, `Finalizer` (which can return `Exception` or `void`), and `Transpiler` (which must return `IEnumerable<HarmonyLib.CodeInstruction>`). You can define multiple patches if you wish.
|
||||
|
||||
### Logging
|
||||
### Mouse-Inspect
|
||||
|
||||
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.
|
||||
* The "Mouse Inspect" dropdown in the "Inspector" panel allows you to inspect objects under the mouse.
|
||||
* <b>World</b>: uses Physics.Raycast to look for Colliders
|
||||
* <b>UI</b>: uses GraphicRaycasters to find UI objects
|
||||
|
||||
These logs are also visible in the Debug Console part of the UI.
|
||||
### Clipboard
|
||||
|
||||
* The "Clipboard" panel allows you to see your current paste value, or clear it (resets it to `null`)
|
||||
* Can copy the value from any member in a Reflection Inspector, Enumerable or Dictionary, and from the target of any Inspector tab
|
||||
* Can paste values onto any member in a Reflection Inspector
|
||||
* Non-parsable arguments in Method/Property Evaluators allow pasting values
|
||||
* The C# Console has helper methods `Copy(obj)` and `Paste()` for accessing the Clipboard
|
||||
|
||||
### Settings
|
||||
|
||||
You can change the settings via the "Options" page of the main menu, or directly from the config file.
|
||||
* You can change the settings via the "Options" tab of the menu, or directly from the config file.
|
||||
* BepInEx: `BepInEx\config\com.sinai.unityexplorer.cfg`
|
||||
* MelonLoader: `UserData\MelonPreferences.cfg`
|
||||
* Standalone `{DLL_location}\UnityExplorer\config.cfg`
|
||||
|
||||
Depending on the release you are using, the config file will be found at:
|
||||
* BepInEx: `BepInEx\config\com.sinai.unityexplorer.cfg`
|
||||
* MelonLoader: `UserData\MelonPreferences.cfg`
|
||||
* Standalone `{DLL_location}\UnityExplorer\config.ini`
|
||||
# Building
|
||||
|
||||
## Building
|
||||
0. Clone the repository and run `git submodule update --init --recursive` to get the submodules.
|
||||
1. Open the `src\UnityExplorer.sln` project.
|
||||
2. Build `mcs` (Release/AnyCPU, you may need to run `nuget restore mcs.sln`)
|
||||
3. Build the UnityExplorer release(s) you want to use, either by selecting the config as the Active Config, or batch-building.
|
||||
|
||||
Building the project should be straight-forward, the references are all inside the `lib\` folder.
|
||||
If you fork the repository on GitHub you can build using the [dotnet workflow](https://github.com/sinai-dev/UnityExplorer/blob/master/.github/workflows/dotnet.yml):
|
||||
|
||||
1. Open the `src\UnityExplorer.sln` project in Visual Studio.
|
||||
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.
|
||||
4. If ILRepack complains about an error, just change the Active config to a different release and then back again. This sometimes happens for the first time you build the project.
|
||||
0. Click on the Actions tab and enable workflows in your repository
|
||||
1. Click on the "Build UnityExplorer" workflow, then click "Run Workflow" and run it manually, or make a new commit to trigger the workflow.
|
||||
2. Take the artifact from the completed run.
|
||||
|
||||
## Acknowledgments
|
||||
# Acknowledgments
|
||||
|
||||
* [ManlyMarco](https://github.com/ManlyMarco) for [Runtime Unity Editor](https://github.com/ManlyMarco/RuntimeUnityEditor) \[[license](THIRDPARTY_LICENSES.md#runtimeunityeditor-license)\], 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) \[no license\], used as the `Mono.CSharp` reference for the C# Console.
|
||||
* [HerpDerpenstine](https://github.com/HerpDerpinstine) for [MelonCoroutines](https://github.com/LavaGang/MelonLoader/blob/6cc958ec23b5e2e8453a73bc2e0d5aa353d4f0d1/MelonLoader.Support.Il2Cpp/MelonCoroutines.cs) \[[license](THIRDPARTY_LICENSES.md#melonloader-license)\], they were included for standalone IL2CPP coroutine support.
|
||||
* [InGameCodeEditor](https://assetstore.unity.com/packages/tools/gui/ingame-code-editor-144254) \[[license](THIRDPARTY_LICENSES.md#ingamecodeeditor-license)\] was used as the base for the syntax highlighting for UnityExplorer's C# console (`UnityExplorer.UI.Main.CSConsole.Lexer`).
|
||||
* [ManlyMarco](https://github.com/ManlyMarco) for [Runtime Unity Editor](https://github.com/ManlyMarco/RuntimeUnityEditor) \[[license](THIRDPARTY_LICENSES.md#runtimeunityeditor-license)\], the ScriptEvaluator from RUE's REPL console was used as the base for UnityExplorer's C# console.
|
||||
* [Geoffrey Horsington](https://github.com/ghorsington) for [mcs-unity](https://github.com/sinai-dev/mcs-unity) \[no license\], used as the `Mono.CSharp` reference for the C# Console.
|
||||
|
||||
### Disclaimer
|
||||
|
||||
|
@ -1,6 +1,5 @@
|
||||
* [RuntimeUnityEditor License](#runtimeunityeditor-license)
|
||||
* [MelonLoader License](#melonloader-license)
|
||||
* [InGameCodeEditor License](#ingamecodeeditor-license)
|
||||
|
||||
## RuntimeUnityEditor License
|
||||
|
||||
@ -873,195 +872,3 @@ Public License instead of this License. But first, please read
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
## InGameCodeEditor License
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright 2020 - 2021 Lava Gang
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
BIN
img/preview.png
BIN
img/preview.png
Binary file not shown.
Before Width: | Height: | Size: 407 KiB After Width: | Height: | Size: 495 KiB |
BIN
img/social.png
BIN
img/social.png
Binary file not shown.
Before Width: | Height: | Size: 200 KiB After Width: | Height: | Size: 232 KiB |
BIN
lib/0Harmony.dll
BIN
lib/0Harmony.dll
Binary file not shown.
BIN
lib/BepInEx.5/BepInEx.dll
Normal file
BIN
lib/BepInEx.5/BepInEx.dll
Normal file
Binary file not shown.
BIN
lib/BepInEx.6.IL2CPP/BepInEx.Core.dll
Normal file
BIN
lib/BepInEx.6.IL2CPP/BepInEx.Core.dll
Normal file
Binary file not shown.
BIN
lib/BepInEx.6.IL2CPP/BepInEx.IL2CPP.dll
Normal file
BIN
lib/BepInEx.6.IL2CPP/BepInEx.IL2CPP.dll
Normal file
Binary file not shown.
BIN
lib/BepInEx.6.Mono/BepInEx.Core.dll
Normal file
BIN
lib/BepInEx.6.Mono/BepInEx.Core.dll
Normal file
Binary file not shown.
BIN
lib/BepInEx.6.Mono/BepInEx.Unity.dll
Normal file
BIN
lib/BepInEx.6.Mono/BepInEx.Unity.dll
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
lib/BepInEx.dll
BIN
lib/BepInEx.dll
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
lib/MelonLoader/MelonLoader.dll
Normal file
BIN
lib/MelonLoader/MelonLoader.dll
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
1
lib/mcs-unity
Submodule
1
lib/mcs-unity
Submodule
Submodule lib/mcs-unity added at 0bc7359dd7
BIN
lib/mcs.dll
BIN
lib/mcs.dll
Binary file not shown.
BIN
lib/mono/UnityEngine.UI.dll
Normal file
BIN
lib/mono/UnityEngine.UI.dll
Normal file
Binary file not shown.
BIN
lib/mono/UnityEngine.dll
Normal file
BIN
lib/mono/UnityEngine.dll
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
lib/unhollowed/UnityEngine.AssetBundleModule.dll
Normal file
BIN
lib/unhollowed/UnityEngine.AssetBundleModule.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.
141
src/CSConsole/CSAutoCompleter.cs
Normal file
141
src/CSConsole/CSAutoCompleter.cs
Normal file
@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.CSConsole.Lexers;
|
||||
using UnityExplorer.UI;
|
||||
using UnityExplorer.UI.Widgets.AutoComplete;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CSConsole
|
||||
{
|
||||
public class CSAutoCompleter : ISuggestionProvider
|
||||
{
|
||||
public InputFieldRef InputField => ConsoleController.Input;
|
||||
|
||||
public bool AnchorToCaretPosition => true;
|
||||
|
||||
bool ISuggestionProvider.AllowNavigation => true;
|
||||
|
||||
public void OnSuggestionClicked(Suggestion suggestion)
|
||||
{
|
||||
ConsoleController.InsertSuggestionAtCaret(suggestion.UnderlyingValue);
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(this);
|
||||
}
|
||||
|
||||
private readonly HashSet<char> delimiters = new()
|
||||
{
|
||||
'{', '}', ',', ';', '<', '>', '(', ')', '[', ']', '=', '|', '&', '?'
|
||||
};
|
||||
|
||||
private readonly List<Suggestion> suggestions = new List<Suggestion>();
|
||||
|
||||
public void CheckAutocompletes()
|
||||
{
|
||||
if (string.IsNullOrEmpty(InputField.Text))
|
||||
{
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(this);
|
||||
return;
|
||||
}
|
||||
|
||||
suggestions.Clear();
|
||||
|
||||
int caret = Math.Max(0, Math.Min(InputField.Text.Length - 1, InputField.Component.caretPosition - 1));
|
||||
int startIdx = caret;
|
||||
|
||||
// If the character at the caret index is whitespace or delimiter,
|
||||
// or if the next character (if it exists) is not whitespace,
|
||||
// then we don't want to provide suggestions.
|
||||
if (char.IsWhiteSpace(InputField.Text[caret])
|
||||
|| delimiters.Contains(InputField.Text[caret])
|
||||
|| (InputField.Text.Length > caret + 1 && !char.IsWhiteSpace(InputField.Text[caret + 1])))
|
||||
{
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(this);
|
||||
return;
|
||||
}
|
||||
|
||||
// get the current composition string (from caret back to last delimiter)
|
||||
while (startIdx > 0)
|
||||
{
|
||||
startIdx--;
|
||||
char c = InputField.Text[startIdx];
|
||||
if (delimiters.Contains(c) || char.IsWhiteSpace(c))
|
||||
{
|
||||
startIdx++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
string input = InputField.Text.Substring(startIdx, caret - startIdx + 1);
|
||||
|
||||
// Get MCS completions
|
||||
|
||||
string[] evaluatorCompletions = ConsoleController.Evaluator.GetCompletions(input, out string prefix);
|
||||
|
||||
if (evaluatorCompletions != null && evaluatorCompletions.Any())
|
||||
{
|
||||
suggestions.AddRange(from completion in evaluatorCompletions
|
||||
select new Suggestion(GetHighlightString(prefix, completion), completion));
|
||||
}
|
||||
|
||||
// Get manual namespace completions
|
||||
|
||||
foreach (var ns in ReflectionUtility.AllNamespaces)
|
||||
{
|
||||
if (ns.StartsWith(input))
|
||||
{
|
||||
if (!namespaceHighlights.ContainsKey(ns))
|
||||
namespaceHighlights.Add(ns, $"<color=#CCCCCC>{ns}</color>");
|
||||
|
||||
string completion = ns.Substring(input.Length, ns.Length - input.Length);
|
||||
suggestions.Add(new Suggestion(namespaceHighlights[ns], completion));
|
||||
}
|
||||
}
|
||||
|
||||
// Get manual keyword completions
|
||||
|
||||
foreach (var kw in KeywordLexer.keywords)
|
||||
{
|
||||
if (kw.StartsWith(input))// && kw.Length > input.Length)
|
||||
{
|
||||
if (!keywordHighlights.ContainsKey(kw))
|
||||
keywordHighlights.Add(kw, $"<color=#{SignatureHighlighter.keywordBlueHex}>{kw}</color>");
|
||||
|
||||
string completion = kw.Substring(input.Length, kw.Length - input.Length);
|
||||
suggestions.Add(new Suggestion(keywordHighlights[kw], completion));
|
||||
}
|
||||
}
|
||||
|
||||
if (suggestions.Any())
|
||||
{
|
||||
AutoCompleteModal.Instance.TakeOwnership(this);
|
||||
AutoCompleteModal.Instance.SetSuggestions(suggestions);
|
||||
}
|
||||
else
|
||||
{
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(this);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private readonly Dictionary<string, string> namespaceHighlights = new Dictionary<string, string>();
|
||||
|
||||
private readonly Dictionary<string, string> keywordHighlights = new Dictionary<string, string>();
|
||||
|
||||
private readonly StringBuilder highlightBuilder = new StringBuilder();
|
||||
private const string OPEN_HIGHLIGHT = "<color=cyan>";
|
||||
|
||||
private string GetHighlightString(string prefix, string completion)
|
||||
{
|
||||
highlightBuilder.Clear();
|
||||
highlightBuilder.Append(OPEN_HIGHLIGHT);
|
||||
highlightBuilder.Append(prefix);
|
||||
highlightBuilder.Append(SignatureHighlighter.CLOSE_COLOR);
|
||||
highlightBuilder.Append(completion);
|
||||
return highlightBuilder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
767
src/CSConsole/ConsoleController.cs
Normal file
767
src/CSConsole/ConsoleController.cs
Normal file
@ -0,0 +1,767 @@
|
||||
using Mono.CSharp;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.UI;
|
||||
using UniverseLib.Input;
|
||||
using UnityExplorer.CSConsole;
|
||||
using UnityExplorer.UI;
|
||||
using UnityExplorer.UI.Panels;
|
||||
using UnityExplorer.UI.Widgets.AutoComplete;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib.Utility;
|
||||
using HarmonyLib;
|
||||
using UniverseLib.Runtime;
|
||||
|
||||
namespace UnityExplorer.CSConsole
|
||||
{
|
||||
public static class ConsoleController
|
||||
{
|
||||
public static ScriptEvaluator Evaluator;
|
||||
public static LexerBuilder Lexer;
|
||||
public static CSAutoCompleter Completer;
|
||||
|
||||
private static HashSet<string> usingDirectives;
|
||||
private static StringBuilder evaluatorOutput;
|
||||
private static StringWriter evaluatorStringWriter;
|
||||
|
||||
public static CSConsolePanel Panel => UIManager.GetPanel<CSConsolePanel>(UIManager.Panels.CSConsole);
|
||||
public static InputFieldRef Input => Panel.Input;
|
||||
|
||||
public static int LastCaretPosition { get; private set; }
|
||||
internal static float defaultInputFieldAlpha;
|
||||
|
||||
// Todo save as config?
|
||||
public static bool EnableCtrlRShortcut { get; private set; } = true;
|
||||
public static bool EnableAutoIndent { get; private set; } = true;
|
||||
public static bool EnableSuggestions { get; private set; } = true;
|
||||
|
||||
internal static string ScriptsFolder => Path.Combine(ExplorerCore.Loader.ExplorerFolder, "Scripts");
|
||||
|
||||
internal static readonly string[] DefaultUsing = new string[]
|
||||
{
|
||||
"System",
|
||||
"System.Linq",
|
||||
"System.Text",
|
||||
"System.Collections",
|
||||
"System.Collections.Generic",
|
||||
"UnityEngine",
|
||||
#if CPP
|
||||
"UnhollowerBaseLib",
|
||||
"UnhollowerRuntimeLib",
|
||||
#endif
|
||||
};
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
InitEventSystemPropertyHandlers();
|
||||
|
||||
// Make sure console is supported on this platform
|
||||
try
|
||||
{
|
||||
ResetConsole(false);
|
||||
// ensure the compiler is supported (if this fails then SRE is probably stubbed)
|
||||
Evaluator.Compile("0 == 0");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
DisableConsole(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
// Setup console
|
||||
Lexer = new LexerBuilder();
|
||||
Completer = new CSAutoCompleter();
|
||||
|
||||
SetupHelpInteraction();
|
||||
|
||||
Panel.OnInputChanged += OnInputChanged;
|
||||
Panel.InputScroller.OnScroll += OnInputScrolled;
|
||||
Panel.OnCompileClicked += Evaluate;
|
||||
Panel.OnResetClicked += ResetConsole;
|
||||
Panel.OnHelpDropdownChanged += HelpSelected;
|
||||
Panel.OnAutoIndentToggled += OnToggleAutoIndent;
|
||||
Panel.OnCtrlRToggled += OnToggleCtrlRShortcut;
|
||||
Panel.OnSuggestionsToggled += OnToggleSuggestions;
|
||||
Panel.OnPanelResized += OnInputScrolled;
|
||||
|
||||
// Run startup script
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(ScriptsFolder))
|
||||
Directory.CreateDirectory(ScriptsFolder);
|
||||
|
||||
var startupPath = Path.Combine(ScriptsFolder, "startup.cs");
|
||||
if (File.Exists(startupPath))
|
||||
{
|
||||
ExplorerCore.Log($"Executing startup script from '{startupPath}'...");
|
||||
var text = File.ReadAllText(startupPath);
|
||||
Input.Text = text;
|
||||
Evaluate();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Exception executing startup script: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
#region UI Listeners and options
|
||||
|
||||
// TODO save
|
||||
|
||||
private static void OnToggleAutoIndent(bool value)
|
||||
{
|
||||
EnableAutoIndent = value;
|
||||
}
|
||||
|
||||
private static void OnToggleCtrlRShortcut(bool value)
|
||||
{
|
||||
EnableCtrlRShortcut = value;
|
||||
}
|
||||
|
||||
private static void OnToggleSuggestions(bool value)
|
||||
{
|
||||
EnableSuggestions = value;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region Evaluating
|
||||
|
||||
private static void GenerateTextWriter()
|
||||
{
|
||||
evaluatorOutput = new StringBuilder();
|
||||
evaluatorStringWriter = new StringWriter(evaluatorOutput);
|
||||
}
|
||||
|
||||
public static void ResetConsole() => ResetConsole(true);
|
||||
|
||||
public static void ResetConsole(bool logSuccess = true)
|
||||
{
|
||||
if (SRENotSupported)
|
||||
return;
|
||||
|
||||
if (Evaluator != null)
|
||||
Evaluator.Dispose();
|
||||
|
||||
GenerateTextWriter();
|
||||
Evaluator = new ScriptEvaluator(evaluatorStringWriter)
|
||||
{
|
||||
InteractiveBaseClass = typeof(ScriptInteraction)
|
||||
};
|
||||
|
||||
usingDirectives = new HashSet<string>();
|
||||
foreach (var use in DefaultUsing)
|
||||
AddUsing(use);
|
||||
|
||||
if (logSuccess)
|
||||
ExplorerCore.Log($"C# Console reset. Using directives:\r\n{Evaluator.GetUsing()}");
|
||||
}
|
||||
|
||||
public static void AddUsing(string assemblyName)
|
||||
{
|
||||
if (!usingDirectives.Contains(assemblyName))
|
||||
{
|
||||
Evaluate($"using {assemblyName};", true);
|
||||
usingDirectives.Add(assemblyName);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Evaluate()
|
||||
{
|
||||
if (SRENotSupported)
|
||||
return;
|
||||
|
||||
Evaluate(Input.Text);
|
||||
}
|
||||
|
||||
public static void Evaluate(string input, bool supressLog = false)
|
||||
{
|
||||
if (SRENotSupported)
|
||||
return;
|
||||
|
||||
if (evaluatorStringWriter == null || evaluatorOutput == null)
|
||||
{
|
||||
GenerateTextWriter();
|
||||
Evaluator._textWriter = evaluatorStringWriter;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Compile the code. If it returned a CompiledMethod, it is REPL.
|
||||
CompiledMethod repl = Evaluator.Compile(input);
|
||||
|
||||
if (repl != null)
|
||||
{
|
||||
// Valid REPL, we have a delegate to the evaluation.
|
||||
try
|
||||
{
|
||||
object ret = null;
|
||||
repl.Invoke(ref ret);
|
||||
var result = ret?.ToString();
|
||||
if (!string.IsNullOrEmpty(result))
|
||||
ExplorerCore.Log($"Invoked REPL, result: {ret}");
|
||||
else
|
||||
ExplorerCore.Log($"Invoked REPL (no return value)");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Exception invoking REPL: {ex}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// The compiled code was not REPL, so it was a using directive or it defined classes.
|
||||
|
||||
string output = Evaluator._textWriter.ToString();
|
||||
var outputSplit = output.Split('\n');
|
||||
if (outputSplit.Length >= 2)
|
||||
output = outputSplit[outputSplit.Length - 2];
|
||||
evaluatorOutput.Clear();
|
||||
|
||||
if (ScriptEvaluator._reportPrinter.ErrorsCount > 0)
|
||||
throw new FormatException($"Unable to compile the code. Evaluator's last output was:\r\n{output}");
|
||||
else if (!supressLog)
|
||||
ExplorerCore.Log($"Code compiled without errors.");
|
||||
}
|
||||
}
|
||||
catch (FormatException fex)
|
||||
{
|
||||
if (!supressLog)
|
||||
ExplorerCore.LogWarning(fex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!supressLog)
|
||||
ExplorerCore.LogWarning(ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
// Updating and event listeners
|
||||
|
||||
private static bool settingCaretCoroutine;
|
||||
|
||||
private static void OnInputScrolled() => HighlightVisibleInput();
|
||||
|
||||
private static string previousInput;
|
||||
|
||||
// Invoked at most once per frame
|
||||
private static void OnInputChanged(string value)
|
||||
{
|
||||
if (SRENotSupported)
|
||||
return;
|
||||
|
||||
// prevent escape wiping input
|
||||
if (InputManager.GetKeyDown(KeyCode.Escape))
|
||||
{
|
||||
Input.Text = previousInput;
|
||||
|
||||
if (EnableSuggestions && AutoCompleteModal.CheckEscape(Completer))
|
||||
OnAutocompleteEscaped();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
previousInput = value;
|
||||
|
||||
if (EnableSuggestions && AutoCompleteModal.CheckEnter(Completer))
|
||||
OnAutocompleteEnter();
|
||||
|
||||
if (!settingCaretCoroutine)
|
||||
{
|
||||
if (EnableAutoIndent)
|
||||
DoAutoIndent();
|
||||
}
|
||||
|
||||
var inStringOrComment = HighlightVisibleInput();
|
||||
|
||||
if (!settingCaretCoroutine)
|
||||
{
|
||||
if (EnableSuggestions)
|
||||
{
|
||||
if (inStringOrComment)
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(Completer);
|
||||
else
|
||||
Completer.CheckAutocompletes();
|
||||
}
|
||||
}
|
||||
|
||||
UpdateCaret(out _);
|
||||
}
|
||||
|
||||
private static float timeOfLastCtrlR;
|
||||
|
||||
public static void Update()
|
||||
{
|
||||
if (SRENotSupported)
|
||||
return;
|
||||
|
||||
UpdateCaret(out bool caretMoved);
|
||||
|
||||
if (!settingCaretCoroutine && EnableSuggestions)
|
||||
{
|
||||
if (AutoCompleteModal.CheckEscape(Completer))
|
||||
{
|
||||
OnAutocompleteEscaped();
|
||||
return;
|
||||
}
|
||||
|
||||
if (caretMoved)
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(Completer);
|
||||
}
|
||||
|
||||
if (EnableCtrlRShortcut
|
||||
&& (InputManager.GetKey(KeyCode.LeftControl) || InputManager.GetKey(KeyCode.RightControl))
|
||||
&& InputManager.GetKeyDown(KeyCode.R)
|
||||
&& timeOfLastCtrlR.OccuredEarlierThanDefault())
|
||||
{
|
||||
timeOfLastCtrlR = Time.realtimeSinceStartup;
|
||||
Evaluate(Panel.Input.Text);
|
||||
}
|
||||
}
|
||||
|
||||
private const int CSCONSOLE_LINEHEIGHT = 18;
|
||||
|
||||
private static void UpdateCaret(out bool caretMoved)
|
||||
{
|
||||
int prevCaret = LastCaretPosition;
|
||||
caretMoved = false;
|
||||
|
||||
// Override up/down arrow movement when autocompleting
|
||||
if (EnableSuggestions && AutoCompleteModal.CheckNavigation(Completer))
|
||||
{
|
||||
Input.Component.caretPosition = LastCaretPosition;
|
||||
return;
|
||||
}
|
||||
|
||||
if (Input.Component.isFocused)
|
||||
{
|
||||
LastCaretPosition = Input.Component.caretPosition;
|
||||
caretMoved = LastCaretPosition != prevCaret;
|
||||
}
|
||||
|
||||
if (Input.Text.Length == 0)
|
||||
return;
|
||||
|
||||
// If caret moved, ensure caret is visible in the viewport
|
||||
if (caretMoved)
|
||||
{
|
||||
var charInfo = Input.TextGenerator.characters[LastCaretPosition];
|
||||
var charTop = charInfo.cursorPos.y;
|
||||
var charBot = charTop - CSCONSOLE_LINEHEIGHT;
|
||||
|
||||
var viewportMin = Input.Transform.rect.height - Input.Transform.anchoredPosition.y - (Input.Transform.rect.height * 0.5f);
|
||||
var viewportMax = viewportMin - Panel.InputScroller.ViewportRect.rect.height;
|
||||
|
||||
float diff = 0f;
|
||||
if (charTop > viewportMin)
|
||||
diff = charTop - viewportMin;
|
||||
else if (charBot < viewportMax)
|
||||
diff = charBot - viewportMax;
|
||||
|
||||
if (Math.Abs(diff) > 1)
|
||||
{
|
||||
var rect = Input.Transform;
|
||||
rect.anchoredPosition = new Vector2(rect.anchoredPosition.x, rect.anchoredPosition.y - diff);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetCaretPosition(int caretPosition)
|
||||
{
|
||||
settingCaretCoroutine = true;
|
||||
Input.Component.readOnly = true;
|
||||
RuntimeHelper.StartCoroutine(SetCaretCoroutine(caretPosition));
|
||||
}
|
||||
|
||||
static void InitEventSystemPropertyHandlers()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var member in typeof(EventSystem).GetMembers(AccessTools.all))
|
||||
{
|
||||
if (member.Name == "m_CurrentSelected")
|
||||
{
|
||||
Type backingType;
|
||||
if (member.MemberType == MemberTypes.Property)
|
||||
backingType = (member as PropertyInfo).PropertyType;
|
||||
else
|
||||
backingType = (member as FieldInfo).FieldType;
|
||||
|
||||
usingEventSystemDictionaryMembers = ReflectionUtility.IsDictionary(backingType);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Exception checking EventSystem property backing type: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
static bool usingEventSystemDictionaryMembers;
|
||||
|
||||
static readonly AmbiguousMemberHandler<EventSystem, GameObject> m_CurrentSelected_Handler_Normal
|
||||
= new(true, true, "m_CurrentSelected", "m_currentSelected");
|
||||
static readonly AmbiguousMemberHandler<EventSystem, Dictionary<int, GameObject>> m_CurrentSelected_Handler_Dictionary
|
||||
= new(true, true, "m_CurrentSelected", "m_currentSelected");
|
||||
|
||||
static readonly AmbiguousMemberHandler<EventSystem, bool> m_SelectionGuard_Handler_Normal
|
||||
= new(true, true, "m_SelectionGuard", "m_selectionGuard");
|
||||
static readonly AmbiguousMemberHandler<EventSystem, Dictionary<int, bool>> m_SelectionGuard_Handler_Dictionary
|
||||
= new(true, true, "m_SelectionGuard", "m_selectionGuard");
|
||||
|
||||
static void SetCurrentSelectedGameObject(EventSystem instance, GameObject value)
|
||||
{
|
||||
instance.SetSelectedGameObject(value);
|
||||
|
||||
if (usingEventSystemDictionaryMembers)
|
||||
m_CurrentSelected_Handler_Dictionary.GetValue(instance)[0] = value;
|
||||
else
|
||||
m_CurrentSelected_Handler_Normal.SetValue(instance, value);
|
||||
}
|
||||
|
||||
static void SetSelectionGuard(EventSystem instance, bool value)
|
||||
{
|
||||
if (usingEventSystemDictionaryMembers)
|
||||
m_SelectionGuard_Handler_Dictionary.GetValue(instance)[0] = value;
|
||||
else
|
||||
m_SelectionGuard_Handler_Normal.SetValue(instance, value);
|
||||
}
|
||||
|
||||
private static IEnumerator SetCaretCoroutine(int caretPosition)
|
||||
{
|
||||
var color = Input.Component.selectionColor;
|
||||
color.a = 0f;
|
||||
Input.Component.selectionColor = color;
|
||||
|
||||
try { SetCurrentSelectedGameObject(CursorUnlocker.CurrentEventSystem, null); }
|
||||
catch (Exception ex) { ExplorerCore.Log($"Failed removing selected object: {ex}"); }
|
||||
|
||||
yield return null; // ~~~~~~~ YIELD FRAME ~~~~~~~~~
|
||||
|
||||
try { SetSelectionGuard(CursorUnlocker.CurrentEventSystem, false); }
|
||||
catch (Exception ex) { ExplorerCore.Log($"Failed setting selection guard: {ex}"); }
|
||||
|
||||
try { SetCurrentSelectedGameObject(CursorUnlocker.CurrentEventSystem, Input.GameObject); }
|
||||
catch (Exception ex) { ExplorerCore.Log($"Failed setting selected gameobject: {ex}"); }
|
||||
|
||||
yield return null; // ~~~~~~~ YIELD FRAME ~~~~~~~~~
|
||||
|
||||
Input.Component.Select();
|
||||
|
||||
Input.Component.caretPosition = caretPosition;
|
||||
Input.Component.selectionFocusPosition = caretPosition;
|
||||
LastCaretPosition = Input.Component.caretPosition;
|
||||
|
||||
color.a = defaultInputFieldAlpha;
|
||||
Input.Component.selectionColor = color;
|
||||
|
||||
Input.Component.readOnly = false;
|
||||
settingCaretCoroutine = false;
|
||||
}
|
||||
|
||||
#region Lexer Highlighting
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if caret is inside string or comment, false otherwise
|
||||
/// </summary>
|
||||
private static bool HighlightVisibleInput()
|
||||
{
|
||||
if (string.IsNullOrEmpty(Input.Text))
|
||||
{
|
||||
Panel.HighlightText.text = "";
|
||||
Panel.LineNumberText.text = "1";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Calculate the visible lines
|
||||
|
||||
int topLine = -1;
|
||||
int bottomLine = -1;
|
||||
|
||||
// the top and bottom position of the viewport in relation to the text height
|
||||
// they need the half-height adjustment to normalize against the 'line.topY' value.
|
||||
var viewportMin = Input.Transform.rect.height - Input.Transform.anchoredPosition.y - (Input.Transform.rect.height * 0.5f);
|
||||
var viewportMax = viewportMin - Panel.InputScroller.ViewportRect.rect.height;
|
||||
|
||||
for (int i = 0; i < Input.TextGenerator.lineCount; i++)
|
||||
{
|
||||
var line = Input.TextGenerator.lines[i];
|
||||
// if not set the top line yet, and top of line is below the viewport top
|
||||
if (topLine == -1 && line.topY <= viewportMin)
|
||||
topLine = i;
|
||||
// if bottom of line is below the viewport bottom
|
||||
if ((line.topY - line.height) >= viewportMax)
|
||||
bottomLine = i;
|
||||
}
|
||||
|
||||
topLine = Math.Max(0, topLine - 1);
|
||||
bottomLine = Math.Min(Input.TextGenerator.lineCount - 1, bottomLine + 1);
|
||||
|
||||
int startIdx = Input.TextGenerator.lines[topLine].startCharIdx;
|
||||
int endIdx = (bottomLine >= Input.TextGenerator.lineCount - 1)
|
||||
? Input.Text.Length - 1
|
||||
: (Input.TextGenerator.lines[bottomLine + 1].startCharIdx - 1);
|
||||
|
||||
|
||||
// Highlight the visible text with the LexerBuilder
|
||||
|
||||
Panel.HighlightText.text = Lexer.BuildHighlightedString(Input.Text, startIdx, endIdx, topLine, LastCaretPosition, out bool ret);
|
||||
|
||||
// Set the line numbers
|
||||
|
||||
// determine true starting line number (not the same as the cached TextGenerator line numbers)
|
||||
int realStartLine = 0;
|
||||
for (int i = 0; i < startIdx; i++)
|
||||
{
|
||||
if (LexerBuilder.IsNewLine(Input.Text[i]))
|
||||
realStartLine++;
|
||||
}
|
||||
realStartLine++;
|
||||
char lastPrev = '\n';
|
||||
|
||||
var sb = new StringBuilder();
|
||||
|
||||
// append leading new lines for spacing (no point rendering line numbers we cant see)
|
||||
for (int i = 0; i < topLine; i++)
|
||||
sb.Append('\n');
|
||||
|
||||
// append the displayed line numbers
|
||||
for (int i = topLine; i <= bottomLine; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
lastPrev = Input.Text[Input.TextGenerator.lines[i].startCharIdx - 1];
|
||||
|
||||
// previous line ended with a newline character, this is an actual new line.
|
||||
if (LexerBuilder.IsNewLine(lastPrev))
|
||||
{
|
||||
sb.Append(realStartLine.ToString());
|
||||
realStartLine++;
|
||||
}
|
||||
|
||||
sb.Append('\n');
|
||||
}
|
||||
|
||||
Panel.LineNumberText.text = sb.ToString();
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region Autocompletes
|
||||
|
||||
public static void InsertSuggestionAtCaret(string suggestion)
|
||||
{
|
||||
settingCaretCoroutine = true;
|
||||
Input.Text = Input.Text.Insert(LastCaretPosition, suggestion);
|
||||
|
||||
SetCaretPosition(LastCaretPosition + suggestion.Length);
|
||||
LastCaretPosition = Input.Component.caretPosition;
|
||||
}
|
||||
|
||||
private static void OnAutocompleteEnter()
|
||||
{
|
||||
// Remove the new line
|
||||
int lastIdx = Input.Component.caretPosition - 1;
|
||||
Input.Text = Input.Text.Remove(lastIdx, 1);
|
||||
|
||||
// Use the selected suggestion
|
||||
Input.Component.caretPosition = LastCaretPosition;
|
||||
Completer.OnSuggestionClicked(AutoCompleteModal.SelectedSuggestion);
|
||||
}
|
||||
|
||||
private static void OnAutocompleteEscaped()
|
||||
{
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(Completer);
|
||||
SetCaretPosition(LastCaretPosition);
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region Auto indenting
|
||||
|
||||
private static int prevContentLen = 0;
|
||||
|
||||
private static void DoAutoIndent()
|
||||
{
|
||||
if (Input.Text.Length > prevContentLen)
|
||||
{
|
||||
int inc = Input.Text.Length - prevContentLen;
|
||||
|
||||
if (inc == 1)
|
||||
{
|
||||
int caret = Input.Component.caretPosition;
|
||||
Input.Text = Lexer.IndentCharacter(Input.Text, ref caret);
|
||||
Input.Component.caretPosition = caret;
|
||||
LastCaretPosition = caret;
|
||||
}
|
||||
else
|
||||
{
|
||||
// todo indenting for copy+pasted content
|
||||
|
||||
//ExplorerCore.Log("Content increased by " + inc);
|
||||
//var comp = Input.Text.Substring(PreviousCaretPosition, inc);
|
||||
//ExplorerCore.Log("composition string: " + comp);
|
||||
}
|
||||
}
|
||||
|
||||
prevContentLen = Input.Text.Length;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region "Help" interaction
|
||||
|
||||
private static bool SRENotSupported;
|
||||
|
||||
private static void DisableConsole(Exception ex)
|
||||
{
|
||||
SRENotSupported = true;
|
||||
Input.Component.readOnly = true;
|
||||
Input.Component.textComponent.color = "5d8556".ToColor();
|
||||
|
||||
if (ex is NotSupportedException)
|
||||
{
|
||||
Input.Text = $@"The C# Console has been disabled because System.Reflection.Emit threw an exception: {ex.ReflectionExToString()}
|
||||
|
||||
If the game was built with Unity's stubbed netstandard 2.0 runtime, you can fix this with UnityDoorstop:
|
||||
* Download the Unity Editor version that the game uses
|
||||
* Navigate to the folder:
|
||||
- Editor\Data\PlaybackEngines\windowsstandalonesupport\Variations\mono\Managed
|
||||
- or, Editor\Data\MonoBleedingEdge\lib\mono\4.5
|
||||
* Copy the mscorlib.dll and System.Reflection.Emit DLLs from the folder
|
||||
* Make a subfolder in the folder that contains doorstop_config.ini
|
||||
* Put the DLLs inside the subfolder
|
||||
* Set the 'dllSearchPathOverride' in doorstop_config.ini to the subfolder name";
|
||||
}
|
||||
else
|
||||
{
|
||||
Input.Text = $@"The C# Console has been disabled because of an unknown error.
|
||||
{ex}";
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, string> helpDict = new();
|
||||
|
||||
public static void SetupHelpInteraction()
|
||||
{
|
||||
var drop = Panel.HelpDropdown;
|
||||
|
||||
helpDict.Add("Help", "");
|
||||
helpDict.Add("Usings", HELP_USINGS);
|
||||
helpDict.Add("REPL", HELP_REPL);
|
||||
helpDict.Add("Classes", HELP_CLASSES);
|
||||
helpDict.Add("Coroutines", HELP_COROUTINES);
|
||||
|
||||
foreach (var opt in helpDict)
|
||||
drop.options.Add(new Dropdown.OptionData(opt.Key));
|
||||
}
|
||||
|
||||
public static void HelpSelected(int index)
|
||||
{
|
||||
if (index == 0)
|
||||
return;
|
||||
|
||||
var helpText = helpDict.ElementAt(index);
|
||||
|
||||
Input.Text = helpText.Value;
|
||||
|
||||
Panel.HelpDropdown.value = 0;
|
||||
}
|
||||
|
||||
|
||||
internal const string STARTUP_TEXT = @"<color=#5d8556>// Welcome to the UnityExplorer C# Console!
|
||||
|
||||
// It is recommended to use the Log panel (or a console log window) while using this tool.
|
||||
// Use the Help dropdown to see detailed examples of how to use the console.
|
||||
|
||||
// To execute a script automatically on startup, put the script at 'UnityExplorer\Scripts\startup.cs'</color>";
|
||||
|
||||
internal const string HELP_USINGS = @"// You can add a using directive to any namespace, but you must compile for it to take effect.
|
||||
// It will remain in effect until you Reset the console.
|
||||
using UnityEngine.UI;
|
||||
|
||||
// To see your current usings, use the ""GetUsing();"" helper.
|
||||
// Note: You cannot add usings and evaluate REPL at the same time.";
|
||||
|
||||
internal const string HELP_REPL = @"/* REPL (Read-Evaluate-Print-Loop) is a way to execute code immediately.
|
||||
* REPL code cannot contain any using directives or classes.
|
||||
* The return value of the last line of your REPL will be printed to the log.
|
||||
* Variables defined in REPL will exist until you Reset the console.
|
||||
*/
|
||||
|
||||
// eg: This code would print 'Hello, World!', and then print 6 as the return value.
|
||||
Log(""Hello, world!"");
|
||||
var x = 5;
|
||||
++x;
|
||||
|
||||
/* The following helpers are available in REPL mode:
|
||||
* CurrentTarget; - System.Object, the target of the active Inspector tab
|
||||
* AllTargets; - System.Object[], the targets of all Inspector tabs
|
||||
* Log(obj); - prints a message to the console log
|
||||
* Inspect(obj); - inspect the object with the Inspector
|
||||
* Inspect(someType); - inspect a Type with static reflection
|
||||
* Start(enumerator); - Coroutine, starts the IEnumerator as a Coroutine, and returns the Coroutine.
|
||||
* Stop(coroutine); - stop the Coroutine ONLY if it was started with Start(ienumerator).
|
||||
* Copy(obj); - copies the object to the UnityExplorer Clipboard
|
||||
* Paste(); - System.Object, the contents of the Clipboard.
|
||||
* GetUsing(); - prints the current using directives to the console log
|
||||
* GetVars(); - prints the names and values of the REPL variables you have defined
|
||||
* GetClasses(); - prints the names and members of the classes you have defined
|
||||
* help; - the default REPL help command, contains additional helpers.
|
||||
*/";
|
||||
|
||||
internal const string HELP_CLASSES = @"// Classes you compile will exist until the application closes.
|
||||
// You can soft-overwrite a class by compiling it again with the same name. The old class will still technically exist in memory.
|
||||
|
||||
// Compiled classes can be accessed from both inside and outside this console.
|
||||
// Note: in IL2CPP, you must declare a Namespace to inject these classes with ClassInjector or it will crash the game.
|
||||
|
||||
public class HelloWorld
|
||||
{
|
||||
public static void Main()
|
||||
{
|
||||
UnityExplorer.ExplorerCore.Log(""Hello, world!"");
|
||||
}
|
||||
}
|
||||
|
||||
// In REPL, you could call the example method above with ""HelloWorld.Main();""
|
||||
// Note: The compiler does not allow you to run REPL code and define classes at the same time.
|
||||
|
||||
// In REPL, use the ""GetClasses();"" helper to see the classes you have defined since the last Reset.";
|
||||
|
||||
internal const string HELP_COROUTINES = @"// To start a Coroutine directly, use ""Start(SomeCoroutine());"" in REPL mode.
|
||||
|
||||
// To declare a coroutine, you will need to compile it separately. For example:
|
||||
public class MyCoro
|
||||
{
|
||||
public static IEnumerator Main()
|
||||
{
|
||||
yield return null;
|
||||
UnityExplorer.ExplorerCore.Log(""Hello, world after one frame!"");
|
||||
}
|
||||
}
|
||||
// To run this Coroutine in REPL, it would look like ""Start(MyCoro.Main());""";
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
363
src/CSConsole/LexerBuilder.cs
Normal file
363
src/CSConsole/LexerBuilder.cs
Normal file
@ -0,0 +1,363 @@
|
||||
using Mono.CSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CSConsole.Lexers;
|
||||
using UniverseLib;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CSConsole
|
||||
{
|
||||
public struct MatchInfo
|
||||
{
|
||||
public int startIndex;
|
||||
public int endIndex;
|
||||
public bool isStringOrComment;
|
||||
public bool matchToEndOfLine;
|
||||
public string htmlColorTag;
|
||||
}
|
||||
|
||||
public class LexerBuilder
|
||||
{
|
||||
#region Core and initialization
|
||||
|
||||
public const char WHITESPACE = ' ';
|
||||
public readonly HashSet<char> IndentOpenChars = new HashSet<char> { '{', '(' };
|
||||
public readonly HashSet<char> IndentCloseChars = new HashSet<char> { '}', ')' };
|
||||
|
||||
private readonly Lexer[] lexers;
|
||||
private readonly HashSet<char> delimiters = new HashSet<char>();
|
||||
|
||||
private readonly StringLexer stringLexer = new StringLexer();
|
||||
private readonly CommentLexer commentLexer = new CommentLexer();
|
||||
|
||||
public LexerBuilder()
|
||||
{
|
||||
lexers = new Lexer[]
|
||||
{
|
||||
commentLexer,
|
||||
stringLexer,
|
||||
new SymbolLexer(),
|
||||
new NumberLexer(),
|
||||
new KeywordLexer(),
|
||||
};
|
||||
|
||||
foreach (var matcher in lexers)
|
||||
{
|
||||
foreach (char c in matcher.Delimiters)
|
||||
{
|
||||
if (!delimiters.Contains(c))
|
||||
delimiters.Add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>The last committed index for a match or no-match. Starts at -1 for a new parse.</summary>
|
||||
public int CommittedIndex { get; private set; }
|
||||
/// <summary>The index of the character we are currently parsing, at minimum it will be CommittedIndex + 1.</summary>
|
||||
public int CurrentIndex { get; private set; }
|
||||
|
||||
/// <summary>The current character we are parsing, determined by CurrentIndex.</summary>
|
||||
public char Current => !EndOfInput ? currentInput[CurrentIndex] : WHITESPACE;
|
||||
/// <summary>The previous character (CurrentIndex - 1), or whitespace if no previous character.</summary>
|
||||
public char Previous => CurrentIndex >= 1 ? currentInput[CurrentIndex - 1] : WHITESPACE;
|
||||
|
||||
/// <summary>Returns true if CurrentIndex is >= the current input length.</summary>
|
||||
public bool EndOfInput => CurrentIndex > currentEndIdx;
|
||||
/// <summary>Returns true if EndOfInput or current character is a new line.</summary>
|
||||
public bool EndOrNewLine => EndOfInput || IsNewLine(Current);
|
||||
|
||||
public static bool IsNewLine(char c) => c == '\n' || c == '\r';
|
||||
|
||||
private string currentInput;
|
||||
private int currentStartIdx;
|
||||
private int currentEndIdx;
|
||||
|
||||
/// <summary>
|
||||
/// Parse the range of the string with the Lexer and build a RichText-highlighted representation of it.
|
||||
/// </summary>
|
||||
/// <param name="input">The entire input string which you want to parse a section (or all) of</param>
|
||||
/// <param name="startIdx">The first character you want to highlight</param>
|
||||
/// <param name="endIdx">The last character you want to highlight</param>
|
||||
/// <param name="leadingLines">The amount of leading empty lines you want before the first character in the return string.</param>
|
||||
/// <returns>A string which contains the amount of leading lines specified, as well as the rich-text highlighted section.</returns>
|
||||
public string BuildHighlightedString(string input, int startIdx, int endIdx, int leadingLines, int caretIdx, out bool caretInStringOrComment)
|
||||
{
|
||||
caretInStringOrComment = false;
|
||||
|
||||
if (string.IsNullOrEmpty(input) || endIdx <= startIdx)
|
||||
return input;
|
||||
|
||||
currentInput = input;
|
||||
currentStartIdx = startIdx;
|
||||
currentEndIdx = endIdx;
|
||||
|
||||
var sb = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < leadingLines; i++)
|
||||
sb.Append('\n');
|
||||
|
||||
int lastUnhighlighted = startIdx;
|
||||
foreach (var match in GetMatches())
|
||||
{
|
||||
// append non-highlighted text between last match and this
|
||||
for (int i = lastUnhighlighted; i < match.startIndex; i++)
|
||||
sb.Append(input[i]);
|
||||
|
||||
// append the highlighted match
|
||||
sb.Append(match.htmlColorTag);
|
||||
for (int i = match.startIndex; i <= match.endIndex && i <= currentEndIdx; i++)
|
||||
sb.Append(input[i]);
|
||||
sb.Append(SignatureHighlighter.CLOSE_COLOR);
|
||||
|
||||
// update the last unhighlighted start index
|
||||
lastUnhighlighted = match.endIndex + 1;
|
||||
|
||||
int matchEndIdx = match.endIndex;
|
||||
if (match.matchToEndOfLine)
|
||||
{
|
||||
while (input.Length - 1 >= matchEndIdx)
|
||||
{
|
||||
matchEndIdx++;
|
||||
if (IsNewLine(input[matchEndIdx]))
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// check caretIdx to determine inStringOrComment state
|
||||
if (caretIdx >= match.startIndex && (caretIdx <= (matchEndIdx+1) || (caretIdx >= input.Length && matchEndIdx >= input.Length - 1)))
|
||||
caretInStringOrComment = match.isStringOrComment;
|
||||
}
|
||||
|
||||
// Append trailing unhighlighted input
|
||||
while (lastUnhighlighted <= endIdx)
|
||||
{
|
||||
sb.Append(input[lastUnhighlighted]);
|
||||
lastUnhighlighted++;
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
|
||||
// Match builder, iterates through each Lexer and returns all matches found.
|
||||
|
||||
public IEnumerable<MatchInfo> GetMatches()
|
||||
{
|
||||
CommittedIndex = currentStartIdx - 1;
|
||||
Rollback();
|
||||
|
||||
while (!EndOfInput)
|
||||
{
|
||||
SkipWhitespace();
|
||||
bool anyMatch = false;
|
||||
int startIndex = CommittedIndex + 1;
|
||||
|
||||
foreach (var lexer in lexers)
|
||||
{
|
||||
if (lexer.TryMatchCurrent(this))
|
||||
{
|
||||
anyMatch = true;
|
||||
|
||||
yield return new MatchInfo
|
||||
{
|
||||
startIndex = startIndex,
|
||||
endIndex = CommittedIndex,
|
||||
htmlColorTag = lexer.ColorTag,
|
||||
isStringOrComment = lexer is StringLexer || lexer is CommentLexer,
|
||||
};
|
||||
break;
|
||||
}
|
||||
else
|
||||
Rollback();
|
||||
}
|
||||
|
||||
if (!anyMatch)
|
||||
{
|
||||
CurrentIndex = CommittedIndex + 1;
|
||||
Commit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Methods used by the Lexers for interfacing with the current parse process
|
||||
|
||||
public char PeekNext(int amount = 1)
|
||||
{
|
||||
CurrentIndex += amount;
|
||||
return Current;
|
||||
}
|
||||
|
||||
public void Commit()
|
||||
{
|
||||
CommittedIndex = Math.Min(currentEndIdx, CurrentIndex);
|
||||
}
|
||||
|
||||
public void Rollback()
|
||||
{
|
||||
CurrentIndex = CommittedIndex + 1;
|
||||
}
|
||||
|
||||
public void RollbackBy(int amount)
|
||||
{
|
||||
CurrentIndex = Math.Max(CommittedIndex + 1, CurrentIndex - amount);
|
||||
}
|
||||
|
||||
public bool IsDelimiter(char character, bool orWhitespace = false, bool orLetterOrDigit = false)
|
||||
{
|
||||
return delimiters.Contains(character)
|
||||
|| (orWhitespace && char.IsWhiteSpace(character))
|
||||
|| (orLetterOrDigit && char.IsLetterOrDigit(character));
|
||||
}
|
||||
|
||||
private void SkipWhitespace()
|
||||
{
|
||||
// peek and commit as long as there is whitespace
|
||||
while (!EndOfInput && char.IsWhiteSpace(Current))
|
||||
{
|
||||
Commit();
|
||||
PeekNext();
|
||||
}
|
||||
|
||||
if (!char.IsWhiteSpace(Current))
|
||||
Rollback();
|
||||
}
|
||||
|
||||
#region Auto Indenting
|
||||
|
||||
// Using the Lexer for indenting as it already has what we need to tokenize strings and comments.
|
||||
// At the moment this only handles when a single newline or close-delimiter is composed.
|
||||
// Does not handle copy+paste or any other characters yet.
|
||||
|
||||
public string IndentCharacter(string input, ref int caretIndex)
|
||||
{
|
||||
int lastCharIndex = caretIndex - 1;
|
||||
char c = input[lastCharIndex];
|
||||
|
||||
// we only want to indent for new lines and close indents
|
||||
if (!IsNewLine(c) && !IndentCloseChars.Contains(c))
|
||||
return input;
|
||||
|
||||
// perform a light parse up to the caret to determine indent level
|
||||
currentInput = input;
|
||||
currentStartIdx = 0;
|
||||
currentEndIdx = lastCharIndex;
|
||||
CommittedIndex = -1;
|
||||
Rollback();
|
||||
|
||||
int indent = 0;
|
||||
|
||||
while (!EndOfInput)
|
||||
{
|
||||
if (CurrentIndex >= lastCharIndex)
|
||||
{
|
||||
// reached the caret index
|
||||
if (indent <= 0)
|
||||
break;
|
||||
|
||||
if (IsNewLine(c))
|
||||
input = IndentNewLine(input, indent, ref caretIndex);
|
||||
else // closing indent
|
||||
input = IndentCloseDelimiter(input, indent, lastCharIndex, ref caretIndex);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// Try match strings and comments (Lexer will commit to the end of the match)
|
||||
if (stringLexer.TryMatchCurrent(this) || commentLexer.TryMatchCurrent(this))
|
||||
{
|
||||
PeekNext();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Still parsing, check indent
|
||||
|
||||
if (IndentOpenChars.Contains(Current))
|
||||
indent++;
|
||||
else if (IndentCloseChars.Contains(Current))
|
||||
indent--;
|
||||
|
||||
Commit();
|
||||
PeekNext();
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
private string IndentNewLine(string input, int indent, ref int caretIndex)
|
||||
{
|
||||
// continue until the end of line or next non-whitespace character.
|
||||
// if there's a close-indent on this line, reduce the indent level.
|
||||
while (CurrentIndex < input.Length - 1)
|
||||
{
|
||||
CurrentIndex++;
|
||||
char next = input[CurrentIndex];
|
||||
if (IsNewLine(next))
|
||||
break;
|
||||
if (char.IsWhiteSpace(next))
|
||||
continue;
|
||||
else if (IndentCloseChars.Contains(next))
|
||||
indent--;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (indent > 0)
|
||||
{
|
||||
input = input.Insert(caretIndex, new string('\t', indent));
|
||||
caretIndex += indent;
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
private string IndentCloseDelimiter(string input, int indent, int lastCharIndex, ref int caretIndex)
|
||||
{
|
||||
if (CurrentIndex > lastCharIndex)
|
||||
{
|
||||
return input;
|
||||
}
|
||||
|
||||
// lower the indent level by one as we would not have accounted for this closing symbol
|
||||
indent--;
|
||||
|
||||
// go back from the caret to the start of the line, calculate how much indent we need to adjust.
|
||||
while (CurrentIndex > 0)
|
||||
{
|
||||
CurrentIndex--;
|
||||
char prev = input[CurrentIndex];
|
||||
if (IsNewLine(prev))
|
||||
break;
|
||||
if (!char.IsWhiteSpace(prev))
|
||||
{
|
||||
// the line containing the closing bracket has non-whitespace characters before it. do not indent.
|
||||
indent = 0;
|
||||
break;
|
||||
}
|
||||
else if (prev == '\t')
|
||||
indent--;
|
||||
}
|
||||
|
||||
if (indent > 0)
|
||||
{
|
||||
input = input.Insert(caretIndex, new string('\t', indent));
|
||||
caretIndex += indent;
|
||||
}
|
||||
else if (indent < 0)
|
||||
{
|
||||
// line is overly indented
|
||||
input = input.Remove(lastCharIndex - 1, -indent);
|
||||
caretIndex += indent;
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
53
src/CSConsole/Lexers/CommentLexer.cs
Normal file
53
src/CSConsole/Lexers/CommentLexer.cs
Normal file
@ -0,0 +1,53 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityExplorer.CSConsole.Lexers
|
||||
{
|
||||
public class CommentLexer : Lexer
|
||||
{
|
||||
private enum CommentType
|
||||
{
|
||||
Line,
|
||||
Block
|
||||
}
|
||||
|
||||
// forest green
|
||||
protected override Color HighlightColor => new Color(0.34f, 0.65f, 0.29f, 1.0f);
|
||||
|
||||
public override bool TryMatchCurrent(LexerBuilder lexer)
|
||||
{
|
||||
if (lexer.Current == '/')
|
||||
{
|
||||
lexer.PeekNext();
|
||||
if (lexer.Current == '/')
|
||||
{
|
||||
// line comment. read to end of line or file.
|
||||
do
|
||||
{
|
||||
lexer.Commit();
|
||||
lexer.PeekNext();
|
||||
}
|
||||
while (!lexer.EndOrNewLine);
|
||||
|
||||
return true;
|
||||
}
|
||||
else if (lexer.Current == '*')
|
||||
{
|
||||
// block comment, read until end of file or closing '*/'
|
||||
lexer.PeekNext();
|
||||
do
|
||||
{
|
||||
lexer.PeekNext();
|
||||
lexer.Commit();
|
||||
}
|
||||
while (!lexer.EndOfInput && !(lexer.Current == '/' && lexer.Previous == '*'));
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
63
src/CSConsole/Lexers/KeywordLexer.cs
Normal file
63
src/CSConsole/Lexers/KeywordLexer.cs
Normal file
@ -0,0 +1,63 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityExplorer.CSConsole.Lexers
|
||||
{
|
||||
public class KeywordLexer : Lexer
|
||||
{
|
||||
// system blue
|
||||
protected override Color HighlightColor => new Color(0.33f, 0.61f, 0.83f, 1.0f);
|
||||
|
||||
public static readonly HashSet<string> keywords = new HashSet<string>
|
||||
{
|
||||
// reserved keywords
|
||||
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue",
|
||||
"decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally",
|
||||
"fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock",
|
||||
"long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public",
|
||||
"readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch",
|
||||
"this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void",
|
||||
"volatile", "while",
|
||||
// contextual keywords
|
||||
"add", "and", "alias", "ascending", "async", "await", "by", "descending", "dynamic", "equals", "from", "get",
|
||||
"global", "group", "init", "into", "join", "let", "managed", "nameof", "not", "notnull", "on",
|
||||
"or", "orderby", "partial", "record", "remove", "select", "set", "unmanaged", "value", "var", "when", "where",
|
||||
"where", "with", "yield", "nint", "nuint"
|
||||
};
|
||||
|
||||
public override bool TryMatchCurrent(LexerBuilder lexer)
|
||||
{
|
||||
var prev = lexer.Previous;
|
||||
var first = lexer.Current;
|
||||
|
||||
// check for keywords
|
||||
if (lexer.IsDelimiter(prev, true) && char.IsLetter(first))
|
||||
{
|
||||
// can be a keyword...
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(lexer.Current);
|
||||
while (!lexer.EndOfInput && char.IsLetter(lexer.PeekNext()))
|
||||
sb.Append(lexer.Current);
|
||||
|
||||
// next must be whitespace or delimiter
|
||||
if (!lexer.EndOfInput && !(char.IsWhiteSpace(lexer.Current) || lexer.IsDelimiter(lexer.Current)))
|
||||
return false;
|
||||
|
||||
if (keywords.Contains(sb.ToString()))
|
||||
{
|
||||
if (!lexer.EndOfInput)
|
||||
lexer.RollbackBy(1);
|
||||
lexer.Commit();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
20
src/CSConsole/Lexers/Lexer.cs
Normal file
20
src/CSConsole/Lexers/Lexer.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
using UniverseLib;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CSConsole.Lexers
|
||||
{
|
||||
public abstract class Lexer
|
||||
{
|
||||
public virtual IEnumerable<char> Delimiters => Enumerable.Empty<char>();
|
||||
|
||||
protected abstract Color HighlightColor { get; }
|
||||
|
||||
public string ColorTag => colorTag ?? (colorTag = "<color=#" + HighlightColor.ToHex() + ">");
|
||||
private string colorTag;
|
||||
|
||||
public abstract bool TryMatchCurrent(LexerBuilder lexer);
|
||||
}
|
||||
}
|
32
src/CSConsole/Lexers/NumberLexer.cs
Normal file
32
src/CSConsole/Lexers/NumberLexer.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityExplorer.CSConsole.Lexers
|
||||
{
|
||||
public class NumberLexer : Lexer
|
||||
{
|
||||
// Maroon
|
||||
protected override Color HighlightColor => new Color(0.58f, 0.33f, 0.33f, 1.0f);
|
||||
|
||||
private bool IsNumeric(char c) => char.IsNumber(c) || c == '.';
|
||||
|
||||
public override bool TryMatchCurrent(LexerBuilder lexer)
|
||||
{
|
||||
// previous character must be whitespace or delimiter
|
||||
if (!lexer.IsDelimiter(lexer.Previous, true))
|
||||
return false;
|
||||
|
||||
if (!IsNumeric(lexer.Current))
|
||||
return false;
|
||||
|
||||
while (!lexer.EndOfInput)
|
||||
{
|
||||
lexer.Commit();
|
||||
if (!IsNumeric(lexer.PeekNext()))
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
80
src/CSConsole/Lexers/StringLexer.cs
Normal file
80
src/CSConsole/Lexers/StringLexer.cs
Normal file
@ -0,0 +1,80 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityExplorer.CSConsole.Lexers
|
||||
{
|
||||
public class StringLexer : Lexer
|
||||
{
|
||||
public override IEnumerable<char> Delimiters => new[] { '"', '\'', };
|
||||
|
||||
// orange
|
||||
protected override Color HighlightColor => new Color(0.79f, 0.52f, 0.32f, 1.0f);
|
||||
|
||||
public override bool TryMatchCurrent(LexerBuilder lexer)
|
||||
{
|
||||
if (lexer.Current == '"')
|
||||
{
|
||||
if (lexer.Previous == '@')
|
||||
{
|
||||
// verbatim string, continue until un-escaped quote.
|
||||
while (!lexer.EndOfInput)
|
||||
{
|
||||
lexer.Commit();
|
||||
if (lexer.PeekNext() == '"')
|
||||
{
|
||||
lexer.Commit();
|
||||
// possibly the end, check for escaped quotes.
|
||||
// commit the character and flip the escape bool for each quote.
|
||||
bool escaped = false;
|
||||
while (lexer.PeekNext() == '"')
|
||||
{
|
||||
lexer.Commit();
|
||||
escaped = !escaped;
|
||||
}
|
||||
// if the last quote wasnt escaped, that was the end of the string.
|
||||
if (!escaped)
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// normal string
|
||||
// continue until a quote which is not escaped, or end of input
|
||||
|
||||
while (!lexer.EndOfInput)
|
||||
{
|
||||
lexer.Commit();
|
||||
lexer.PeekNext();
|
||||
if ((lexer.Current == '"') && lexer.Previous != '\\')
|
||||
{
|
||||
lexer.Commit();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
else if (lexer.Current == '\'')
|
||||
{
|
||||
// char
|
||||
|
||||
while (!lexer.EndOfInput)
|
||||
{
|
||||
lexer.Commit();
|
||||
lexer.PeekNext();
|
||||
if ((lexer.Current == '\'') && lexer.Previous != '\\')
|
||||
{
|
||||
lexer.Commit();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
49
src/CSConsole/Lexers/SymbolLexer.cs
Normal file
49
src/CSConsole/Lexers/SymbolLexer.cs
Normal file
@ -0,0 +1,49 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityExplorer.CSConsole.Lexers
|
||||
{
|
||||
public class SymbolLexer : Lexer
|
||||
{
|
||||
// silver
|
||||
protected override Color HighlightColor => new Color(0.6f, 0.6f, 0.6f);
|
||||
|
||||
// all symbols are delimiters
|
||||
public override IEnumerable<char> Delimiters => symbols.Where(it => it != '.'); // '.' is not a delimiter, only a separator.
|
||||
|
||||
public static bool IsSymbol(char c) => symbols.Contains(c);
|
||||
|
||||
public static readonly HashSet<char> symbols = new HashSet<char>
|
||||
{
|
||||
'[', '{', '(', // open
|
||||
']', '}', ')', // close
|
||||
'.', ',', ';', ':', '?', '@', // special
|
||||
|
||||
// operators
|
||||
'+', '-', '*', '/', '%', '&', '|', '^', '~', '=', '<', '>', '!',
|
||||
};
|
||||
|
||||
public override bool TryMatchCurrent(LexerBuilder lexer)
|
||||
{
|
||||
// previous character must be delimiter, whitespace, or alphanumeric.
|
||||
if (!lexer.IsDelimiter(lexer.Previous, true, true))
|
||||
return false;
|
||||
|
||||
if (IsSymbol(lexer.Current))
|
||||
{
|
||||
do
|
||||
{
|
||||
lexer.Commit();
|
||||
lexer.PeekNext();
|
||||
}
|
||||
while (IsSymbol(lexer.Current));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,12 +1,13 @@
|
||||
using System;
|
||||
using Mono.CSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using Mono.CSharp;
|
||||
using System.Text;
|
||||
|
||||
// Thanks to ManlyMarco for most of this
|
||||
// Thanks to ManlyMarco for this
|
||||
|
||||
namespace UnityExplorer.Core.CSharp
|
||||
namespace UnityExplorer.CSConsole
|
||||
{
|
||||
public class ScriptEvaluator : Evaluator, IDisposable
|
||||
{
|
||||
@ -15,14 +16,14 @@ namespace UnityExplorer.Core.CSharp
|
||||
"mscorlib", "System.Core", "System", "System.Xml"
|
||||
};
|
||||
|
||||
internal static TextWriter _textWriter;
|
||||
internal TextWriter _textWriter;
|
||||
internal static StreamReportPrinter _reportPrinter;
|
||||
|
||||
public ScriptEvaluator(TextWriter tw) : base(BuildContext(tw))
|
||||
{
|
||||
_textWriter = tw;
|
||||
|
||||
ImportAppdomainAssemblies(ReferenceAssembly);
|
||||
ImportAppdomainAssemblies(Reference);
|
||||
AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoad;
|
||||
}
|
||||
|
||||
@ -39,7 +40,15 @@ namespace UnityExplorer.Core.CSharp
|
||||
if (StdLib.Contains(name))
|
||||
return;
|
||||
|
||||
ReferenceAssembly(args.LoadedAssembly);
|
||||
Reference(args.LoadedAssembly);
|
||||
}
|
||||
|
||||
private void Reference(Assembly asm)
|
||||
{
|
||||
var name = asm.GetName().Name;
|
||||
if (name == "completions")
|
||||
return;
|
||||
ReferenceAssembly(asm);
|
||||
}
|
||||
|
||||
private static CompilerContext BuildContext(TextWriter tw)
|
||||
@ -65,9 +74,7 @@ namespace UnityExplorer.Core.CSharp
|
||||
{
|
||||
string name = assembly.GetName().Name;
|
||||
if (StdLib.Contains(name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
import(assembly);
|
||||
}
|
77
src/CSConsole/ScriptInteraction.cs
Normal file
77
src/CSConsole/ScriptInteraction.cs
Normal file
@ -0,0 +1,77 @@
|
||||
using HarmonyLib;
|
||||
using Mono.CSharp;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.Runtime;
|
||||
using UnityExplorer.UI.Panels;
|
||||
using UniverseLib;
|
||||
|
||||
namespace UnityExplorer.CSConsole
|
||||
{
|
||||
public class ScriptInteraction : InteractiveBase
|
||||
{
|
||||
public static object CurrentTarget
|
||||
=> InspectorManager.ActiveInspector?.Target;
|
||||
|
||||
public static object[] AllTargets
|
||||
=> InspectorManager.Inspectors.Select(it => it.Target).ToArray();
|
||||
|
||||
public static void Log(object message)
|
||||
=> ExplorerCore.Log(message);
|
||||
|
||||
public static void Inspect(object obj)
|
||||
=> InspectorManager.Inspect(obj);
|
||||
|
||||
public static void Inspect(Type type)
|
||||
=> InspectorManager.Inspect(type);
|
||||
|
||||
public static Coroutine Start(IEnumerator ienumerator)
|
||||
=> RuntimeHelper.StartCoroutine(ienumerator);
|
||||
|
||||
public static void Stop(Coroutine coro)
|
||||
=> RuntimeHelper.StopCoroutine(coro);
|
||||
|
||||
public static void Copy(object obj)
|
||||
=> ClipboardPanel.Copy(obj);
|
||||
|
||||
public static object Paste()
|
||||
=> ClipboardPanel.Current;
|
||||
|
||||
public static void GetUsing()
|
||||
=> Log(Evaluator.GetUsing());
|
||||
|
||||
public static void GetVars()
|
||||
{
|
||||
var vars = Evaluator.GetVars()?.Trim();
|
||||
if (string.IsNullOrEmpty(vars))
|
||||
ExplorerCore.LogWarning("No variables seem to be defined!");
|
||||
else
|
||||
Log(vars);
|
||||
}
|
||||
|
||||
public static void GetClasses()
|
||||
{
|
||||
if (AccessTools.Field(typeof(Evaluator), "source_file")
|
||||
.GetValue(Evaluator) is CompilationSourceFile sourceFile
|
||||
&& sourceFile.Containers.Any())
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append($"There are {sourceFile.Containers.Count} defined classes:");
|
||||
foreach (TypeDefinition type in sourceFile.Containers.Where(it => it is TypeDefinition))
|
||||
{
|
||||
sb.Append($"\n\n{type.MemberName.Name}:");
|
||||
foreach (var member in type.Members)
|
||||
sb.Append($"\n\t- {member.AttributeTargets}: \"{member.MemberName.Name}\" ({member.ModFlags})");
|
||||
}
|
||||
Log(sb.ToString());
|
||||
}
|
||||
else
|
||||
ExplorerCore.LogWarning("No classes seem to be defined.");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
49
src/CacheObject/CacheConfigEntry.cs
Normal file
49
src/CacheObject/CacheConfigEntry.cs
Normal file
@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityExplorer.Config;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public class CacheConfigEntry : CacheObjectBase
|
||||
{
|
||||
public CacheConfigEntry(IConfigElement configElement)
|
||||
{
|
||||
this.RefConfigElement = configElement;
|
||||
this.FallbackType = configElement.ElementType;
|
||||
|
||||
this.NameLabelText = $"<color=cyan>{configElement.Name}</color>" +
|
||||
$"\r\n<color=grey><i>{configElement.Description}</i></color>";
|
||||
this.NameLabelTextRaw = string.Empty;
|
||||
|
||||
configElement.OnValueChangedNotify += UpdateValueFromSource;
|
||||
}
|
||||
|
||||
public IConfigElement RefConfigElement;
|
||||
|
||||
public override bool ShouldAutoEvaluate => true;
|
||||
public override bool HasArguments => false;
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public void UpdateValueFromSource()
|
||||
{
|
||||
//if (RefConfigElement.BoxedValue.Equals(this.Value))
|
||||
// return;
|
||||
|
||||
SetValueFromSource(RefConfigElement.BoxedValue);
|
||||
|
||||
if (this.CellView != null)
|
||||
this.SetDataToCell(CellView);
|
||||
}
|
||||
|
||||
public override void TrySetUserValue(object value)
|
||||
{
|
||||
this.Value = value;
|
||||
RefConfigElement.BoxedValue = value;
|
||||
}
|
||||
|
||||
protected override bool TryAutoEvaluateIfUnitialized(CacheObjectCell cell) => true;
|
||||
}
|
||||
}
|
83
src/CacheObject/CacheConstructor.cs
Normal file
83
src/CacheObject/CacheConstructor.cs
Normal file
@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityExplorer.Inspectors;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public class CacheConstructor : CacheMember
|
||||
{
|
||||
public ConstructorInfo CtorInfo { get; }
|
||||
readonly Type typeForStructConstructor;
|
||||
|
||||
public override Type DeclaringType => typeForStructConstructor ?? CtorInfo.DeclaringType;
|
||||
public override bool IsStatic => true;
|
||||
public override bool ShouldAutoEvaluate => false;
|
||||
public override bool CanWrite => false;
|
||||
|
||||
public CacheConstructor(ConstructorInfo ci)
|
||||
{
|
||||
this.CtorInfo = ci;
|
||||
}
|
||||
|
||||
public CacheConstructor(Type typeForStructConstructor)
|
||||
{
|
||||
this.typeForStructConstructor = typeForStructConstructor;
|
||||
}
|
||||
|
||||
public override void SetInspectorOwner(ReflectionInspector inspector, MemberInfo member)
|
||||
{
|
||||
// if is parameterless struct ctor
|
||||
if (typeForStructConstructor != null)
|
||||
{
|
||||
this.Owner = inspector;
|
||||
|
||||
// eg. Vector3.Vector3()
|
||||
this.NameLabelText = SignatureHighlighter.Parse(typeForStructConstructor, false);
|
||||
NameLabelText += $".{NameLabelText}()";
|
||||
|
||||
this.NameForFiltering = SignatureHighlighter.RemoveHighlighting(NameLabelText);
|
||||
this.NameLabelTextRaw = NameForFiltering;
|
||||
return;
|
||||
}
|
||||
|
||||
base.SetInspectorOwner(inspector, member);
|
||||
|
||||
Arguments = CtorInfo.GetParameters();
|
||||
if (CtorInfo.DeclaringType.IsGenericTypeDefinition)
|
||||
GenericArguments = CtorInfo.DeclaringType.GetGenericArguments();
|
||||
}
|
||||
|
||||
protected override object TryEvaluate()
|
||||
{
|
||||
try
|
||||
{
|
||||
Type returnType = DeclaringType;
|
||||
|
||||
if (returnType.IsGenericTypeDefinition)
|
||||
returnType = DeclaringType.MakeGenericType(Evaluator.TryParseGenericArguments());
|
||||
|
||||
object ret;
|
||||
if (HasArguments)
|
||||
ret = Activator.CreateInstance(returnType, Evaluator.TryParseArguments());
|
||||
else
|
||||
ret = Activator.CreateInstance(returnType, ArgumentUtility.EmptyArgs);
|
||||
|
||||
HadException = false;
|
||||
LastException = null;
|
||||
return ret;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HadException = true;
|
||||
LastException = ex;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void TrySetValue(object value) => throw new NotImplementedException("You can't set a constructor");
|
||||
}
|
||||
}
|
59
src/CacheObject/CacheField.cs
Normal file
59
src/CacheObject/CacheField.cs
Normal file
@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityExplorer.Inspectors;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public class CacheField : CacheMember
|
||||
{
|
||||
public FieldInfo FieldInfo { get; internal set; }
|
||||
public override Type DeclaringType => FieldInfo.DeclaringType;
|
||||
public override bool IsStatic => FieldInfo.IsStatic;
|
||||
public override bool CanWrite => m_canWrite ?? (bool)(m_canWrite = !(FieldInfo.IsLiteral && !FieldInfo.IsInitOnly));
|
||||
private bool? m_canWrite;
|
||||
|
||||
public override bool ShouldAutoEvaluate => true;
|
||||
|
||||
public CacheField(FieldInfo fi)
|
||||
{
|
||||
this.FieldInfo = fi;
|
||||
}
|
||||
|
||||
public override void SetInspectorOwner(ReflectionInspector inspector, MemberInfo member)
|
||||
{
|
||||
base.SetInspectorOwner(inspector, member);
|
||||
}
|
||||
|
||||
protected override object TryEvaluate()
|
||||
{
|
||||
try
|
||||
{
|
||||
var ret = FieldInfo.GetValue(DeclaringInstance);
|
||||
HadException = false;
|
||||
LastException = null;
|
||||
return ret;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HadException = true;
|
||||
LastException = ex;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void TrySetValue(object value)
|
||||
{
|
||||
try
|
||||
{
|
||||
FieldInfo.SetValue(DeclaringInstance, value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
98
src/CacheObject/CacheKeyValuePair.cs
Normal file
98
src/CacheObject/CacheKeyValuePair.cs
Normal file
@ -0,0 +1,98 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityExplorer.CacheObject.IValues;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
using UniverseLib;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public class CacheKeyValuePair : CacheObjectBase
|
||||
{
|
||||
//public InteractiveList CurrentList { get; set; }
|
||||
|
||||
public int DictIndex;
|
||||
public object DictKey;
|
||||
public object DisplayedKey;
|
||||
|
||||
public bool KeyInputWanted;
|
||||
public bool InspectWanted;
|
||||
public string KeyLabelText;
|
||||
public string KeyInputText;
|
||||
public string KeyInputTypeText;
|
||||
|
||||
public float DesiredKeyWidth;
|
||||
public float DesiredValueWidth;
|
||||
|
||||
public override bool ShouldAutoEvaluate => true;
|
||||
public override bool HasArguments => false;
|
||||
public override bool CanWrite => Owner.CanWrite;
|
||||
|
||||
public void SetDictOwner(InteractiveDictionary dict, int index)
|
||||
{
|
||||
this.Owner = dict;
|
||||
this.DictIndex = index;
|
||||
}
|
||||
|
||||
public void SetKey(object key)
|
||||
{
|
||||
this.DictKey = key;
|
||||
this.DisplayedKey = key.TryCast();
|
||||
|
||||
var type = DisplayedKey.GetType();
|
||||
if (ParseUtility.CanParse(type))
|
||||
{
|
||||
KeyInputWanted = true;
|
||||
KeyInputText = ParseUtility.ToStringForInput(DisplayedKey, type);
|
||||
KeyInputTypeText = SignatureHighlighter.Parse(type, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
KeyInputWanted = false;
|
||||
InspectWanted = type != typeof(bool) && !type.IsEnum;
|
||||
KeyLabelText = ToStringUtility.ToStringWithType(DisplayedKey, type, true);
|
||||
}
|
||||
}
|
||||
|
||||
public override void SetDataToCell(CacheObjectCell cell)
|
||||
{
|
||||
base.SetDataToCell(cell);
|
||||
|
||||
var kvpCell = cell as CacheKeyValuePairCell;
|
||||
|
||||
kvpCell.NameLabel.text = $"{DictIndex}:";
|
||||
kvpCell.HiddenNameLabel.Text = "";
|
||||
kvpCell.Image.color = DictIndex % 2 == 0 ? CacheListEntryCell.EvenColor : CacheListEntryCell.OddColor;
|
||||
|
||||
if (KeyInputWanted)
|
||||
{
|
||||
kvpCell.KeyInputField.UIRoot.SetActive(true);
|
||||
kvpCell.KeyInputTypeLabel.gameObject.SetActive(true);
|
||||
kvpCell.KeyLabel.gameObject.SetActive(false);
|
||||
kvpCell.KeyInspectButton.Component.gameObject.SetActive(false);
|
||||
|
||||
kvpCell.KeyInputField.Text = KeyInputText;
|
||||
kvpCell.KeyInputTypeLabel.text = KeyInputTypeText;
|
||||
}
|
||||
else
|
||||
{
|
||||
kvpCell.KeyInputField.UIRoot.SetActive(false);
|
||||
kvpCell.KeyInputTypeLabel.gameObject.SetActive(false);
|
||||
kvpCell.KeyLabel.gameObject.SetActive(true);
|
||||
kvpCell.KeyInspectButton.Component.gameObject.SetActive(InspectWanted);
|
||||
|
||||
kvpCell.KeyLabel.text = KeyLabelText;
|
||||
}
|
||||
}
|
||||
|
||||
public override void TrySetUserValue(object value)
|
||||
{
|
||||
(Owner as InteractiveDictionary).TrySetValueToKey(DictKey, value, DictIndex);
|
||||
}
|
||||
|
||||
|
||||
protected override bool TryAutoEvaluateIfUnitialized(CacheObjectCell cell) => true;
|
||||
}
|
||||
}
|
42
src/CacheObject/CacheListEntry.cs
Normal file
42
src/CacheObject/CacheListEntry.cs
Normal file
@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityExplorer.CacheObject.IValues;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public class CacheListEntry : CacheObjectBase
|
||||
{
|
||||
public int ListIndex;
|
||||
|
||||
public override bool ShouldAutoEvaluate => true;
|
||||
public override bool HasArguments => false;
|
||||
public override bool CanWrite => Owner?.CanWrite ?? false;
|
||||
|
||||
public void SetListOwner(InteractiveList list, int listIndex)
|
||||
{
|
||||
this.Owner = list;
|
||||
this.ListIndex = listIndex;
|
||||
}
|
||||
|
||||
public override void SetDataToCell(CacheObjectCell cell)
|
||||
{
|
||||
base.SetDataToCell(cell);
|
||||
|
||||
var listCell = cell as CacheListEntryCell;
|
||||
|
||||
listCell.NameLabel.text = $"{ListIndex}:";
|
||||
listCell.HiddenNameLabel.Text = "";
|
||||
listCell.Image.color = ListIndex % 2 == 0 ? CacheListEntryCell.EvenColor : CacheListEntryCell.OddColor;
|
||||
}
|
||||
|
||||
public override void TrySetUserValue(object value)
|
||||
{
|
||||
(Owner as InteractiveList).TrySetValueToIndex(value, this.ListIndex);
|
||||
}
|
||||
|
||||
protected override bool TryAutoEvaluateIfUnitialized(CacheObjectCell cell) => true;
|
||||
}
|
||||
}
|
354
src/CacheObject/CacheMember.cs
Normal file
354
src/CacheObject/CacheMember.cs
Normal file
@ -0,0 +1,354 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.Runtime;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
using UnityExplorer.Inspectors;
|
||||
using UniverseLib.UI.Models;
|
||||
using UnityExplorer.UI;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UnityExplorer.UI.Widgets;
|
||||
using UniverseLib.Utility;
|
||||
using UniverseLib.UI.ObjectPool;
|
||||
using System.Collections;
|
||||
using HarmonyLib;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public abstract class CacheMember : CacheObjectBase
|
||||
{
|
||||
public abstract Type DeclaringType { get; }
|
||||
public string NameForFiltering { get; protected set; }
|
||||
public object DeclaringInstance => IsStatic ? null : (m_declaringInstance ??= Owner.Target.TryCast(DeclaringType));
|
||||
private object m_declaringInstance;
|
||||
|
||||
public abstract bool IsStatic { get; }
|
||||
public override bool HasArguments => Arguments?.Length > 0 || GenericArguments.Length > 0;
|
||||
public ParameterInfo[] Arguments { get; protected set; } = new ParameterInfo[0];
|
||||
public Type[] GenericArguments { get; protected set; } = ArgumentUtility.EmptyTypes;
|
||||
public EvaluateWidget Evaluator { get; protected set; }
|
||||
public bool Evaluating => Evaluator != null && Evaluator.UIRoot.activeSelf;
|
||||
|
||||
public virtual void SetInspectorOwner(ReflectionInspector inspector, MemberInfo member)
|
||||
{
|
||||
this.Owner = inspector;
|
||||
this.NameLabelText = this switch
|
||||
{
|
||||
CacheMethod => SignatureHighlighter.HighlightMethod(member as MethodInfo),
|
||||
CacheConstructor => SignatureHighlighter.HighlightConstructor(member as ConstructorInfo),
|
||||
_ => SignatureHighlighter.Parse(member.DeclaringType, false, member),
|
||||
};
|
||||
|
||||
this.NameForFiltering = SignatureHighlighter.RemoveHighlighting(NameLabelText);
|
||||
this.NameLabelTextRaw = NameForFiltering;
|
||||
}
|
||||
|
||||
public override void ReleasePooledObjects()
|
||||
{
|
||||
base.ReleasePooledObjects();
|
||||
|
||||
if (this.Evaluator != null)
|
||||
{
|
||||
this.Evaluator.OnReturnToPool();
|
||||
Pool<EvaluateWidget>.Return(this.Evaluator);
|
||||
this.Evaluator = null;
|
||||
}
|
||||
}
|
||||
|
||||
public override void UnlinkFromView()
|
||||
{
|
||||
if (this.Evaluator != null)
|
||||
this.Evaluator.UIRoot.transform.SetParent(Pool<EvaluateWidget>.Instance.InactiveHolder.transform, false);
|
||||
|
||||
base.UnlinkFromView();
|
||||
}
|
||||
|
||||
protected abstract object TryEvaluate();
|
||||
|
||||
protected abstract void TrySetValue(object value);
|
||||
|
||||
/// <summary>
|
||||
/// Evaluate is called when first shown (if ShouldAutoEvaluate), or else when Evaluate button is clicked, or auto-updated.
|
||||
/// </summary>
|
||||
public void Evaluate()
|
||||
{
|
||||
SetValueFromSource(TryEvaluate());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when user presses the Evaluate button.
|
||||
/// </summary>
|
||||
public void EvaluateAndSetCell()
|
||||
{
|
||||
Evaluate();
|
||||
if (CellView != null)
|
||||
SetDataToCell(CellView);
|
||||
}
|
||||
|
||||
public override void TrySetUserValue(object value)
|
||||
{
|
||||
TrySetValue(value);
|
||||
Evaluate();
|
||||
}
|
||||
|
||||
protected override void SetValueState(CacheObjectCell cell, ValueStateArgs args)
|
||||
{
|
||||
base.SetValueState(cell, args);
|
||||
}
|
||||
|
||||
private static readonly Color evalEnabledColor = new(0.15f, 0.25f, 0.15f);
|
||||
private static readonly Color evalDisabledColor = new(0.15f, 0.15f, 0.15f);
|
||||
|
||||
protected override bool TryAutoEvaluateIfUnitialized(CacheObjectCell objectcell)
|
||||
{
|
||||
var cell = objectcell as CacheMemberCell;
|
||||
|
||||
cell.EvaluateHolder.SetActive(!ShouldAutoEvaluate);
|
||||
if (!ShouldAutoEvaluate)
|
||||
{
|
||||
cell.EvaluateButton.Component.gameObject.SetActive(true);
|
||||
if (HasArguments)
|
||||
{
|
||||
if (!Evaluating)
|
||||
cell.EvaluateButton.ButtonText.text = $"Evaluate ({Arguments.Length + GenericArguments.Length})";
|
||||
else
|
||||
{
|
||||
cell.EvaluateButton.ButtonText.text = "Hide";
|
||||
Evaluator.UIRoot.transform.SetParent(cell.EvaluateHolder.transform, false);
|
||||
RuntimeHelper.SetColorBlock(cell.EvaluateButton.Component, evalEnabledColor, evalEnabledColor * 1.3f);
|
||||
}
|
||||
}
|
||||
else
|
||||
cell.EvaluateButton.ButtonText.text = "Evaluate";
|
||||
|
||||
if (!Evaluating)
|
||||
RuntimeHelper.SetColorBlock(cell.EvaluateButton.Component, evalDisabledColor, evalDisabledColor * 1.3f);
|
||||
}
|
||||
|
||||
if (State == ValueState.NotEvaluated && !ShouldAutoEvaluate)
|
||||
{
|
||||
SetValueState(cell, ValueStateArgs.Default);
|
||||
cell.RefreshSubcontentButton();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (State == ValueState.NotEvaluated)
|
||||
Evaluate();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void OnEvaluateClicked()
|
||||
{
|
||||
if (!HasArguments)
|
||||
{
|
||||
EvaluateAndSetCell();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Evaluator == null)
|
||||
{
|
||||
this.Evaluator = Pool<EvaluateWidget>.Borrow();
|
||||
Evaluator.OnBorrowedFromPool(this);
|
||||
Evaluator.UIRoot.transform.SetParent((CellView as CacheMemberCell).EvaluateHolder.transform, false);
|
||||
TryAutoEvaluateIfUnitialized(CellView);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Evaluator.UIRoot.activeSelf)
|
||||
Evaluator.UIRoot.SetActive(false);
|
||||
else
|
||||
Evaluator.UIRoot.SetActive(true);
|
||||
|
||||
TryAutoEvaluateIfUnitialized(CellView);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#region Cache Member Util
|
||||
|
||||
public static List<CacheMember> GetCacheMembers(object inspectorTarget, Type type, ReflectionInspector inspector)
|
||||
{
|
||||
//var list = new List<CacheMember>();
|
||||
HashSet<string> cachedSigs = new();
|
||||
List<CacheMember> props = new();
|
||||
List<CacheMember> fields = new();
|
||||
List<CacheMember> ctors = new();
|
||||
List<CacheMember> methods = new();
|
||||
|
||||
var types = ReflectionUtility.GetAllBaseTypes(type);
|
||||
|
||||
var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
|
||||
if (!inspector.StaticOnly)
|
||||
flags |= BindingFlags.Instance;
|
||||
|
||||
if (!type.IsAbstract)
|
||||
{
|
||||
// Get non-static constructors of the main type.
|
||||
// There's no reason to get the static cctor, it will be invoked when we inspect the class.
|
||||
// Also no point getting ctors on inherited types.
|
||||
foreach (var ctor in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
|
||||
TryCacheMember(ctor, ctors, cachedSigs, type, inspector);
|
||||
|
||||
// structs always have a parameterless constructor
|
||||
if (type.IsValueType)
|
||||
{
|
||||
CacheConstructor cached = new(type);
|
||||
cached.SetFallbackType(type);
|
||||
cached.SetInspectorOwner(inspector, null);
|
||||
ctors.Add(cached);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var declaringType in types)
|
||||
{
|
||||
var target = inspectorTarget;
|
||||
if (!inspector.StaticOnly)
|
||||
target = target.TryCast(declaringType);
|
||||
|
||||
foreach (var prop in declaringType.GetProperties(flags))
|
||||
if (prop.DeclaringType == declaringType)
|
||||
TryCacheMember(prop, props, cachedSigs, declaringType, inspector);
|
||||
|
||||
foreach (var field in declaringType.GetFields(flags))
|
||||
if (field.DeclaringType == declaringType)
|
||||
TryCacheMember(field, fields, cachedSigs, declaringType, inspector);
|
||||
|
||||
foreach (var method in declaringType.GetMethods(flags))
|
||||
if (method.DeclaringType == declaringType)
|
||||
TryCacheMember(method, methods, cachedSigs, declaringType, inspector);
|
||||
|
||||
}
|
||||
|
||||
var sorted = new List<CacheMember>();
|
||||
sorted.AddRange(props.OrderBy(it => Array.IndexOf(types, it.DeclaringType))
|
||||
.ThenBy(it => it.NameForFiltering));
|
||||
sorted.AddRange(fields.OrderBy(it => Array.IndexOf(types, it.DeclaringType))
|
||||
.ThenBy(it => it.NameForFiltering));
|
||||
sorted.AddRange(ctors.OrderBy(it => Array.IndexOf(types, it.DeclaringType))
|
||||
.ThenBy(it => it.NameForFiltering));
|
||||
sorted.AddRange(methods.OrderBy(it => Array.IndexOf(types, it.DeclaringType))
|
||||
.ThenBy(it => it.NameForFiltering));
|
||||
return sorted;
|
||||
}
|
||||
|
||||
private static void TryCacheMember(MemberInfo member, IList list, HashSet<string> cachedSigs,
|
||||
Type declaringType, ReflectionInspector inspector, bool ignorePropertyMethodInfos = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (UERuntimeHelper.IsBlacklisted(member))
|
||||
return;
|
||||
|
||||
var sig = GetSig(member);
|
||||
|
||||
// ExplorerCore.Log($"Trying to cache member {sig}... ({member.MemberType})");
|
||||
|
||||
CacheMember cached;
|
||||
Type returnType;
|
||||
switch (member.MemberType)
|
||||
{
|
||||
case MemberTypes.Constructor:
|
||||
{
|
||||
var ci = member as ConstructorInfo;
|
||||
sig += GetArgumentString(ci.GetParameters());
|
||||
if (cachedSigs.Contains(sig))
|
||||
return;
|
||||
cached = new CacheConstructor(ci);
|
||||
returnType = ci.DeclaringType;
|
||||
}
|
||||
break;
|
||||
|
||||
case MemberTypes.Method:
|
||||
{
|
||||
var mi = member as MethodInfo;
|
||||
if (ignorePropertyMethodInfos
|
||||
&& (mi.Name.StartsWith("get_") || mi.Name.StartsWith("set_")))
|
||||
return;
|
||||
|
||||
sig += GetArgumentString(mi.GetParameters());
|
||||
if (cachedSigs.Contains(sig))
|
||||
return;
|
||||
|
||||
cached = new CacheMethod(mi);
|
||||
returnType = mi.ReturnType;
|
||||
break;
|
||||
}
|
||||
|
||||
case MemberTypes.Property:
|
||||
{
|
||||
var pi = member as PropertyInfo;
|
||||
|
||||
if (!pi.CanRead && pi.CanWrite)
|
||||
{
|
||||
// write-only property, cache the set method instead.
|
||||
var setMethod = pi.GetSetMethod(true);
|
||||
if (setMethod != null)
|
||||
TryCacheMember(setMethod, list, cachedSigs, declaringType, inspector, false);
|
||||
return;
|
||||
}
|
||||
|
||||
sig += GetArgumentString(pi.GetIndexParameters());
|
||||
if (cachedSigs.Contains(sig))
|
||||
return;
|
||||
|
||||
cached = new CacheProperty(pi);
|
||||
returnType = pi.PropertyType;
|
||||
break;
|
||||
}
|
||||
|
||||
case MemberTypes.Field:
|
||||
{
|
||||
var fi = member as FieldInfo;
|
||||
cached = new CacheField(fi);
|
||||
returnType = fi.FieldType;
|
||||
break;
|
||||
}
|
||||
|
||||
default: return;
|
||||
}
|
||||
|
||||
cachedSigs.Add(sig);
|
||||
|
||||
cached.SetFallbackType(returnType);
|
||||
cached.SetInspectorOwner(inspector, member);
|
||||
|
||||
list.Add(cached);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Exception caching member {member.DeclaringType.FullName}.{member.Name}!");
|
||||
ExplorerCore.Log(e.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
internal static string GetSig(MemberInfo member)
|
||||
=> $"{member.DeclaringType.Name}.{member.Name}";
|
||||
|
||||
internal static string GetArgumentString(ParameterInfo[] args)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(' ');
|
||||
sb.Append('(');
|
||||
foreach (var param in args)
|
||||
{
|
||||
sb.Append(param.ParameterType.Name);
|
||||
sb.Append(' ');
|
||||
sb.Append(param.Name);
|
||||
sb.Append(',');
|
||||
sb.Append(' ');
|
||||
}
|
||||
sb.Append(')');
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
}
|
||||
}
|
62
src/CacheObject/CacheMethod.cs
Normal file
62
src/CacheObject/CacheMethod.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityExplorer.Inspectors;
|
||||
using UniverseLib;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public class CacheMethod : CacheMember
|
||||
{
|
||||
public MethodInfo MethodInfo { get; }
|
||||
public override Type DeclaringType => MethodInfo.DeclaringType;
|
||||
public override bool CanWrite => false;
|
||||
public override bool IsStatic => MethodInfo.IsStatic;
|
||||
|
||||
public override bool ShouldAutoEvaluate => false;
|
||||
|
||||
public CacheMethod (MethodInfo mi)
|
||||
{
|
||||
this.MethodInfo = mi;
|
||||
}
|
||||
|
||||
public override void SetInspectorOwner(ReflectionInspector inspector, MemberInfo member)
|
||||
{
|
||||
base.SetInspectorOwner(inspector, member);
|
||||
|
||||
Arguments = MethodInfo.GetParameters();
|
||||
if (MethodInfo.IsGenericMethod)
|
||||
GenericArguments = MethodInfo.GetGenericArguments();
|
||||
}
|
||||
|
||||
protected override object TryEvaluate()
|
||||
{
|
||||
try
|
||||
{
|
||||
var methodInfo = MethodInfo;
|
||||
if (methodInfo.IsGenericMethod)
|
||||
methodInfo = MethodInfo.MakeGenericMethod(Evaluator.TryParseGenericArguments());
|
||||
|
||||
object ret;
|
||||
if (HasArguments)
|
||||
ret = methodInfo.Invoke(DeclaringInstance, Evaluator.TryParseArguments());
|
||||
else
|
||||
ret = methodInfo.Invoke(DeclaringInstance, ArgumentUtility.EmptyArgs);
|
||||
HadException = false;
|
||||
LastException = null;
|
||||
return ret;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HadException = true;
|
||||
LastException = ex;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void TrySetValue(object value) => throw new NotImplementedException("You can't set a method");
|
||||
}
|
||||
}
|
494
src/CacheObject/CacheObjectBase.cs
Normal file
494
src/CacheObject/CacheObjectBase.cs
Normal file
@ -0,0 +1,494 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.Runtime;
|
||||
using UnityExplorer.CacheObject.IValues;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
using UniverseLib.UI.Models;
|
||||
using UnityExplorer.UI;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.Utility;
|
||||
using UniverseLib.UI.ObjectPool;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public enum ValueState
|
||||
{
|
||||
NotEvaluated,
|
||||
Exception,
|
||||
Boolean,
|
||||
Number,
|
||||
String,
|
||||
Enum,
|
||||
Collection,
|
||||
Dictionary,
|
||||
ValueStruct,
|
||||
Color,
|
||||
Unsupported
|
||||
}
|
||||
|
||||
public abstract class CacheObjectBase
|
||||
{
|
||||
public ICacheObjectController Owner { get; set; }
|
||||
|
||||
public CacheObjectCell CellView { get; internal set; }
|
||||
|
||||
public object Value { get; protected set; }
|
||||
public Type FallbackType { get; protected set; }
|
||||
public bool LastValueWasNull { get; private set; }
|
||||
|
||||
public ValueState State = ValueState.NotEvaluated;
|
||||
public Type LastValueType;
|
||||
|
||||
public InteractiveValue IValue { get; private set; }
|
||||
public Type CurrentIValueType { get; private set; }
|
||||
public bool SubContentShowWanted { get; private set; }
|
||||
|
||||
public string NameLabelText { get; protected set; }
|
||||
public string NameLabelTextRaw { get; protected set; }
|
||||
public string ValueLabelText { get; protected set; }
|
||||
|
||||
public abstract bool ShouldAutoEvaluate { get; }
|
||||
public abstract bool HasArguments { get; }
|
||||
public abstract bool CanWrite { get; }
|
||||
public bool HadException { get; protected set; }
|
||||
public Exception LastException { get; protected set; }
|
||||
|
||||
public virtual void SetFallbackType(Type fallbackType)
|
||||
{
|
||||
this.FallbackType = fallbackType;
|
||||
this.ValueLabelText = GetValueLabel();
|
||||
}
|
||||
|
||||
protected const string NOT_YET_EVAL = "<color=grey>Not yet evaluated</color>";
|
||||
|
||||
public virtual void ReleasePooledObjects()
|
||||
{
|
||||
if (this.IValue != null)
|
||||
ReleaseIValue();
|
||||
|
||||
if (this.CellView != null)
|
||||
UnlinkFromView();
|
||||
}
|
||||
|
||||
public virtual void SetView(CacheObjectCell cellView)
|
||||
{
|
||||
this.CellView = cellView;
|
||||
cellView.Occupant = this;
|
||||
}
|
||||
|
||||
public virtual void UnlinkFromView()
|
||||
{
|
||||
if (this.CellView == null)
|
||||
return;
|
||||
|
||||
this.CellView.Occupant = null;
|
||||
this.CellView = null;
|
||||
|
||||
if (this.IValue != null)
|
||||
this.IValue.UIRoot.transform.SetParent(InactiveIValueHolder.transform, false);
|
||||
}
|
||||
|
||||
// Updating and applying values
|
||||
|
||||
public void SetUserValue(object value)
|
||||
{
|
||||
value = value.TryCast(FallbackType);
|
||||
|
||||
TrySetUserValue(value);
|
||||
|
||||
if (CellView != null)
|
||||
SetDataToCell(CellView);
|
||||
|
||||
// If the owner's parent CacheObject is set, we are setting the value of an inspected struct.
|
||||
// Set the inspector target as the value back to that parent cacheobject.
|
||||
if (Owner.ParentCacheObject != null)
|
||||
Owner.ParentCacheObject.SetUserValue(Owner.Target);
|
||||
}
|
||||
|
||||
public abstract void TrySetUserValue(object value);
|
||||
|
||||
// The only method which sets the CacheObjectBase.Value
|
||||
public virtual void SetValueFromSource(object value)
|
||||
{
|
||||
this.Value = value;
|
||||
|
||||
if (!Value.IsNullOrDestroyed())
|
||||
Value = Value.TryCast();
|
||||
|
||||
ProcessOnEvaluate();
|
||||
|
||||
if (this.IValue != null)
|
||||
{
|
||||
if (SubContentShowWanted)
|
||||
this.IValue.SetValue(Value);
|
||||
else
|
||||
IValue.PendingValueWanted = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void ProcessOnEvaluate()
|
||||
{
|
||||
var prevState = State;
|
||||
|
||||
if (HadException)
|
||||
{
|
||||
LastValueWasNull = true;
|
||||
LastValueType = FallbackType;
|
||||
State = ValueState.Exception;
|
||||
}
|
||||
else if (Value.IsNullOrDestroyed())
|
||||
{
|
||||
LastValueWasNull = true;
|
||||
State = GetStateForType(FallbackType);
|
||||
}
|
||||
else
|
||||
{
|
||||
LastValueWasNull = false;
|
||||
State = GetStateForType(Value.GetActualType());
|
||||
}
|
||||
|
||||
if (IValue != null)
|
||||
{
|
||||
// If we changed states (always needs IValue change)
|
||||
// or if the value is null, and the fallback type isnt string (we always want to edit strings).
|
||||
if (State != prevState || (State != ValueState.String && Value.IsNullOrDestroyed()))
|
||||
{
|
||||
// need to return IValue
|
||||
ReleaseIValue();
|
||||
SubContentShowWanted = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Set label text
|
||||
this.ValueLabelText = GetValueLabel();
|
||||
}
|
||||
|
||||
public ValueState GetStateForType(Type type)
|
||||
{
|
||||
if (LastValueType == type)
|
||||
return State;
|
||||
|
||||
LastValueType = type;
|
||||
if (type == typeof(bool))
|
||||
return ValueState.Boolean;
|
||||
else if (type.IsPrimitive || type == typeof(decimal))
|
||||
return ValueState.Number;
|
||||
else if (type == typeof(string))
|
||||
return ValueState.String;
|
||||
else if (type.IsEnum)
|
||||
return ValueState.Enum;
|
||||
else if (type == typeof(Color) || type == typeof(Color32))
|
||||
return ValueState.Color;
|
||||
else if (InteractiveValueStruct.SupportsType(type))
|
||||
return ValueState.ValueStruct;
|
||||
else if (ReflectionUtility.IsDictionary(type))
|
||||
return ValueState.Dictionary;
|
||||
else if (!typeof(Transform).IsAssignableFrom(type) && ReflectionUtility.IsEnumerable(type))
|
||||
return ValueState.Collection;
|
||||
else
|
||||
return ValueState.Unsupported;
|
||||
}
|
||||
|
||||
protected string GetValueLabel()
|
||||
{
|
||||
string label = "";
|
||||
|
||||
switch (State)
|
||||
{
|
||||
case ValueState.NotEvaluated:
|
||||
return $"<i>{NOT_YET_EVAL} ({SignatureHighlighter.Parse(FallbackType, true)})</i>";
|
||||
|
||||
case ValueState.Exception:
|
||||
return $"<i><color=red>{LastException.ReflectionExToString()}</color></i>";
|
||||
|
||||
// bool and number dont want the label for the value at all
|
||||
case ValueState.Boolean:
|
||||
case ValueState.Number:
|
||||
return null;
|
||||
|
||||
// and valuestruct also doesnt want it if we can parse it
|
||||
case ValueState.ValueStruct:
|
||||
if (ParseUtility.CanParse(LastValueType))
|
||||
return null;
|
||||
break;
|
||||
|
||||
// string wants it trimmed to max 200 chars
|
||||
case ValueState.String:
|
||||
if (!LastValueWasNull)
|
||||
return $"\"{ToStringUtility.PruneString(Value as string, 200, 5)}\"";
|
||||
break;
|
||||
|
||||
// try to prefix the count of the collection for lists and dicts
|
||||
case ValueState.Collection:
|
||||
if (!LastValueWasNull)
|
||||
{
|
||||
if (Value is IList iList)
|
||||
label = $"[{iList.Count}] ";
|
||||
else if (Value is ICollection iCol)
|
||||
label = $"[{iCol.Count}] ";
|
||||
else
|
||||
label = "[?] ";
|
||||
}
|
||||
break;
|
||||
|
||||
case ValueState.Dictionary:
|
||||
if (!LastValueWasNull)
|
||||
{
|
||||
if (Value is IDictionary iDict)
|
||||
label = $"[{iDict.Count}] ";
|
||||
else
|
||||
label = "[?] ";
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Cases which dont return will append to ToStringWithType
|
||||
|
||||
return label += ToStringUtility.ToStringWithType(Value, FallbackType, true);
|
||||
}
|
||||
|
||||
// Setting cell state from our model
|
||||
|
||||
/// <summary>Return false if SetCell should abort, true if it should continue.</summary>
|
||||
protected abstract bool TryAutoEvaluateIfUnitialized(CacheObjectCell cell);
|
||||
|
||||
public virtual void SetDataToCell(CacheObjectCell cell)
|
||||
{
|
||||
cell.NameLabel.text = NameLabelText;
|
||||
if (cell.HiddenNameLabel != null)
|
||||
cell.HiddenNameLabel.Text = NameLabelTextRaw ?? string.Empty;
|
||||
cell.ValueLabel.gameObject.SetActive(true);
|
||||
|
||||
cell.SubContentHolder.gameObject.SetActive(SubContentShowWanted);
|
||||
if (IValue != null)
|
||||
{
|
||||
IValue.UIRoot.transform.SetParent(cell.SubContentHolder.transform, false);
|
||||
IValue.SetLayout();
|
||||
}
|
||||
|
||||
bool evaluated = TryAutoEvaluateIfUnitialized(cell);
|
||||
|
||||
if (cell.CopyButton != null)
|
||||
{
|
||||
bool hasEvaluated = State != ValueState.NotEvaluated && State != ValueState.Exception;
|
||||
cell.CopyButton.Component.gameObject.SetActive(hasEvaluated);
|
||||
cell.PasteButton.Component.gameObject.SetActive(hasEvaluated && this.CanWrite);
|
||||
}
|
||||
|
||||
if (!evaluated)
|
||||
return;
|
||||
|
||||
// The following only executes if the object has evaluated.
|
||||
// For members and properties with args, they will return by default now.
|
||||
|
||||
switch (State)
|
||||
{
|
||||
case ValueState.Exception:
|
||||
SetValueState(cell, ValueStateArgs.Default);
|
||||
break;
|
||||
case ValueState.Boolean:
|
||||
SetValueState(cell, new ValueStateArgs(false, toggleActive: true, applyActive: CanWrite));
|
||||
break;
|
||||
case ValueState.Number:
|
||||
SetValueState(cell, new ValueStateArgs(false, typeLabelActive: true, inputActive: true, applyActive: CanWrite));
|
||||
break;
|
||||
case ValueState.String:
|
||||
if (LastValueWasNull)
|
||||
SetValueState(cell, new ValueStateArgs(true, subContentButtonActive: true));
|
||||
else
|
||||
SetValueState(cell, new ValueStateArgs(true, false, SignatureHighlighter.StringOrange, subContentButtonActive: true));
|
||||
break;
|
||||
case ValueState.Enum:
|
||||
SetValueState(cell, new ValueStateArgs(true, subContentButtonActive: CanWrite));
|
||||
break;
|
||||
case ValueState.Color:
|
||||
case ValueState.ValueStruct:
|
||||
if (ParseUtility.CanParse(LastValueType))
|
||||
SetValueState(cell, new ValueStateArgs(false, false, null, true, false, true, CanWrite, true, true));
|
||||
else
|
||||
SetValueState(cell, new ValueStateArgs(true, inspectActive: true, subContentButtonActive: true));
|
||||
break;
|
||||
case ValueState.Collection:
|
||||
case ValueState.Dictionary:
|
||||
SetValueState(cell, new ValueStateArgs(true, inspectActive: !LastValueWasNull, subContentButtonActive: !LastValueWasNull));
|
||||
break;
|
||||
case ValueState.Unsupported:
|
||||
SetValueState(cell, new ValueStateArgs(true, inspectActive: !LastValueWasNull));
|
||||
break;
|
||||
}
|
||||
|
||||
cell.RefreshSubcontentButton();
|
||||
}
|
||||
|
||||
protected virtual void SetValueState(CacheObjectCell cell, ValueStateArgs args)
|
||||
{
|
||||
// main value label
|
||||
if (args.valueActive)
|
||||
{
|
||||
cell.ValueLabel.text = ValueLabelText;
|
||||
cell.ValueLabel.supportRichText = args.valueRichText;
|
||||
cell.ValueLabel.color = args.valueColor;
|
||||
}
|
||||
else
|
||||
cell.ValueLabel.text = "";
|
||||
|
||||
// Type label (for primitives)
|
||||
cell.TypeLabel.gameObject.SetActive(args.typeLabelActive);
|
||||
if (args.typeLabelActive)
|
||||
cell.TypeLabel.text = SignatureHighlighter.Parse(LastValueType, false);
|
||||
|
||||
// toggle for bools
|
||||
cell.Toggle.gameObject.SetActive(args.toggleActive);
|
||||
if (args.toggleActive)
|
||||
{
|
||||
cell.Toggle.interactable = CanWrite;
|
||||
cell.Toggle.isOn = (bool)Value;
|
||||
cell.ToggleText.text = Value.ToString();
|
||||
}
|
||||
|
||||
// inputfield for numbers
|
||||
cell.InputField.UIRoot.SetActive(args.inputActive);
|
||||
if (args.inputActive)
|
||||
{
|
||||
cell.InputField.Text = ParseUtility.ToStringForInput(Value, LastValueType);
|
||||
cell.InputField.Component.readOnly = !CanWrite;
|
||||
}
|
||||
|
||||
// apply for bool and numbers
|
||||
cell.ApplyButton.Component.gameObject.SetActive(args.applyActive);
|
||||
|
||||
// Inspect button only if last value not null.
|
||||
if (cell.InspectButton != null)
|
||||
cell.InspectButton.Component.gameObject.SetActive(args.inspectActive && !LastValueWasNull);
|
||||
|
||||
// allow IValue for null strings though
|
||||
cell.SubContentButton.Component.gameObject.SetActive(args.subContentButtonActive && (!LastValueWasNull || State == ValueState.String));
|
||||
}
|
||||
|
||||
// CacheObjectCell Apply
|
||||
|
||||
public virtual void OnCellApplyClicked()
|
||||
{
|
||||
if (State == ValueState.Boolean)
|
||||
SetUserValue(this.CellView.Toggle.isOn);
|
||||
else
|
||||
{
|
||||
if (ParseUtility.TryParse(CellView.InputField.Text, LastValueType, out object value, out Exception ex))
|
||||
{
|
||||
SetUserValue(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
ExplorerCore.LogWarning("Unable to parse input!");
|
||||
if (ex != null)
|
||||
ExplorerCore.Log(ex.ReflectionExToString());
|
||||
}
|
||||
}
|
||||
|
||||
SetDataToCell(this.CellView);
|
||||
}
|
||||
|
||||
// IValues
|
||||
|
||||
public virtual void OnCellSubContentToggle()
|
||||
{
|
||||
if (this.IValue == null)
|
||||
{
|
||||
var ivalueType = InteractiveValue.GetIValueTypeForState(State);
|
||||
|
||||
if (ivalueType == null)
|
||||
return;
|
||||
|
||||
IValue = (InteractiveValue)Pool.Borrow(ivalueType);
|
||||
CurrentIValueType = ivalueType;
|
||||
|
||||
IValue.OnBorrowed(this);
|
||||
IValue.SetValue(this.Value);
|
||||
IValue.UIRoot.transform.SetParent(CellView.SubContentHolder.transform, false);
|
||||
CellView.SubContentHolder.SetActive(true);
|
||||
SubContentShowWanted = true;
|
||||
|
||||
// update our cell after creating the ivalue (the value may have updated, make sure its consistent)
|
||||
this.ProcessOnEvaluate();
|
||||
this.SetDataToCell(this.CellView);
|
||||
}
|
||||
else
|
||||
{
|
||||
SubContentShowWanted = !SubContentShowWanted;
|
||||
CellView.SubContentHolder.SetActive(SubContentShowWanted);
|
||||
|
||||
if (SubContentShowWanted && IValue.PendingValueWanted)
|
||||
{
|
||||
IValue.PendingValueWanted = false;
|
||||
this.ProcessOnEvaluate();
|
||||
this.SetDataToCell(this.CellView);
|
||||
IValue.SetValue(this.Value);
|
||||
}
|
||||
}
|
||||
|
||||
CellView.RefreshSubcontentButton();
|
||||
}
|
||||
|
||||
public virtual void ReleaseIValue()
|
||||
{
|
||||
if (IValue == null)
|
||||
return;
|
||||
|
||||
IValue.ReleaseFromOwner();
|
||||
Pool.Return(CurrentIValueType, IValue);
|
||||
|
||||
IValue = null;
|
||||
}
|
||||
|
||||
internal static GameObject InactiveIValueHolder
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!inactiveIValueHolder)
|
||||
{
|
||||
inactiveIValueHolder = new GameObject("Temp_IValue_Holder");
|
||||
GameObject.DontDestroyOnLoad(inactiveIValueHolder);
|
||||
inactiveIValueHolder.transform.parent = UniversalUI.PoolHolder.transform;
|
||||
inactiveIValueHolder.SetActive(false);
|
||||
}
|
||||
return inactiveIValueHolder;
|
||||
}
|
||||
}
|
||||
private static GameObject inactiveIValueHolder;
|
||||
|
||||
// Value state args helper
|
||||
|
||||
public struct ValueStateArgs
|
||||
{
|
||||
public ValueStateArgs(bool valueActive = true, bool valueRichText = true, Color? valueColor = null,
|
||||
bool typeLabelActive = false, bool toggleActive = false, bool inputActive = false, bool applyActive = false,
|
||||
bool inspectActive = false, bool subContentButtonActive = false)
|
||||
{
|
||||
this.valueActive = valueActive;
|
||||
this.valueRichText = valueRichText;
|
||||
this.valueColor = valueColor == null ? Color.white : (Color)valueColor;
|
||||
this.typeLabelActive = typeLabelActive;
|
||||
this.toggleActive = toggleActive;
|
||||
this.inputActive = inputActive;
|
||||
this.applyActive = applyActive;
|
||||
this.inspectActive = inspectActive;
|
||||
this.subContentButtonActive = subContentButtonActive;
|
||||
}
|
||||
|
||||
public static ValueStateArgs Default => _default;
|
||||
private static ValueStateArgs _default = new ValueStateArgs(true);
|
||||
|
||||
public bool valueActive, valueRichText, typeLabelActive, toggleActive,
|
||||
inputActive, applyActive, inspectActive, subContentButtonActive;
|
||||
|
||||
public Color valueColor;
|
||||
}
|
||||
}
|
||||
}
|
75
src/CacheObject/CacheProperty.cs
Normal file
75
src/CacheObject/CacheProperty.cs
Normal file
@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.Inspectors;
|
||||
using UnityExplorer.Runtime;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public class CacheProperty : CacheMember
|
||||
{
|
||||
public PropertyInfo PropertyInfo { get; internal set; }
|
||||
public override Type DeclaringType => PropertyInfo.DeclaringType;
|
||||
public override bool CanWrite => PropertyInfo.CanWrite;
|
||||
public override bool IsStatic => m_isStatic ?? (bool)(m_isStatic = PropertyInfo.GetAccessors(true)[0].IsStatic);
|
||||
private bool? m_isStatic;
|
||||
|
||||
public override bool ShouldAutoEvaluate => !HasArguments;
|
||||
|
||||
public CacheProperty(PropertyInfo pi)
|
||||
{
|
||||
this.PropertyInfo = pi;
|
||||
}
|
||||
|
||||
public override void SetInspectorOwner(ReflectionInspector inspector, MemberInfo member)
|
||||
{
|
||||
base.SetInspectorOwner(inspector, member);
|
||||
|
||||
Arguments = PropertyInfo.GetIndexParameters();
|
||||
}
|
||||
|
||||
protected override object TryEvaluate()
|
||||
{
|
||||
try
|
||||
{
|
||||
object ret;
|
||||
if (HasArguments)
|
||||
ret = PropertyInfo.GetValue(DeclaringInstance, this.Evaluator.TryParseArguments());
|
||||
else
|
||||
ret = PropertyInfo.GetValue(DeclaringInstance, null);
|
||||
HadException = false;
|
||||
LastException = null;
|
||||
return ret;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HadException = true;
|
||||
LastException = ex;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void TrySetValue(object value)
|
||||
{
|
||||
if (!CanWrite)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
bool _static = PropertyInfo.GetAccessors(true)[0].IsStatic;
|
||||
|
||||
if (HasArguments)
|
||||
PropertyInfo.SetValue(DeclaringInstance, value, Evaluator.TryParseArguments());
|
||||
else
|
||||
PropertyInfo.SetValue(DeclaringInstance, value, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
52
src/CacheObject/ICacheObjectController.cs
Normal file
52
src/CacheObject/ICacheObjectController.cs
Normal file
@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
|
||||
namespace UnityExplorer.CacheObject
|
||||
{
|
||||
public interface ICacheObjectController
|
||||
{
|
||||
CacheObjectBase ParentCacheObject { get; }
|
||||
|
||||
object Target { get; }
|
||||
Type TargetType { get; }
|
||||
|
||||
bool CanWrite { get; }
|
||||
}
|
||||
|
||||
public static class CacheObjectControllerHelper
|
||||
{
|
||||
// Helper so that this doesn't need to be copy+pasted between each implementation of the interface
|
||||
|
||||
public static void SetCell(CacheObjectCell cell, int index, IList cachedEntries, Action<CacheObjectCell> onDataSetToCell)
|
||||
{
|
||||
if (index < 0 || index >= cachedEntries.Count)
|
||||
{
|
||||
if (cell.Occupant != null)
|
||||
cell.Occupant.UnlinkFromView();
|
||||
|
||||
cell.Disable();
|
||||
return;
|
||||
}
|
||||
|
||||
var entry = (CacheObjectBase)cachedEntries[index];
|
||||
|
||||
if (entry.CellView != null && entry.CellView != cell)
|
||||
entry.UnlinkFromView();
|
||||
|
||||
if (cell.Occupant != null && cell.Occupant != entry)
|
||||
cell.Occupant.UnlinkFromView();
|
||||
|
||||
if (entry.CellView != cell)
|
||||
entry.SetView(cell);
|
||||
|
||||
entry.SetDataToCell(cell);
|
||||
|
||||
onDataSetToCell?.Invoke(cell);
|
||||
}
|
||||
}
|
||||
}
|
206
src/CacheObject/IValues/InteractiveColor.cs
Normal file
206
src/CacheObject/IValues/InteractiveColor.cs
Normal file
@ -0,0 +1,206 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.UI;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib;
|
||||
|
||||
namespace UnityExplorer.CacheObject.IValues
|
||||
{
|
||||
public class InteractiveColor : InteractiveValue
|
||||
{
|
||||
public bool IsValueColor32;
|
||||
|
||||
public Color EditedColor;
|
||||
|
||||
private Image colorImage;
|
||||
private readonly InputFieldRef[] inputs = new InputFieldRef[4];
|
||||
private readonly Slider[] sliders = new Slider[4];
|
||||
|
||||
private ButtonRef applyButton;
|
||||
|
||||
private static readonly string[] fieldNames = new[] { "R", "G", "B", "A" };
|
||||
|
||||
public override void OnBorrowed(CacheObjectBase owner)
|
||||
{
|
||||
base.OnBorrowed(owner);
|
||||
|
||||
applyButton.Component.gameObject.SetActive(owner.CanWrite);
|
||||
|
||||
foreach (var slider in sliders)
|
||||
slider.interactable = owner.CanWrite;
|
||||
foreach (var input in inputs)
|
||||
input.Component.readOnly = !owner.CanWrite;
|
||||
}
|
||||
|
||||
// owner setting value to this
|
||||
public override void SetValue(object value)
|
||||
{
|
||||
OnOwnerSetValue(value);
|
||||
}
|
||||
|
||||
private void OnOwnerSetValue(object value)
|
||||
{
|
||||
if (value is Color32 c32)
|
||||
{
|
||||
IsValueColor32 = true;
|
||||
EditedColor = c32;
|
||||
inputs[0].Text = c32.r.ToString();
|
||||
inputs[1].Text = c32.g.ToString();
|
||||
inputs[2].Text = c32.b.ToString();
|
||||
inputs[3].Text = c32.a.ToString();
|
||||
foreach (var slider in sliders)
|
||||
slider.maxValue = 255;
|
||||
}
|
||||
else
|
||||
{
|
||||
IsValueColor32 = false;
|
||||
EditedColor = (Color)value;
|
||||
inputs[0].Text = EditedColor.r.ToString();
|
||||
inputs[1].Text = EditedColor.g.ToString();
|
||||
inputs[2].Text = EditedColor.b.ToString();
|
||||
inputs[3].Text = EditedColor.a.ToString();
|
||||
foreach (var slider in sliders)
|
||||
slider.maxValue = 1;
|
||||
}
|
||||
|
||||
if (colorImage)
|
||||
colorImage.color = EditedColor;
|
||||
}
|
||||
|
||||
// setting value to owner
|
||||
|
||||
public void SetValueToOwner()
|
||||
{
|
||||
if (IsValueColor32)
|
||||
CurrentOwner.SetUserValue((Color32)EditedColor);
|
||||
else
|
||||
CurrentOwner.SetUserValue(EditedColor);
|
||||
}
|
||||
|
||||
private void SetColorField(float val, int fieldIndex)
|
||||
{
|
||||
switch (fieldIndex)
|
||||
{
|
||||
case 0: EditedColor.r = val; break;
|
||||
case 1: EditedColor.g = val; break;
|
||||
case 2: EditedColor.b = val; break;
|
||||
case 3: EditedColor.a = val; break;
|
||||
}
|
||||
|
||||
if (colorImage)
|
||||
colorImage.color = EditedColor;
|
||||
}
|
||||
|
||||
private void OnInputChanged(string val, int fieldIndex)
|
||||
{
|
||||
try
|
||||
{
|
||||
float f;
|
||||
if (IsValueColor32)
|
||||
{
|
||||
byte value = byte.Parse(val);
|
||||
sliders[fieldIndex].value = value;
|
||||
f = (float)((decimal)value / 255);
|
||||
}
|
||||
else
|
||||
{
|
||||
f = float.Parse(val);
|
||||
sliders[fieldIndex].value = f;
|
||||
}
|
||||
|
||||
SetColorField(f, fieldIndex);
|
||||
}
|
||||
catch (ArgumentException) { } // ignore bad user input
|
||||
catch (FormatException) { }
|
||||
catch (OverflowException) { }
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning("InteractiveColor OnInput: " + ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSliderValueChanged(float val, int fieldIndex)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (IsValueColor32)
|
||||
{
|
||||
inputs[fieldIndex].Text = ((byte)val).ToString();
|
||||
val /= 255f;
|
||||
}
|
||||
else
|
||||
{
|
||||
inputs[fieldIndex].Text = val.ToString();
|
||||
}
|
||||
|
||||
SetColorField(val, fieldIndex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning("InteractiveColor OnSlider: " + ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// UI Construction
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
UIRoot = UIFactory.CreateVerticalGroup(parent, "InteractiveColor", false, false, true, true, 3, new Vector4(4, 4, 4, 4),
|
||||
new Color(0.06f, 0.06f, 0.06f));
|
||||
|
||||
// hori group
|
||||
|
||||
var horiGroup = UIFactory.CreateHorizontalGroup(UIRoot, "ColorEditor", false, false, true, true, 5,
|
||||
default, new Color(1, 1, 1, 0), TextAnchor.MiddleLeft);
|
||||
|
||||
// sliders / inputs
|
||||
|
||||
var grid = UIFactory.CreateGridGroup(horiGroup, "Grid", new Vector2(140, 25), new Vector2(2, 2), new Color(1, 1, 1, 0));
|
||||
UIFactory.SetLayoutElement(grid, minWidth: 580, minHeight: 25, flexibleWidth: 0);
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
AddEditorRow(i, grid);
|
||||
|
||||
// apply button
|
||||
|
||||
applyButton = UIFactory.CreateButton(horiGroup, "ApplyButton", "Apply", new Color(0.2f, 0.26f, 0.2f));
|
||||
UIFactory.SetLayoutElement(applyButton.Component.gameObject, minHeight: 25, minWidth: 90);
|
||||
applyButton.OnClick += SetValueToOwner;
|
||||
|
||||
// image of color
|
||||
|
||||
var imgObj = UIFactory.CreateUIObject("ColorImageHelper", horiGroup);
|
||||
UIFactory.SetLayoutElement(imgObj, minHeight: 25, minWidth: 50, flexibleWidth: 50);
|
||||
colorImage = imgObj.AddComponent<Image>();
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
|
||||
internal void AddEditorRow(int index, GameObject groupObj)
|
||||
{
|
||||
var row = UIFactory.CreateHorizontalGroup(groupObj, "EditorRow_" + fieldNames[index],
|
||||
false, true, true, true, 5, default, new Color(1, 1, 1, 0));
|
||||
|
||||
var label = UIFactory.CreateLabel(row, "RowLabel", $"{fieldNames[index]}:", TextAnchor.MiddleRight, Color.cyan);
|
||||
UIFactory.SetLayoutElement(label.gameObject, minWidth: 17, flexibleWidth: 0, minHeight: 25);
|
||||
|
||||
var input = UIFactory.CreateInputField(row, "Input", "...");
|
||||
UIFactory.SetLayoutElement(input.UIRoot, minWidth: 40, minHeight: 25, flexibleHeight: 0);
|
||||
inputs[index] = input;
|
||||
input.OnValueChanged += (string val) => { OnInputChanged(val, index); };
|
||||
|
||||
var sliderObj = UIFactory.CreateSlider(row, "Slider", out Slider slider);
|
||||
sliders[index] = slider;
|
||||
UIFactory.SetLayoutElement(sliderObj, minHeight: 25, minWidth: 70, flexibleWidth: 999, flexibleHeight: 0);
|
||||
slider.minValue = 0;
|
||||
slider.maxValue = 1;
|
||||
slider.onValueChanged.AddListener((float val) => { OnSliderValueChanged(val, index); });
|
||||
}
|
||||
}
|
||||
}
|
254
src/CacheObject/IValues/InteractiveDictionary.cs
Normal file
254
src/CacheObject/IValues/InteractiveDictionary.cs
Normal file
@ -0,0 +1,254 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
using UnityExplorer.Inspectors;
|
||||
using UnityExplorer.UI;
|
||||
using UnityExplorer.UI.Panels;
|
||||
using UnityExplorer.UI.Widgets;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Widgets;
|
||||
using UniverseLib.UI.Widgets.ScrollView;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject.IValues
|
||||
{
|
||||
public class InteractiveDictionary : InteractiveValue, ICellPoolDataSource<CacheKeyValuePairCell>, ICacheObjectController
|
||||
{
|
||||
CacheObjectBase ICacheObjectController.ParentCacheObject => this.CurrentOwner;
|
||||
object ICacheObjectController.Target => this.CurrentOwner.Value;
|
||||
public Type TargetType { get; private set; }
|
||||
|
||||
public override bool CanWrite => base.CanWrite && RefIDictionary != null && !RefIDictionary.IsReadOnly;
|
||||
|
||||
public Type KeysType;
|
||||
public Type ValuesType;
|
||||
public IDictionary RefIDictionary;
|
||||
|
||||
public int ItemCount => cachedEntries.Count;
|
||||
private readonly List<CacheKeyValuePair> cachedEntries = new List<CacheKeyValuePair>();
|
||||
|
||||
public ScrollPool<CacheKeyValuePairCell> DictScrollPool { get; private set; }
|
||||
|
||||
private Text NotSupportedLabel;
|
||||
|
||||
public Text TopLabel;
|
||||
|
||||
public LayoutElement KeyTitleLayout;
|
||||
public LayoutElement ValueTitleLayout;
|
||||
|
||||
public override void OnBorrowed(CacheObjectBase owner)
|
||||
{
|
||||
base.OnBorrowed(owner);
|
||||
|
||||
DictScrollPool.Refresh(true, true);
|
||||
}
|
||||
|
||||
public override void ReleaseFromOwner()
|
||||
{
|
||||
base.ReleaseFromOwner();
|
||||
|
||||
ClearAndRelease();
|
||||
}
|
||||
|
||||
private void ClearAndRelease()
|
||||
{
|
||||
RefIDictionary = null;
|
||||
|
||||
foreach (var entry in cachedEntries)
|
||||
{
|
||||
entry.UnlinkFromView();
|
||||
entry.ReleasePooledObjects();
|
||||
}
|
||||
|
||||
cachedEntries.Clear();
|
||||
}
|
||||
|
||||
public override void SetValue(object value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
// should never be null
|
||||
ClearAndRelease();
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
var type = value.GetActualType();
|
||||
ReflectionUtility.TryGetEntryTypes(type, out KeysType, out ValuesType);
|
||||
|
||||
CacheEntries(value);
|
||||
|
||||
TopLabel.text = $"[{cachedEntries.Count}] {SignatureHighlighter.Parse(type, false)}";
|
||||
}
|
||||
|
||||
this.DictScrollPool.Refresh(true, false);
|
||||
}
|
||||
|
||||
private void CacheEntries(object value)
|
||||
{
|
||||
RefIDictionary = value as IDictionary;
|
||||
|
||||
if (ReflectionUtility.TryGetDictEnumerator(value, out IEnumerator<DictionaryEntry> dictEnumerator))
|
||||
{
|
||||
NotSupportedLabel.gameObject.SetActive(false);
|
||||
|
||||
int idx = 0;
|
||||
while (dictEnumerator.MoveNext())
|
||||
{
|
||||
CacheKeyValuePair cache;
|
||||
if (idx >= cachedEntries.Count)
|
||||
{
|
||||
cache = new CacheKeyValuePair();
|
||||
cache.SetDictOwner(this, idx);
|
||||
cachedEntries.Add(cache);
|
||||
}
|
||||
else
|
||||
cache = cachedEntries[idx];
|
||||
|
||||
cache.SetFallbackType(ValuesType);
|
||||
cache.SetKey(dictEnumerator.Current.Key);
|
||||
cache.SetValueFromSource(dictEnumerator.Current.Value);
|
||||
|
||||
idx++;
|
||||
}
|
||||
|
||||
// Remove excess cached entries if dict count decreased
|
||||
if (cachedEntries.Count > idx)
|
||||
{
|
||||
for (int i = cachedEntries.Count - 1; i >= idx; i--)
|
||||
{
|
||||
var cache = cachedEntries[i];
|
||||
if (cache.CellView != null)
|
||||
cache.UnlinkFromView();
|
||||
|
||||
cache.ReleasePooledObjects();
|
||||
cachedEntries.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NotSupportedLabel.gameObject.SetActive(true);
|
||||
}
|
||||
}
|
||||
|
||||
// Setting value to dictionary
|
||||
|
||||
public void TrySetValueToKey(object key, object value, int keyIndex)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!RefIDictionary.Contains(key))
|
||||
{
|
||||
ExplorerCore.LogWarning("Unable to set key! Key may have been boxed to/from Il2Cpp Object.");
|
||||
return;
|
||||
}
|
||||
|
||||
RefIDictionary[key] = value;
|
||||
|
||||
var entry = cachedEntries[keyIndex];
|
||||
entry.SetValueFromSource(value);
|
||||
if (entry.CellView != null)
|
||||
entry.SetDataToCell(entry.CellView);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Exception setting IDictionary key! {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
// KVP entry scroll pool
|
||||
|
||||
public void OnCellBorrowed(CacheKeyValuePairCell cell) { }
|
||||
|
||||
public void SetCell(CacheKeyValuePairCell cell, int index)
|
||||
{
|
||||
CacheObjectControllerHelper.SetCell(cell, index, cachedEntries, SetCellLayout);
|
||||
}
|
||||
|
||||
public int AdjustedWidth => (int)UIRect.rect.width - 80;
|
||||
|
||||
public override void SetLayout()
|
||||
{
|
||||
var minHeight = 5f;
|
||||
|
||||
KeyTitleLayout.minWidth = AdjustedWidth * 0.44f;
|
||||
ValueTitleLayout.minWidth = AdjustedWidth * 0.55f;
|
||||
|
||||
foreach (var cell in DictScrollPool.CellPool)
|
||||
{
|
||||
SetCellLayout(cell);
|
||||
if (cell.Enabled)
|
||||
minHeight += cell.Rect.rect.height;
|
||||
}
|
||||
|
||||
this.scrollLayout.minHeight = Math.Min(InspectorPanel.CurrentPanelHeight - 400f, minHeight);
|
||||
}
|
||||
|
||||
private void SetCellLayout(CacheObjectCell objcell)
|
||||
{
|
||||
var cell = objcell as CacheKeyValuePairCell;
|
||||
cell.KeyGroupLayout.minWidth = cell.AdjustedWidth * 0.44f;
|
||||
cell.RightGroupLayout.minWidth = cell.AdjustedWidth * 0.55f;
|
||||
|
||||
if (cell.Occupant?.IValue != null)
|
||||
cell.Occupant.IValue.SetLayout();
|
||||
}
|
||||
|
||||
private LayoutElement scrollLayout;
|
||||
private RectTransform UIRect;
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
UIRoot = UIFactory.CreateVerticalGroup(parent, "InteractiveDict", true, true, true, true, 6, new Vector4(10, 3, 15, 4),
|
||||
new Color(0.05f, 0.05f, 0.05f));
|
||||
UIFactory.SetLayoutElement(UIRoot, flexibleWidth: 9999, minHeight: 25, flexibleHeight: 475);
|
||||
UIRoot.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
|
||||
UIRect = UIRoot.GetComponent<RectTransform>();
|
||||
|
||||
// Entries label
|
||||
|
||||
TopLabel = UIFactory.CreateLabel(UIRoot, "EntryLabel", "not set", TextAnchor.MiddleLeft, fontSize: 16);
|
||||
TopLabel.horizontalOverflow = HorizontalWrapMode.Overflow;
|
||||
|
||||
// key / value titles
|
||||
|
||||
var titleGroup = UIFactory.CreateUIObject("TitleGroup", UIRoot);
|
||||
UIFactory.SetLayoutElement(titleGroup, minHeight: 25, flexibleWidth: 9999, flexibleHeight: 0);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(titleGroup, false, true, true, true, padLeft: 65, padRight: 0, childAlignment: TextAnchor.LowerLeft);
|
||||
|
||||
var keyTitle = UIFactory.CreateLabel(titleGroup, "KeyTitle", "Keys", TextAnchor.MiddleLeft);
|
||||
UIFactory.SetLayoutElement(keyTitle.gameObject, minWidth: 100, flexibleWidth: 0);
|
||||
KeyTitleLayout = keyTitle.GetComponent<LayoutElement>();
|
||||
|
||||
var valueTitle = UIFactory.CreateLabel(titleGroup, "ValueTitle", "Values", TextAnchor.MiddleLeft);
|
||||
UIFactory.SetLayoutElement(valueTitle.gameObject, minWidth: 100, flexibleWidth: 0);
|
||||
ValueTitleLayout = valueTitle.GetComponent<LayoutElement>();
|
||||
|
||||
// entry scroll pool
|
||||
|
||||
DictScrollPool = UIFactory.CreateScrollPool<CacheKeyValuePairCell>(UIRoot, "EntryList", out GameObject scrollObj,
|
||||
out GameObject _, new Color(0.09f, 0.09f, 0.09f));
|
||||
UIFactory.SetLayoutElement(scrollObj, minHeight: 150, flexibleHeight: 0);
|
||||
DictScrollPool.Initialize(this, SetLayout);
|
||||
scrollLayout = scrollObj.GetComponent<LayoutElement>();
|
||||
|
||||
NotSupportedLabel = UIFactory.CreateLabel(DictScrollPool.Content.gameObject, "NotSupportedMessage",
|
||||
"The IDictionary failed to enumerate. This is likely due to an issue with Unhollowed interfaces.",
|
||||
TextAnchor.MiddleLeft, Color.red);
|
||||
|
||||
UIFactory.SetLayoutElement(NotSupportedLabel.gameObject, minHeight: 25, flexibleWidth: 9999);
|
||||
NotSupportedLabel.gameObject.SetActive(false);
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
}
|
||||
}
|
253
src/CacheObject/IValues/InteractiveEnum.cs
Normal file
253
src/CacheObject/IValues/InteractiveEnum.cs
Normal file
@ -0,0 +1,253 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.UI;
|
||||
using UnityExplorer.UI.Widgets.AutoComplete;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject.IValues
|
||||
{
|
||||
public class InteractiveEnum : InteractiveValue
|
||||
{
|
||||
public bool IsFlags;
|
||||
public Type EnumType;
|
||||
|
||||
private Type lastType;
|
||||
|
||||
public OrderedDictionary CurrentValues;
|
||||
|
||||
private InputFieldRef inputField;
|
||||
private ButtonRef enumHelperButton;
|
||||
private EnumCompleter enumCompleter;
|
||||
|
||||
private GameObject toggleHolder;
|
||||
private readonly List<Toggle> flagToggles = new();
|
||||
private readonly List<Text> flagTexts = new();
|
||||
|
||||
public CachedEnumValue ValueAtIndex(int idx) => (CachedEnumValue)CurrentValues[idx];
|
||||
public CachedEnumValue ValueAtKey(object key) => (CachedEnumValue)CurrentValues[key];
|
||||
|
||||
// Setting value from owner
|
||||
public override void SetValue(object value)
|
||||
{
|
||||
EnumType = value.GetType();
|
||||
|
||||
if (lastType != EnumType)
|
||||
{
|
||||
CurrentValues = GetEnumValues(EnumType);
|
||||
|
||||
IsFlags = EnumType.GetCustomAttributes(typeof(FlagsAttribute), true) is object[] fa && fa.Any();
|
||||
if (IsFlags)
|
||||
SetupTogglesForEnumType();
|
||||
else
|
||||
{
|
||||
inputField.Component.gameObject.SetActive(true);
|
||||
enumHelperButton.Component.gameObject.SetActive(true);
|
||||
toggleHolder.SetActive(false);
|
||||
}
|
||||
|
||||
enumCompleter.EnumType = EnumType;
|
||||
enumCompleter.CacheEnumValues();
|
||||
|
||||
lastType = EnumType;
|
||||
}
|
||||
|
||||
if (!IsFlags)
|
||||
inputField.Text = value.ToString();
|
||||
else
|
||||
SetTogglesForValue(value);
|
||||
|
||||
this.enumCompleter.chosenSuggestion = value.ToString();
|
||||
AutoCompleteModal.Instance.ReleaseOwnership(this.enumCompleter);
|
||||
}
|
||||
|
||||
private void SetTogglesForValue(object value)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < CurrentValues.Count; i++)
|
||||
flagToggles[i].isOn = (value as Enum).HasFlag(ValueAtIndex(i).ActualValue as Enum);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning("Exception setting flag toggles: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
// Setting value to owner
|
||||
|
||||
private void OnApplyClicked()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsFlags)
|
||||
{
|
||||
if (ParseUtility.TryParse(this.inputField.Text, EnumType, out object value, out Exception ex))
|
||||
CurrentOwner.SetUserValue(value);
|
||||
else
|
||||
throw ex;
|
||||
}
|
||||
else
|
||||
{
|
||||
SetValueFromFlags();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning("Exception setting from dropdown: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetValueFromFlags()
|
||||
{
|
||||
try
|
||||
{
|
||||
List<string> values = new List<string>();
|
||||
for (int i = 0; i < CurrentValues.Count; i++)
|
||||
{
|
||||
if (flagToggles[i].isOn)
|
||||
values.Add(ValueAtIndex(i).Name);
|
||||
}
|
||||
|
||||
CurrentOwner.SetUserValue(Enum.Parse(EnumType, string.Join(", ", values.ToArray())));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning("Exception setting from flag toggles: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
// UI Construction
|
||||
|
||||
private void EnumHelper_OnClick()
|
||||
{
|
||||
enumCompleter.HelperButtonClicked();
|
||||
}
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
UIRoot = UIFactory.CreateVerticalGroup(parent, "InteractiveEnum", false, false, true, true, 3, new Vector4(4, 4, 4, 4),
|
||||
new Color(0.06f, 0.06f, 0.06f));
|
||||
UIFactory.SetLayoutElement(UIRoot, minHeight: 25, flexibleHeight: 9999, flexibleWidth: 9999);
|
||||
|
||||
var hori = UIFactory.CreateUIObject("Hori", UIRoot);
|
||||
UIFactory.SetLayoutElement(hori, minHeight: 25, flexibleWidth: 9999);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(hori, false, false, true, true, 2);
|
||||
|
||||
var applyButton = UIFactory.CreateButton(hori, "ApplyButton", "Apply", new Color(0.2f, 0.27f, 0.2f));
|
||||
UIFactory.SetLayoutElement(applyButton.Component.gameObject, minHeight: 25, minWidth: 100);
|
||||
applyButton.OnClick += OnApplyClicked;
|
||||
|
||||
inputField = UIFactory.CreateInputField(hori, "InputField", "Enter name or underlying value...");
|
||||
UIFactory.SetLayoutElement(inputField.UIRoot, minHeight: 25, flexibleHeight: 50, minWidth: 100, flexibleWidth: 1000);
|
||||
inputField.Component.lineType = InputField.LineType.MultiLineNewline;
|
||||
inputField.UIRoot.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
|
||||
enumHelperButton = UIFactory.CreateButton(hori, "EnumHelper", "▼");
|
||||
UIFactory.SetLayoutElement(enumHelperButton.Component.gameObject, minWidth: 25, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
|
||||
enumHelperButton.OnClick += EnumHelper_OnClick;
|
||||
|
||||
enumCompleter = new EnumCompleter(this.EnumType, this.inputField);
|
||||
|
||||
toggleHolder = UIFactory.CreateUIObject("ToggleHolder", UIRoot);
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(toggleHolder, false, false, true, true, 4);
|
||||
UIFactory.SetLayoutElement(toggleHolder, minHeight: 25, flexibleWidth: 9999, flexibleHeight: 9999);
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
|
||||
private void SetupTogglesForEnumType()
|
||||
{
|
||||
toggleHolder.SetActive(true);
|
||||
inputField.Component.gameObject.SetActive(false);
|
||||
enumHelperButton.Component.gameObject.SetActive(false);
|
||||
|
||||
// create / set / hide toggles
|
||||
for (int i = 0; i < CurrentValues.Count || i < flagToggles.Count; i++)
|
||||
{
|
||||
if (i >= CurrentValues.Count)
|
||||
{
|
||||
if (i >= flagToggles.Count)
|
||||
break;
|
||||
|
||||
flagToggles[i].gameObject.SetActive(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i >= flagToggles.Count)
|
||||
AddToggleRow();
|
||||
|
||||
flagToggles[i].isOn = false;
|
||||
flagTexts[i].text = ValueAtIndex(i).Name;
|
||||
}
|
||||
}
|
||||
|
||||
private void AddToggleRow()
|
||||
{
|
||||
var row = UIFactory.CreateUIObject("ToggleRow", toggleHolder);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(row, false, false, true, true, 2);
|
||||
UIFactory.SetLayoutElement(row, minHeight: 25, flexibleWidth: 9999);
|
||||
|
||||
var toggleObj = UIFactory.CreateToggle(row, "ToggleObj", out Toggle toggle, out Text toggleText);
|
||||
UIFactory.SetLayoutElement(toggleObj, minHeight: 25, flexibleWidth: 9999);
|
||||
|
||||
flagToggles.Add(toggle);
|
||||
flagTexts.Add(toggleText);
|
||||
}
|
||||
|
||||
#region Enum cache
|
||||
|
||||
internal static readonly Dictionary<string, OrderedDictionary> enumCache = new Dictionary<string, OrderedDictionary>();
|
||||
|
||||
internal static OrderedDictionary GetEnumValues(Type enumType)
|
||||
{
|
||||
//isFlags = enumType.GetCustomAttributes(typeof(FlagsAttribute), true) is object[] fa && fa.Any();
|
||||
|
||||
if (!enumCache.ContainsKey(enumType.AssemblyQualifiedName))
|
||||
{
|
||||
var dict = new OrderedDictionary();
|
||||
var addedNames = new HashSet<string>();
|
||||
|
||||
int i = 0;
|
||||
foreach (var value in Enum.GetValues(enumType))
|
||||
{
|
||||
var name = value.ToString();
|
||||
if (addedNames.Contains(name))
|
||||
continue;
|
||||
addedNames.Add(name);
|
||||
|
||||
dict.Add(value, new CachedEnumValue(value, i, name));
|
||||
i++;
|
||||
}
|
||||
|
||||
enumCache.Add(enumType.AssemblyQualifiedName, dict);
|
||||
}
|
||||
|
||||
return enumCache[enumType.AssemblyQualifiedName];
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
public struct CachedEnumValue
|
||||
{
|
||||
public CachedEnumValue(object value, int index, string name)
|
||||
{
|
||||
EnumIndex = index;
|
||||
Name = name;
|
||||
ActualValue = value;
|
||||
}
|
||||
|
||||
public readonly object ActualValue;
|
||||
public int EnumIndex;
|
||||
public readonly string Name;
|
||||
}
|
||||
}
|
271
src/CacheObject/IValues/InteractiveList.cs
Normal file
271
src/CacheObject/IValues/InteractiveList.cs
Normal file
@ -0,0 +1,271 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.CacheObject.Views;
|
||||
using UnityExplorer.Inspectors;
|
||||
using UnityExplorer.UI;
|
||||
using UnityExplorer.UI.Panels;
|
||||
using UnityExplorer.UI.Widgets;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Widgets;
|
||||
using UniverseLib.UI.Widgets.ScrollView;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject.IValues
|
||||
{
|
||||
public class InteractiveList : InteractiveValue, ICellPoolDataSource<CacheListEntryCell>, ICacheObjectController
|
||||
{
|
||||
CacheObjectBase ICacheObjectController.ParentCacheObject => this.CurrentOwner;
|
||||
object ICacheObjectController.Target => this.CurrentOwner.Value;
|
||||
public Type TargetType { get; private set; }
|
||||
|
||||
public override bool CanWrite => base.CanWrite && ((RefIList != null && !RefIList.IsReadOnly) || IsWritableGenericIList);
|
||||
|
||||
public Type EntryType;
|
||||
public IList RefIList;
|
||||
|
||||
private bool IsWritableGenericIList;
|
||||
private PropertyInfo genericIndexer;
|
||||
|
||||
public int ItemCount => cachedEntries.Count;
|
||||
private readonly List<CacheListEntry> cachedEntries = new();
|
||||
|
||||
public ScrollPool<CacheListEntryCell> ListScrollPool { get; private set; }
|
||||
|
||||
public Text TopLabel;
|
||||
private LayoutElement scrollLayout;
|
||||
private Text NotSupportedLabel;
|
||||
|
||||
public override void OnBorrowed(CacheObjectBase owner)
|
||||
{
|
||||
base.OnBorrowed(owner);
|
||||
|
||||
ListScrollPool.Refresh(true, true);
|
||||
}
|
||||
|
||||
public override void ReleaseFromOwner()
|
||||
{
|
||||
base.ReleaseFromOwner();
|
||||
|
||||
ClearAndRelease();
|
||||
}
|
||||
|
||||
private void ClearAndRelease()
|
||||
{
|
||||
RefIList = null;
|
||||
|
||||
foreach (var entry in cachedEntries)
|
||||
{
|
||||
entry.UnlinkFromView();
|
||||
entry.ReleasePooledObjects();
|
||||
}
|
||||
|
||||
cachedEntries.Clear();
|
||||
}
|
||||
|
||||
// List entry scroll pool
|
||||
|
||||
public override void SetLayout()
|
||||
{
|
||||
var minHeight = 5f;
|
||||
|
||||
foreach (var cell in ListScrollPool.CellPool)
|
||||
{
|
||||
if (cell.Enabled)
|
||||
minHeight += cell.Rect.rect.height;
|
||||
}
|
||||
|
||||
this.scrollLayout.minHeight = Math.Min(InspectorPanel.CurrentPanelHeight - 400f, minHeight);
|
||||
}
|
||||
|
||||
public void OnCellBorrowed(CacheListEntryCell cell) { } // not needed
|
||||
|
||||
public void SetCell(CacheListEntryCell cell, int index)
|
||||
{
|
||||
CacheObjectControllerHelper.SetCell(cell, index, cachedEntries, null);
|
||||
}
|
||||
|
||||
// Setting the List value itself to this model
|
||||
public override void SetValue(object value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
// should never be null
|
||||
if (cachedEntries.Any())
|
||||
ClearAndRelease();
|
||||
}
|
||||
else
|
||||
{
|
||||
var type = value.GetActualType();
|
||||
ReflectionUtility.TryGetEntryType(type, out EntryType);
|
||||
|
||||
CacheEntries(value);
|
||||
|
||||
TopLabel.text = $"[{cachedEntries.Count}] {SignatureHighlighter.Parse(type, false)}";
|
||||
}
|
||||
|
||||
//this.ScrollPoolLayout.minHeight = Math.Min(400f, 35f * values.Count);
|
||||
this.ListScrollPool.Refresh(true, false);
|
||||
}
|
||||
|
||||
private void CacheEntries(object value)
|
||||
{
|
||||
RefIList = value as IList;
|
||||
|
||||
// Check if the type implements IList<T> but not IList (ie. Il2CppArrayBase)
|
||||
if (RefIList == null)
|
||||
CheckGenericIList(value);
|
||||
else
|
||||
IsWritableGenericIList = false;
|
||||
|
||||
int idx = 0;
|
||||
|
||||
if (ReflectionUtility.TryGetEnumerator(value, out IEnumerator enumerator))
|
||||
{
|
||||
NotSupportedLabel.gameObject.SetActive(false);
|
||||
|
||||
while (enumerator.MoveNext())
|
||||
{
|
||||
var entry = enumerator.Current;
|
||||
|
||||
// If list count increased, create new cache entries
|
||||
CacheListEntry cache;
|
||||
if (idx >= cachedEntries.Count)
|
||||
{
|
||||
cache = new CacheListEntry();
|
||||
cache.SetListOwner(this, idx);
|
||||
cachedEntries.Add(cache);
|
||||
}
|
||||
else
|
||||
cache = cachedEntries[idx];
|
||||
|
||||
cache.SetFallbackType(this.EntryType);
|
||||
cache.SetValueFromSource(entry);
|
||||
idx++;
|
||||
}
|
||||
|
||||
// Remove excess cached entries if list count decreased
|
||||
if (cachedEntries.Count > idx)
|
||||
{
|
||||
for (int i = cachedEntries.Count - 1; i >= idx; i--)
|
||||
{
|
||||
var cache = cachedEntries[i];
|
||||
if (cache.CellView != null)
|
||||
cache.UnlinkFromView();
|
||||
|
||||
cache.ReleasePooledObjects();
|
||||
cachedEntries.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NotSupportedLabel.gameObject.SetActive(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckGenericIList(object value)
|
||||
{
|
||||
try
|
||||
{
|
||||
var type = value.GetType();
|
||||
if (type.GetInterfaces().Any(it => it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IList<>)))
|
||||
IsWritableGenericIList = !(bool)type.GetProperty("IsReadOnly").GetValue(value, null);
|
||||
else
|
||||
IsWritableGenericIList = false;
|
||||
|
||||
if (IsWritableGenericIList)
|
||||
{
|
||||
// Find the "this[int index]" property.
|
||||
// It might be a private implementation.
|
||||
foreach (var prop in type.GetProperties(ReflectionUtility.FLAGS))
|
||||
{
|
||||
if ((prop.Name == "Item"
|
||||
|| (prop.Name.StartsWith("System.Collections.Generic.IList<") && prop.Name.EndsWith(">.Item")))
|
||||
&& prop.GetIndexParameters() is ParameterInfo[] parameters
|
||||
&& parameters.Length == 1
|
||||
&& parameters[0].ParameterType == typeof(int))
|
||||
{
|
||||
genericIndexer = prop;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (genericIndexer == null)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Failed to find indexer property for IList<T> type '{type.FullName}'!");
|
||||
IsWritableGenericIList = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Exception processing IEnumerable for IList<T> check: {ex.ReflectionExToString()}");
|
||||
IsWritableGenericIList = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Setting the value of an index to the list
|
||||
|
||||
public void TrySetValueToIndex(object value, int index)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsWritableGenericIList)
|
||||
{
|
||||
RefIList[index] = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
genericIndexer.SetValue(CurrentOwner.Value, value, new object[] { index });
|
||||
}
|
||||
|
||||
var entry = cachedEntries[index];
|
||||
entry.SetValueFromSource(value);
|
||||
|
||||
if (entry.CellView != null)
|
||||
entry.SetDataToCell(entry.CellView);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning($"Exception setting IList value: {ex}");
|
||||
}
|
||||
}
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
UIRoot = UIFactory.CreateVerticalGroup(parent, "InteractiveList", true, true, true, true, 6, new Vector4(10, 3, 15, 4),
|
||||
new Color(0.05f, 0.05f, 0.05f));
|
||||
UIFactory.SetLayoutElement(UIRoot, flexibleWidth: 9999, minHeight: 25, flexibleHeight: 600);
|
||||
UIRoot.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
|
||||
// Entries label
|
||||
|
||||
TopLabel = UIFactory.CreateLabel(UIRoot, "EntryLabel", "not set", TextAnchor.MiddleLeft, fontSize: 16);
|
||||
TopLabel.horizontalOverflow = HorizontalWrapMode.Overflow;
|
||||
|
||||
// entry scroll pool
|
||||
|
||||
ListScrollPool = UIFactory.CreateScrollPool<CacheListEntryCell>(UIRoot, "EntryList", out GameObject scrollObj,
|
||||
out GameObject _, new Color(0.09f, 0.09f, 0.09f));
|
||||
UIFactory.SetLayoutElement(scrollObj, minHeight: 400, flexibleHeight: 0);
|
||||
ListScrollPool.Initialize(this, SetLayout);
|
||||
scrollLayout = scrollObj.GetComponent<LayoutElement>();
|
||||
|
||||
NotSupportedLabel = UIFactory.CreateLabel(ListScrollPool.Content.gameObject, "NotSupportedMessage",
|
||||
"The IEnumerable failed to enumerate. This is likely due to an issue with Unhollowed interfaces.",
|
||||
TextAnchor.MiddleLeft, Color.red);
|
||||
|
||||
UIFactory.SetLayoutElement(NotSupportedLabel.gameObject, minHeight: 25, flexibleWidth: 9999);
|
||||
NotSupportedLabel.gameObject.SetActive(false);
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
}
|
||||
}
|
135
src/CacheObject/IValues/InteractiveString.cs
Normal file
135
src/CacheObject/IValues/InteractiveString.cs
Normal file
@ -0,0 +1,135 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.Config;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.UI.Widgets;
|
||||
using UnityExplorer.UI;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject.IValues
|
||||
{
|
||||
public class InteractiveString : InteractiveValue
|
||||
{
|
||||
private string RealValue;
|
||||
public string EditedValue = "";
|
||||
|
||||
public InputFieldRef inputField;
|
||||
public ButtonRef ApplyButton;
|
||||
|
||||
public GameObject SaveFileRow;
|
||||
public InputFieldRef SaveFilePath;
|
||||
|
||||
public override void OnBorrowed(CacheObjectBase owner)
|
||||
{
|
||||
base.OnBorrowed(owner);
|
||||
|
||||
inputField.Component.readOnly = !owner.CanWrite;
|
||||
ApplyButton.Component.gameObject.SetActive(owner.CanWrite);
|
||||
|
||||
SaveFilePath.Text = Path.Combine(ConfigManager.Default_Output_Path.Value, "untitled.txt");
|
||||
}
|
||||
|
||||
private bool IsStringTooLong(string s)
|
||||
{
|
||||
if (s == null)
|
||||
return false;
|
||||
|
||||
return s.Length >= UniversalUI.MAX_INPUTFIELD_CHARS;
|
||||
}
|
||||
|
||||
public override void SetValue(object value)
|
||||
{
|
||||
RealValue = value as string;
|
||||
SaveFileRow.SetActive(IsStringTooLong(RealValue));
|
||||
|
||||
if (value == null)
|
||||
{
|
||||
inputField.Text = "";
|
||||
EditedValue = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
EditedValue = (string)value;
|
||||
inputField.Text = EditedValue;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnApplyClicked()
|
||||
{
|
||||
CurrentOwner.SetUserValue(EditedValue);
|
||||
}
|
||||
|
||||
private void OnInputChanged(string input)
|
||||
{
|
||||
EditedValue = input;
|
||||
SaveFileRow.SetActive(IsStringTooLong(EditedValue));
|
||||
}
|
||||
|
||||
private void OnSaveFileClicked()
|
||||
{
|
||||
if (RealValue == null)
|
||||
return;
|
||||
|
||||
if (string.IsNullOrEmpty(SaveFilePath.Text))
|
||||
{
|
||||
ExplorerCore.LogWarning("Cannot save an empty file path!");
|
||||
return;
|
||||
}
|
||||
|
||||
var path = IOUtility.EnsureValidFilePath(SaveFilePath.Text);
|
||||
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
|
||||
File.WriteAllText(path, RealValue);
|
||||
}
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
UIRoot = UIFactory.CreateVerticalGroup(parent, "InteractiveString", false, false, true, true, 3, new Vector4(4, 4, 4, 4),
|
||||
new Color(0.06f, 0.06f, 0.06f));
|
||||
|
||||
// Save to file helper
|
||||
|
||||
SaveFileRow = UIFactory.CreateUIObject("SaveFileRow", UIRoot);
|
||||
UIFactory.SetLayoutElement(SaveFileRow, flexibleWidth: 9999);
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(SaveFileRow, false, true, true, true, 3);
|
||||
|
||||
UIFactory.CreateLabel(SaveFileRow, "Info", "<color=red>String is too long! Save to file if you want to see the full string.</color>",
|
||||
TextAnchor.MiddleLeft);
|
||||
|
||||
var horizRow = UIFactory.CreateUIObject("Horiz", SaveFileRow);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(horizRow, false, false, true, true, 4);
|
||||
|
||||
var saveButton = UIFactory.CreateButton(horizRow, "SaveButton", "Save file");
|
||||
UIFactory.SetLayoutElement(saveButton.Component.gameObject, minHeight: 25, minWidth: 100, flexibleWidth: 0);
|
||||
saveButton.OnClick += OnSaveFileClicked;
|
||||
|
||||
SaveFilePath = UIFactory.CreateInputField(horizRow, "SaveInput", "...");
|
||||
UIFactory.SetLayoutElement(SaveFilePath.UIRoot, minHeight: 25, flexibleWidth: 9999);
|
||||
|
||||
// Main Input / apply
|
||||
|
||||
ApplyButton = UIFactory.CreateButton(UIRoot, "ApplyButton", "Apply", new Color(0.2f, 0.27f, 0.2f));
|
||||
UIFactory.SetLayoutElement(ApplyButton.Component.gameObject, minHeight: 25, minWidth: 100, flexibleWidth: 0);
|
||||
ApplyButton.OnClick += OnApplyClicked;
|
||||
|
||||
inputField = UIFactory.CreateInputField(UIRoot, "InputField", "empty");
|
||||
inputField.UIRoot.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
UIFactory.SetLayoutElement(inputField.UIRoot, minHeight: 25, flexibleHeight: 500, flexibleWidth: 9999);
|
||||
inputField.Component.lineType = InputField.LineType.MultiLineNewline;
|
||||
inputField.OnValueChanged += OnInputChanged;
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
72
src/CacheObject/IValues/InteractiveValue.cs
Normal file
72
src/CacheObject/IValues/InteractiveValue.cs
Normal file
@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.UI;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib.UI.ObjectPool;
|
||||
|
||||
namespace UnityExplorer.CacheObject.IValues
|
||||
{
|
||||
public abstract class InteractiveValue : IPooledObject
|
||||
{
|
||||
public static Type GetIValueTypeForState(ValueState state)
|
||||
{
|
||||
switch (state)
|
||||
{
|
||||
case ValueState.String:
|
||||
return typeof(InteractiveString);
|
||||
case ValueState.Enum:
|
||||
return typeof(InteractiveEnum);
|
||||
case ValueState.Collection:
|
||||
return typeof(InteractiveList);
|
||||
case ValueState.Dictionary:
|
||||
return typeof(InteractiveDictionary);
|
||||
case ValueState.ValueStruct:
|
||||
return typeof(InteractiveValueStruct);
|
||||
case ValueState.Color:
|
||||
return typeof(InteractiveColor);
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
public GameObject UIRoot { get; set; }
|
||||
public float DefaultHeight => -1f;
|
||||
|
||||
public virtual bool CanWrite => this.CurrentOwner.CanWrite;
|
||||
|
||||
public CacheObjectBase CurrentOwner => m_owner;
|
||||
private CacheObjectBase m_owner;
|
||||
|
||||
public bool PendingValueWanted;
|
||||
|
||||
public virtual void OnBorrowed(CacheObjectBase owner)
|
||||
{
|
||||
if (this.m_owner != null)
|
||||
{
|
||||
ExplorerCore.LogWarning("Setting an IValue's owner but there is already one set. Maybe it wasn't cleaned up?");
|
||||
ReleaseFromOwner();
|
||||
}
|
||||
|
||||
this.m_owner = owner;
|
||||
}
|
||||
|
||||
public virtual void ReleaseFromOwner()
|
||||
{
|
||||
if (this.m_owner == null)
|
||||
return;
|
||||
|
||||
this.m_owner = null;
|
||||
}
|
||||
|
||||
public abstract void SetValue(object value);
|
||||
|
||||
public virtual void SetLayout() { }
|
||||
|
||||
public abstract GameObject CreateContent(GameObject parent);
|
||||
}
|
||||
}
|
216
src/CacheObject/IValues/InteractiveValueStruct.cs
Normal file
216
src/CacheObject/IValues/InteractiveValueStruct.cs
Normal file
@ -0,0 +1,216 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject;
|
||||
using UnityExplorer.UI;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject.IValues
|
||||
{
|
||||
public class InteractiveValueStruct : InteractiveValue
|
||||
{
|
||||
#region Struct cache / wrapper
|
||||
|
||||
public class StructInfo
|
||||
{
|
||||
public bool IsSupported;
|
||||
public FieldInfo[] Fields;
|
||||
|
||||
public StructInfo(bool isSupported, FieldInfo[] fields)
|
||||
{
|
||||
IsSupported = isSupported;
|
||||
Fields = fields;
|
||||
}
|
||||
|
||||
public void SetValue(object instance, string input, int fieldIndex)
|
||||
{
|
||||
var field = Fields[fieldIndex];
|
||||
|
||||
object val;
|
||||
if (field.FieldType == typeof(string))
|
||||
val = input;
|
||||
else
|
||||
{
|
||||
if (!ParseUtility.TryParse(input, field.FieldType, out val, out Exception ex))
|
||||
{
|
||||
ExplorerCore.LogWarning("Unable to parse input!");
|
||||
if (ex != null) ExplorerCore.Log(ex.ReflectionExToString());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
field.SetValue(instance, val);
|
||||
}
|
||||
|
||||
public string GetValue(object instance, int fieldIndex)
|
||||
{
|
||||
var field = Fields[fieldIndex];
|
||||
var value = field.GetValue(instance);
|
||||
return ParseUtility.ToStringForInput(value, field.FieldType);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, StructInfo> typeSupportCache = new();
|
||||
|
||||
private const BindingFlags INSTANCE_FLAGS = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const string SYSTEM_VOID = "System.Void";
|
||||
|
||||
public static bool SupportsType(Type type)
|
||||
{
|
||||
if (!type.IsValueType || string.IsNullOrEmpty(type.AssemblyQualifiedName) || type.FullName == SYSTEM_VOID)
|
||||
return false;
|
||||
|
||||
if (typeSupportCache.TryGetValue(type.AssemblyQualifiedName, out var info))
|
||||
return info.IsSupported;
|
||||
|
||||
var supported = false;
|
||||
|
||||
var fields = type.GetFields(INSTANCE_FLAGS);
|
||||
if (fields.Length > 0)
|
||||
{
|
||||
if (fields.Any(it => !ParseUtility.CanParse(it.FieldType)))
|
||||
{
|
||||
supported = false;
|
||||
info = new StructInfo(supported, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
supported = true;
|
||||
info = new StructInfo(supported, fields);
|
||||
}
|
||||
}
|
||||
|
||||
typeSupportCache.Add(type.AssemblyQualifiedName, info);
|
||||
|
||||
return supported;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public object RefInstance;
|
||||
|
||||
public StructInfo CurrentInfo;
|
||||
private Type lastStructType;
|
||||
|
||||
private ButtonRef applyButton;
|
||||
private readonly List<GameObject> fieldRows = new List<GameObject>();
|
||||
private readonly List<InputFieldRef> inputFields = new List<InputFieldRef>();
|
||||
private readonly List<Text> labels = new List<Text>();
|
||||
|
||||
public override void OnBorrowed(CacheObjectBase owner)
|
||||
{
|
||||
base.OnBorrowed(owner);
|
||||
|
||||
applyButton.Component.gameObject.SetActive(owner.CanWrite);
|
||||
}
|
||||
|
||||
// Setting value from owner to this
|
||||
|
||||
public override void SetValue(object value)
|
||||
{
|
||||
RefInstance = value;
|
||||
|
||||
var type = RefInstance.GetType();
|
||||
|
||||
if (type != lastStructType)
|
||||
{
|
||||
CurrentInfo = typeSupportCache[type.AssemblyQualifiedName];
|
||||
SetupUIForType();
|
||||
lastStructType = type;
|
||||
}
|
||||
|
||||
for (int i = 0; i < CurrentInfo.Fields.Length; i++)
|
||||
{
|
||||
inputFields[i].Text = CurrentInfo.GetValue(RefInstance, i);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnApplyClicked()
|
||||
{
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < CurrentInfo.Fields.Length; i++)
|
||||
{
|
||||
CurrentInfo.SetValue(RefInstance, inputFields[i].Text, i);
|
||||
}
|
||||
|
||||
CurrentOwner.SetUserValue(RefInstance);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning("Exception setting value: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
// UI Setup for type
|
||||
|
||||
private void SetupUIForType()
|
||||
{
|
||||
for (int i = 0; i < CurrentInfo.Fields.Length || i <= inputFields.Count; i++)
|
||||
{
|
||||
if (i >= CurrentInfo.Fields.Length)
|
||||
{
|
||||
if (i >= inputFields.Count)
|
||||
break;
|
||||
|
||||
fieldRows[i].SetActive(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i >= inputFields.Count)
|
||||
AddEditorRow();
|
||||
|
||||
fieldRows[i].SetActive(true);
|
||||
|
||||
string label = SignatureHighlighter.Parse(CurrentInfo.Fields[i].FieldType, false);
|
||||
label += $" <color={SignatureHighlighter.FIELD_INSTANCE}>{CurrentInfo.Fields[i].Name}</color>:";
|
||||
labels[i].text = label;
|
||||
}
|
||||
}
|
||||
|
||||
private void AddEditorRow()
|
||||
{
|
||||
var row = UIFactory.CreateUIObject("HoriGroup", UIRoot);
|
||||
//row.AddComponent<ContentSizeFitter>().horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
UIFactory.SetLayoutElement(row, minHeight: 25, flexibleWidth: 9999);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(row, false, false, true, true, 8, childAlignment: TextAnchor.MiddleLeft);
|
||||
|
||||
fieldRows.Add(row);
|
||||
|
||||
var label = UIFactory.CreateLabel(row, "Label", "notset", TextAnchor.MiddleLeft);
|
||||
UIFactory.SetLayoutElement(label.gameObject, minHeight: 25, minWidth: 50, flexibleWidth: 0);
|
||||
label.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
labels.Add(label);
|
||||
|
||||
var input = UIFactory.CreateInputField(row, "InputField", "...");
|
||||
UIFactory.SetLayoutElement(input.UIRoot, minHeight: 25, minWidth: 200);
|
||||
var fitter = input.UIRoot.AddComponent<ContentSizeFitter>();
|
||||
fitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
fitter.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
input.Component.lineType = InputField.LineType.MultiLineNewline;
|
||||
inputFields.Add(input);
|
||||
}
|
||||
|
||||
// UI Construction
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
UIRoot = UIFactory.CreateVerticalGroup(parent, "InteractiveValueStruct", false, false, true, true, 3, new Vector4(4, 4, 4, 4),
|
||||
new Color(0.06f, 0.06f, 0.06f), TextAnchor.MiddleLeft);
|
||||
UIFactory.SetLayoutElement(UIRoot, minHeight: 25, flexibleWidth: 9999);
|
||||
|
||||
applyButton = UIFactory.CreateButton(UIRoot, "ApplyButton", "Apply", new Color(0.2f, 0.27f, 0.2f));
|
||||
UIFactory.SetLayoutElement(applyButton.Component.gameObject, minHeight: 25, minWidth: 175);
|
||||
applyButton.OnClick += OnApplyClicked;
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
}
|
||||
}
|
89
src/CacheObject/Views/CacheConfigCell.cs
Normal file
89
src/CacheObject/Views/CacheConfigCell.cs
Normal file
@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.UI;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject.Views
|
||||
{
|
||||
public class ConfigEntryCell : CacheObjectCell
|
||||
{
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
// Main layout
|
||||
|
||||
UIRoot = UIFactory.CreateUIObject(this.GetType().Name, parent, new Vector2(100, 30));
|
||||
Rect = UIRoot.GetComponent<RectTransform>();
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(UIRoot, false, false, true, true, 4, 4, 4, 4, 4, childAlignment: TextAnchor.UpperLeft);
|
||||
UIFactory.SetLayoutElement(UIRoot, minWidth: 100, flexibleWidth: 9999, minHeight: 30, flexibleHeight: 600);
|
||||
UIRoot.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
|
||||
// Left label
|
||||
|
||||
NameLabel = UIFactory.CreateLabel(UIRoot, "NameLabel", "<notset>", TextAnchor.MiddleLeft);
|
||||
NameLabel.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
UIFactory.SetLayoutElement(NameLabel.gameObject, minHeight: 25, flexibleWidth: 9999, flexibleHeight: 300);
|
||||
NameLayout = NameLabel.GetComponent<LayoutElement>();
|
||||
|
||||
// horizontal group
|
||||
|
||||
var horiGroup = UIFactory.CreateUIObject("RightHoriGroup", UIRoot);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(horiGroup, false, false, true, true, 4, childAlignment: TextAnchor.UpperLeft);
|
||||
UIFactory.SetLayoutElement(horiGroup, minHeight: 25, minWidth: 200, flexibleWidth: 9999, flexibleHeight: 800);
|
||||
|
||||
SubContentButton = UIFactory.CreateButton(horiGroup, "SubContentButton", "▲", subInactiveColor);
|
||||
UIFactory.SetLayoutElement(SubContentButton.Component.gameObject, minWidth: 25, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
|
||||
SubContentButton.OnClick += SubContentClicked;
|
||||
|
||||
// Type label
|
||||
|
||||
TypeLabel = UIFactory.CreateLabel(horiGroup, "TypeLabel", "<notset>", TextAnchor.MiddleLeft);
|
||||
TypeLabel.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
UIFactory.SetLayoutElement(TypeLabel.gameObject, minHeight: 25, flexibleHeight: 150, minWidth: 60, flexibleWidth: 0);
|
||||
|
||||
// Bool and number value interaction
|
||||
|
||||
var toggleObj = UIFactory.CreateToggle(horiGroup, "Toggle", out Toggle, out ToggleText);
|
||||
UIFactory.SetLayoutElement(toggleObj, minWidth: 70, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
|
||||
ToggleText.color = SignatureHighlighter.KeywordBlue;
|
||||
Toggle.onValueChanged.AddListener(ToggleClicked);
|
||||
|
||||
InputField = UIFactory.CreateInputField(horiGroup, "InputField", "...");
|
||||
UIFactory.SetLayoutElement(InputField.UIRoot, minWidth: 150, flexibleWidth: 0, minHeight: 25, flexibleHeight: 0);
|
||||
|
||||
// Apply
|
||||
|
||||
ApplyButton = UIFactory.CreateButton(horiGroup, "ApplyButton", "Apply", new Color(0.15f, 0.19f, 0.15f));
|
||||
UIFactory.SetLayoutElement(ApplyButton.Component.gameObject, minWidth: 70, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
|
||||
ApplyButton.OnClick += ApplyClicked;
|
||||
|
||||
// Main value label
|
||||
|
||||
ValueLabel = UIFactory.CreateLabel(horiGroup, "ValueLabel", "Value goes here", TextAnchor.MiddleLeft);
|
||||
ValueLabel.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
UIFactory.SetLayoutElement(ValueLabel.gameObject, minHeight: 25, flexibleHeight: 150, flexibleWidth: 9999);
|
||||
|
||||
// Subcontent
|
||||
|
||||
SubContentHolder = UIFactory.CreateUIObject("SubContent", UIRoot);
|
||||
UIFactory.SetLayoutElement(SubContentHolder.gameObject, minHeight: 30, flexibleHeight: 600, minWidth: 100, flexibleWidth: 9999);
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(SubContentHolder, true, true, true, true, 2, childAlignment: TextAnchor.UpperLeft);
|
||||
//SubContentHolder.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.MinSize;
|
||||
SubContentHolder.SetActive(false);
|
||||
|
||||
// Bottom separator
|
||||
var separator = UIFactory.CreateUIObject("BottomSeperator", UIRoot);
|
||||
UIFactory.SetLayoutElement(separator, minHeight: 1, flexibleHeight: 0, flexibleWidth: 9999);
|
||||
separator.AddComponent<Image>().color = Color.black;
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
|
||||
protected override void ConstructEvaluateHolder(GameObject parent) { }
|
||||
}
|
||||
}
|
94
src/CacheObject/Views/CacheKeyValuePairCell.cs
Normal file
94
src/CacheObject/Views/CacheKeyValuePairCell.cs
Normal file
@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject.IValues;
|
||||
using UnityExplorer.Inspectors;
|
||||
using UnityExplorer.UI;
|
||||
using UnityExplorer.UI.Widgets;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
|
||||
namespace UnityExplorer.CacheObject.Views
|
||||
{
|
||||
public class CacheKeyValuePairCell : CacheObjectCell
|
||||
{
|
||||
public Image Image { get; private set; }
|
||||
public InteractiveDictionary DictOwner => Occupant.Owner as InteractiveDictionary;
|
||||
|
||||
public LayoutElement KeyGroupLayout;
|
||||
public Text KeyLabel;
|
||||
public ButtonRef KeyInspectButton;
|
||||
public InputFieldRef KeyInputField;
|
||||
public Text KeyInputTypeLabel;
|
||||
|
||||
public static Color EvenColor = new Color(0.07f, 0.07f, 0.07f);
|
||||
public static Color OddColor = new Color(0.063f, 0.063f, 0.063f);
|
||||
|
||||
public int AdjustedWidth => (int)Rect.rect.width - 70;
|
||||
|
||||
//public int HalfWidth => (int)(0.5f * Rect.rect.width) - 75;
|
||||
//public int AdjustedKeyWidth => HalfWidth - 50;
|
||||
//public int AdjustedRightWidth => HalfWidth;
|
||||
|
||||
private void KeyInspectClicked()
|
||||
{
|
||||
InspectorManager.Inspect((Occupant as CacheKeyValuePair).DictKey, this.Occupant);
|
||||
}
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
var root = base.CreateContent(parent);
|
||||
|
||||
Image = root.AddComponent<Image>();
|
||||
|
||||
this.NameLayout.minWidth = 70;
|
||||
this.NameLayout.flexibleWidth = 0;
|
||||
this.NameLayout.minHeight = 30;
|
||||
this.NameLayout.flexibleHeight = 0;
|
||||
this.NameLabel.alignment = TextAnchor.MiddleRight;
|
||||
|
||||
this.RightGroupLayout.minWidth = AdjustedWidth * 0.55f;
|
||||
|
||||
// Key area
|
||||
var keyGroup = UIFactory.CreateUIObject("KeyHolder", root.transform.Find("HoriGroup").gameObject);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(keyGroup, false, false, true, true, 2, 0, 0, 4, 4, childAlignment: TextAnchor.MiddleLeft);
|
||||
KeyGroupLayout = UIFactory.SetLayoutElement(keyGroup, minHeight: 30, minWidth: (int)(AdjustedWidth * 0.44f), flexibleWidth: 0);
|
||||
|
||||
// set to be after the NameLabel (our index label), and before the main horizontal group.
|
||||
keyGroup.transform.SetSiblingIndex(1);
|
||||
|
||||
// key Inspect
|
||||
|
||||
KeyInspectButton = UIFactory.CreateButton(keyGroup, "KeyInspectButton", "Inspect", new Color(0.15f, 0.15f, 0.15f));
|
||||
UIFactory.SetLayoutElement(KeyInspectButton.Component.gameObject, minWidth: 60, flexibleWidth: 0, minHeight: 25, flexibleHeight: 0);
|
||||
KeyInspectButton.OnClick += KeyInspectClicked;
|
||||
|
||||
// label
|
||||
|
||||
KeyLabel = UIFactory.CreateLabel(keyGroup, "KeyLabel", "<i>empty</i>", TextAnchor.MiddleLeft);
|
||||
UIFactory.SetLayoutElement(KeyLabel.gameObject, minWidth: 50, flexibleWidth: 999, minHeight: 25);
|
||||
|
||||
// Type label for input field
|
||||
|
||||
KeyInputTypeLabel = UIFactory.CreateLabel(keyGroup, "InputTypeLabel", "<i>null</i>", TextAnchor.MiddleLeft);
|
||||
UIFactory.SetLayoutElement(KeyInputTypeLabel.gameObject, minWidth: 55, flexibleWidth: 0, minHeight: 25, flexibleHeight: 0);
|
||||
|
||||
// input field
|
||||
|
||||
KeyInputField = UIFactory.CreateInputField(keyGroup, "KeyInput", "empty");
|
||||
UIFactory.SetLayoutElement(KeyInputField.UIRoot, minHeight: 25, flexibleHeight: 0, flexibleWidth: 0, preferredWidth: 200);
|
||||
//KeyInputField.lineType = InputField.LineType.MultiLineNewline;
|
||||
KeyInputField.Component.readOnly = true;
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
protected override void ConstructEvaluateHolder(GameObject parent)
|
||||
{
|
||||
// not used
|
||||
}
|
||||
}
|
||||
}
|
44
src/CacheObject/Views/CacheListEntryCell.cs
Normal file
44
src/CacheObject/Views/CacheListEntryCell.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.CacheObject.IValues;
|
||||
|
||||
namespace UnityExplorer.CacheObject.Views
|
||||
{
|
||||
public class CacheListEntryCell : CacheObjectCell
|
||||
{
|
||||
public Image Image { get; private set; }
|
||||
public InteractiveList ListOwner => Occupant.Owner as InteractiveList;
|
||||
|
||||
public static Color EvenColor = new Color(0.12f, 0.12f, 0.12f);
|
||||
public static Color OddColor = new Color(0.1f, 0.1f, 0.1f);
|
||||
|
||||
public override GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
var root = base.CreateContent(parent);
|
||||
|
||||
Image = root.AddComponent<Image>();
|
||||
|
||||
this.NameLayout.minWidth = 40;
|
||||
this.NameLayout.flexibleWidth = 50;
|
||||
this.NameLayout.minHeight = 25;
|
||||
this.NameLayout.flexibleHeight = 0;
|
||||
this.NameLabel.alignment = TextAnchor.MiddleRight;
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
protected override void ConstructEvaluateHolder(GameObject parent)
|
||||
{
|
||||
// not used
|
||||
}
|
||||
|
||||
//protected override void ConstructUpdateToggle(GameObject parent)
|
||||
//{
|
||||
// // not used
|
||||
//}
|
||||
}
|
||||
}
|
39
src/CacheObject/Views/CacheMemberCell.cs
Normal file
39
src/CacheObject/Views/CacheMemberCell.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.UI;
|
||||
using UnityExplorer.UI.Widgets;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
|
||||
namespace UnityExplorer.CacheObject.Views
|
||||
{
|
||||
public class CacheMemberCell : CacheObjectCell
|
||||
{
|
||||
public CacheMember MemberOccupant => Occupant as CacheMember;
|
||||
|
||||
public GameObject EvaluateHolder;
|
||||
public ButtonRef EvaluateButton;
|
||||
|
||||
protected virtual void EvaluateClicked()
|
||||
{
|
||||
this.MemberOccupant.OnEvaluateClicked();
|
||||
}
|
||||
|
||||
protected override void ConstructEvaluateHolder(GameObject parent)
|
||||
{
|
||||
// Evaluate vert group
|
||||
|
||||
EvaluateHolder = UIFactory.CreateUIObject("EvalGroup", parent);
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(EvaluateHolder, false, false, true, true, 3);
|
||||
UIFactory.SetLayoutElement(EvaluateHolder, minHeight: 25, flexibleWidth: 9999, flexibleHeight: 775);
|
||||
|
||||
EvaluateButton = UIFactory.CreateButton(EvaluateHolder, "EvaluateButton", "Evaluate", new Color(0.15f, 0.15f, 0.15f));
|
||||
UIFactory.SetLayoutElement(EvaluateButton.Component.gameObject, minWidth: 100, minHeight: 25);
|
||||
EvaluateButton.OnClick += EvaluateClicked;
|
||||
}
|
||||
}
|
||||
}
|
229
src/CacheObject/Views/CacheObjectCell.cs
Normal file
229
src/CacheObject/Views/CacheObjectCell.cs
Normal file
@ -0,0 +1,229 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UnityExplorer.UI.Panels;
|
||||
using UniverseLib;
|
||||
using UniverseLib.UI;
|
||||
using UniverseLib.UI.Models;
|
||||
using UniverseLib.UI.Widgets.ScrollView;
|
||||
using UniverseLib.Utility;
|
||||
|
||||
namespace UnityExplorer.CacheObject.Views
|
||||
{
|
||||
public abstract class CacheObjectCell : ICell
|
||||
{
|
||||
#region ICell
|
||||
|
||||
public float DefaultHeight => 30f;
|
||||
|
||||
public GameObject UIRoot { get; set; }
|
||||
|
||||
public bool Enabled => m_enabled;
|
||||
private bool m_enabled;
|
||||
|
||||
public RectTransform Rect { get; set; }
|
||||
|
||||
public void Disable()
|
||||
{
|
||||
m_enabled = false;
|
||||
UIRoot.SetActive(false);
|
||||
}
|
||||
|
||||
public void Enable()
|
||||
{
|
||||
m_enabled = true;
|
||||
UIRoot.SetActive(true);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public CacheObjectBase Occupant { get; set; }
|
||||
public bool SubContentActive => SubContentHolder.activeSelf;
|
||||
|
||||
public LayoutElement NameLayout;
|
||||
public GameObject RightGroupContent;
|
||||
public LayoutElement RightGroupLayout;
|
||||
public GameObject SubContentHolder;
|
||||
|
||||
public Text NameLabel;
|
||||
public InputFieldRef HiddenNameLabel; // for selecting the name label
|
||||
public Text TypeLabel;
|
||||
public Text ValueLabel;
|
||||
public Toggle Toggle;
|
||||
public Text ToggleText;
|
||||
public InputFieldRef InputField;
|
||||
|
||||
public ButtonRef InspectButton;
|
||||
public ButtonRef SubContentButton;
|
||||
public ButtonRef ApplyButton;
|
||||
|
||||
public ButtonRef CopyButton;
|
||||
public ButtonRef PasteButton;
|
||||
|
||||
public readonly Color subInactiveColor = new(0.23f, 0.23f, 0.23f);
|
||||
public readonly Color subActiveColor = new(0.23f, 0.33f, 0.23f);
|
||||
|
||||
protected virtual void ApplyClicked()
|
||||
{
|
||||
Occupant.OnCellApplyClicked();
|
||||
}
|
||||
|
||||
protected virtual void InspectClicked()
|
||||
{
|
||||
InspectorManager.Inspect(Occupant.Value, this.Occupant);
|
||||
}
|
||||
|
||||
protected virtual void ToggleClicked(bool value)
|
||||
{
|
||||
ToggleText.text = value.ToString();
|
||||
}
|
||||
|
||||
protected virtual void SubContentClicked()
|
||||
{
|
||||
this.Occupant.OnCellSubContentToggle();
|
||||
}
|
||||
|
||||
protected virtual void OnCopyClicked()
|
||||
{
|
||||
ClipboardPanel.Copy(this.Occupant.Value);
|
||||
}
|
||||
|
||||
protected virtual void OnPasteClicked()
|
||||
{
|
||||
if (ClipboardPanel.TryPaste(this.Occupant.FallbackType, out object paste))
|
||||
this.Occupant.SetUserValue(paste);
|
||||
}
|
||||
|
||||
public void RefreshSubcontentButton()
|
||||
{
|
||||
this.SubContentButton.ButtonText.text = SubContentHolder.activeSelf ? "▼" : "▲";
|
||||
Color color = SubContentHolder.activeSelf ? subActiveColor : subInactiveColor;
|
||||
RuntimeHelper.SetColorBlock(SubContentButton.Component, color, color * 1.3f);
|
||||
}
|
||||
|
||||
protected abstract void ConstructEvaluateHolder(GameObject parent);
|
||||
|
||||
public virtual GameObject CreateContent(GameObject parent)
|
||||
{
|
||||
// Main layout
|
||||
|
||||
UIRoot = UIFactory.CreateUIObject(this.GetType().Name, parent, new Vector2(100, 30));
|
||||
Rect = UIRoot.GetComponent<RectTransform>();
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(UIRoot, false, false, true, true, childAlignment: TextAnchor.UpperLeft);
|
||||
UIFactory.SetLayoutElement(UIRoot, minWidth: 100, flexibleWidth: 9999, minHeight: 30, flexibleHeight: 600);
|
||||
UIRoot.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
|
||||
var horiRow = UIFactory.CreateUIObject("HoriGroup", UIRoot);
|
||||
UIFactory.SetLayoutElement(horiRow, minHeight: 29, flexibleHeight: 150, flexibleWidth: 9999);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(horiRow, false, false, true, true, 5, 2, childAlignment: TextAnchor.UpperLeft);
|
||||
horiRow.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
|
||||
|
||||
// Left name label
|
||||
|
||||
NameLabel = UIFactory.CreateLabel(horiRow, "NameLabel", "<notset>", TextAnchor.MiddleLeft);
|
||||
NameLabel.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
NameLayout = UIFactory.SetLayoutElement(NameLabel.gameObject, minHeight: 25, minWidth: 20, flexibleHeight: 300, flexibleWidth: 0);
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(NameLabel.gameObject, true, true, true, true);
|
||||
|
||||
HiddenNameLabel = UIFactory.CreateInputField(NameLabel.gameObject, "HiddenNameLabel", "");
|
||||
var hiddenRect = HiddenNameLabel.Component.GetComponent<RectTransform>();
|
||||
hiddenRect.anchorMin = Vector2.zero;
|
||||
hiddenRect.anchorMax = Vector2.one;
|
||||
HiddenNameLabel.Component.readOnly = true;
|
||||
HiddenNameLabel.Component.lineType = UnityEngine.UI.InputField.LineType.MultiLineNewline;
|
||||
HiddenNameLabel.Component.textComponent.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
HiddenNameLabel.Component.gameObject.GetComponent<Image>().color = Color.clear;
|
||||
HiddenNameLabel.Component.textComponent.color = Color.clear;
|
||||
UIFactory.SetLayoutElement(HiddenNameLabel.Component.gameObject, minHeight: 25, minWidth: 20, flexibleHeight: 300, flexibleWidth: 0);
|
||||
|
||||
// Right vertical group
|
||||
|
||||
RightGroupContent = UIFactory.CreateUIObject("RightGroup", horiRow);
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(RightGroupContent, false, false, true, true, 4, childAlignment: TextAnchor.UpperLeft);
|
||||
UIFactory.SetLayoutElement(RightGroupContent, minHeight: 25, minWidth: 200, flexibleWidth: 9999, flexibleHeight: 800);
|
||||
RightGroupLayout = RightGroupContent.GetComponent<LayoutElement>();
|
||||
|
||||
ConstructEvaluateHolder(RightGroupContent);
|
||||
|
||||
// Right horizontal group
|
||||
|
||||
var rightHoriGroup = UIFactory.CreateUIObject("RightHoriGroup", RightGroupContent);
|
||||
UIFactory.SetLayoutGroup<HorizontalLayoutGroup>(rightHoriGroup, false, false, true, true, 4, childAlignment: TextAnchor.UpperLeft);
|
||||
UIFactory.SetLayoutElement(rightHoriGroup, minHeight: 25, minWidth: 200, flexibleWidth: 9999, flexibleHeight: 800);
|
||||
|
||||
SubContentButton = UIFactory.CreateButton(rightHoriGroup, "SubContentButton", "▲", subInactiveColor);
|
||||
UIFactory.SetLayoutElement(SubContentButton.Component.gameObject, minWidth: 25, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
|
||||
SubContentButton.OnClick += SubContentClicked;
|
||||
|
||||
// Type label
|
||||
|
||||
TypeLabel = UIFactory.CreateLabel(rightHoriGroup, "ReturnLabel", "<notset>", TextAnchor.MiddleLeft);
|
||||
TypeLabel.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
UIFactory.SetLayoutElement(TypeLabel.gameObject, minHeight: 25, flexibleHeight: 150, minWidth: 45, flexibleWidth: 0);
|
||||
|
||||
// Bool and number value interaction
|
||||
|
||||
var toggleObj = UIFactory.CreateToggle(rightHoriGroup, "Toggle", out Toggle, out ToggleText);
|
||||
UIFactory.SetLayoutElement(toggleObj, minWidth: 70, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
|
||||
ToggleText.color = SignatureHighlighter.KeywordBlue;
|
||||
Toggle.onValueChanged.AddListener(ToggleClicked);
|
||||
|
||||
InputField = UIFactory.CreateInputField(rightHoriGroup, "InputField", "...");
|
||||
UIFactory.SetLayoutElement(InputField.UIRoot, minWidth: 150, flexibleWidth: 0, minHeight: 25, flexibleHeight: 0);
|
||||
|
||||
// Apply
|
||||
|
||||
ApplyButton = UIFactory.CreateButton(rightHoriGroup, "ApplyButton", "Apply", new Color(0.15f, 0.19f, 0.15f));
|
||||
UIFactory.SetLayoutElement(ApplyButton.Component.gameObject, minWidth: 70, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
|
||||
ApplyButton.OnClick += ApplyClicked;
|
||||
|
||||
// Inspect
|
||||
|
||||
InspectButton = UIFactory.CreateButton(rightHoriGroup, "InspectButton", "Inspect", new Color(0.15f, 0.15f, 0.15f));
|
||||
UIFactory.SetLayoutElement(InspectButton.Component.gameObject, minWidth: 70, flexibleWidth: 0, minHeight: 25);
|
||||
InspectButton.OnClick += InspectClicked;
|
||||
|
||||
// Main value label
|
||||
|
||||
ValueLabel = UIFactory.CreateLabel(rightHoriGroup, "ValueLabel", "Value goes here", TextAnchor.MiddleLeft);
|
||||
ValueLabel.horizontalOverflow = HorizontalWrapMode.Wrap;
|
||||
UIFactory.SetLayoutElement(ValueLabel.gameObject, minHeight: 25, flexibleHeight: 150, flexibleWidth: 9999);
|
||||
|
||||
// Copy and Paste buttons
|
||||
|
||||
var buttonHolder = UIFactory.CreateHorizontalGroup(rightHoriGroup, "CopyPasteButtons", false, false, true, true, 4,
|
||||
bgColor: new(1,1,1,0), childAlignment: TextAnchor.MiddleLeft);
|
||||
UIFactory.SetLayoutElement(buttonHolder, minWidth: 60, flexibleWidth: 0);
|
||||
|
||||
CopyButton = UIFactory.CreateButton(buttonHolder, "CopyButton", "Copy", new Color(0.13f, 0.13f, 0.13f, 1f));
|
||||
UIFactory.SetLayoutElement(CopyButton.Component.gameObject, minHeight: 25, minWidth: 28, flexibleWidth: 0);
|
||||
CopyButton.ButtonText.color = Color.yellow;
|
||||
CopyButton.ButtonText.fontSize = 10;
|
||||
CopyButton.OnClick += OnCopyClicked;
|
||||
|
||||
PasteButton = UIFactory.CreateButton(buttonHolder, "PasteButton", "Paste", new Color(0.13f, 0.13f, 0.13f, 1f));
|
||||
UIFactory.SetLayoutElement(PasteButton.Component.gameObject, minHeight: 25, minWidth: 28, flexibleWidth: 0);
|
||||
PasteButton.ButtonText.color = Color.green;
|
||||
PasteButton.ButtonText.fontSize = 10;
|
||||
PasteButton.OnClick += OnPasteClicked;
|
||||
|
||||
// Subcontent
|
||||
|
||||
SubContentHolder = UIFactory.CreateUIObject("SubContent", UIRoot);
|
||||
UIFactory.SetLayoutElement(SubContentHolder.gameObject, minHeight: 30, flexibleHeight: 600, minWidth: 100, flexibleWidth: 9999);
|
||||
UIFactory.SetLayoutGroup<VerticalLayoutGroup>(SubContentHolder, true, true, true, true, 2, childAlignment: TextAnchor.UpperLeft);
|
||||
//SubContentHolder.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.MinSize;
|
||||
SubContentHolder.SetActive(false);
|
||||
|
||||
// Bottom separator
|
||||
var separator = UIFactory.CreateUIObject("BottomSeperator", UIRoot);
|
||||
UIFactory.SetLayoutElement(separator, minHeight: 1, flexibleHeight: 0, flexibleWidth: 9999);
|
||||
separator.AddComponent<Image>().color = Color.black;
|
||||
|
||||
return UIRoot;
|
||||
}
|
||||
}
|
||||
}
|
@ -3,7 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace UnityExplorer.Core.Config
|
||||
namespace UnityExplorer.Config
|
||||
{
|
||||
public class ConfigElement<T> : IConfigElement
|
||||
{
|
||||
@ -18,6 +18,10 @@ namespace UnityExplorer.Core.Config
|
||||
|
||||
public object DefaultValue { get; }
|
||||
|
||||
public ConfigHandler Handler => IsInternal
|
||||
? ConfigManager.InternalHandler
|
||||
: ConfigManager.Handler;
|
||||
|
||||
public T Value
|
||||
{
|
||||
get => m_value;
|
||||
@ -51,19 +55,19 @@ namespace UnityExplorer.Core.Config
|
||||
|
||||
m_value = value;
|
||||
|
||||
ConfigManager.Handler.SetConfigValue(this, value);
|
||||
Handler.SetConfigValue(this, value);
|
||||
|
||||
OnValueChanged?.Invoke(value);
|
||||
OnValueChangedNotify?.Invoke();
|
||||
|
||||
ConfigManager.Handler.OnAnyConfigChanged();
|
||||
Handler.OnAnyConfigChanged();
|
||||
}
|
||||
|
||||
object IConfigElement.GetLoaderConfigValue() => GetLoaderConfigValue();
|
||||
|
||||
public T GetLoaderConfigValue()
|
||||
{
|
||||
return ConfigManager.Handler.GetConfigValue(this);
|
||||
return Handler.GetConfigValue(this);
|
||||
}
|
||||
|
||||
public void RevertToDefaultValue()
|
@ -3,7 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace UnityExplorer.Core.Config
|
||||
namespace UnityExplorer.Config
|
||||
{
|
||||
public abstract class ConfigHandler
|
||||
{
|
139
src/Config/ConfigManager.cs
Normal file
139
src/Config/ConfigManager.cs
Normal file
@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.UI;
|
||||
|
||||
namespace UnityExplorer.Config
|
||||
{
|
||||
public static class ConfigManager
|
||||
{
|
||||
internal static readonly Dictionary<string, IConfigElement> ConfigElements = new();
|
||||
internal static readonly Dictionary<string, IConfigElement> InternalConfigs = new();
|
||||
|
||||
// Each Mod Loader has its own ConfigHandler.
|
||||
// See the UnityExplorer.Loader namespace for the implementations.
|
||||
public static ConfigHandler Handler { get; private set; }
|
||||
|
||||
// Actual UE Settings
|
||||
public static ConfigElement<KeyCode> Master_Toggle;
|
||||
public static ConfigElement<int> Target_Display;
|
||||
public static ConfigElement<UIManager.VerticalAnchor> Main_Navbar_Anchor;
|
||||
public static ConfigElement<bool> Force_Unlock_Mouse;
|
||||
public static ConfigElement<KeyCode> Force_Unlock_Toggle;
|
||||
public static ConfigElement<bool> Aggressive_Mouse_Unlock;
|
||||
public static ConfigElement<bool> Disable_EventSystem_Override;
|
||||
public static ConfigElement<string> Default_Output_Path;
|
||||
public static ConfigElement<bool> Log_Unity_Debug;
|
||||
public static ConfigElement<bool> Hide_On_Startup;
|
||||
public static ConfigElement<float> Startup_Delay_Time;
|
||||
public static ConfigElement<string> Reflection_Signature_Blacklist;
|
||||
public static ConfigElement<KeyCode> World_MouseInspect_Keybind;
|
||||
public static ConfigElement<KeyCode> UI_MouseInspect_Keybind;
|
||||
|
||||
// internal configs
|
||||
internal static InternalConfigHandler InternalHandler { get; private set; }
|
||||
internal static readonly Dictionary<UIManager.Panels, ConfigElement<string>> PanelSaveData = new();
|
||||
|
||||
internal static ConfigElement<string> GetPanelSaveData(UIManager.Panels panel)
|
||||
{
|
||||
if (!PanelSaveData.ContainsKey(panel))
|
||||
PanelSaveData.Add(panel, new ConfigElement<string>(panel.ToString(), string.Empty, string.Empty, true));
|
||||
return PanelSaveData[panel];
|
||||
}
|
||||
|
||||
public static void Init(ConfigHandler configHandler)
|
||||
{
|
||||
Handler = configHandler;
|
||||
Handler.Init();
|
||||
|
||||
InternalHandler = new InternalConfigHandler();
|
||||
InternalHandler.Init();
|
||||
|
||||
CreateConfigElements();
|
||||
|
||||
Handler.LoadConfig();
|
||||
InternalHandler.LoadConfig();
|
||||
|
||||
//InitConsoleCallback();
|
||||
}
|
||||
|
||||
internal static void RegisterConfigElement<T>(ConfigElement<T> configElement)
|
||||
{
|
||||
if (!configElement.IsInternal)
|
||||
{
|
||||
Handler.RegisterConfigElement(configElement);
|
||||
ConfigElements.Add(configElement.Name, configElement);
|
||||
}
|
||||
else
|
||||
{
|
||||
InternalHandler.RegisterConfigElement(configElement);
|
||||
InternalConfigs.Add(configElement.Name, configElement);
|
||||
}
|
||||
}
|
||||
|
||||
private static void CreateConfigElements()
|
||||
{
|
||||
Master_Toggle = new ConfigElement<KeyCode>("UnityExplorer Toggle",
|
||||
"The key to enable or disable UnityExplorer's menu and features.",
|
||||
KeyCode.F7);
|
||||
|
||||
Target_Display = new ConfigElement<int>("Target Display",
|
||||
"The monitor index for UnityExplorer to use, if you have multiple. 0 is the default display, 1 is secondary, etc. " +
|
||||
"Restart recommended when changing this setting. Make sure your extra monitors are the same resolution as your primary monitor.",
|
||||
0);
|
||||
|
||||
Main_Navbar_Anchor = new ConfigElement<UIManager.VerticalAnchor>("Main Navbar Anchor",
|
||||
"The vertical anchor of the main UnityExplorer Navbar, in case you want to move it.",
|
||||
UIManager.VerticalAnchor.Top);
|
||||
|
||||
Hide_On_Startup = new ConfigElement<bool>("Hide On Startup",
|
||||
"Should UnityExplorer be hidden on startup?",
|
||||
false);
|
||||
|
||||
World_MouseInspect_Keybind = new("World Mouse-Inspect Keybind",
|
||||
"Optional keybind to being a World-mode Mouse Inspect.",
|
||||
KeyCode.None);
|
||||
|
||||
UI_MouseInspect_Keybind = new("UI Mouse-Inspect Keybind",
|
||||
"Optional keybind to begin a UI_mode Mouse Inspect.",
|
||||
KeyCode.None);
|
||||
|
||||
Force_Unlock_Mouse = new ConfigElement<bool>("Force Unlock Mouse",
|
||||
"Force the Cursor to be unlocked (visible) when the UnityExplorer menu is open.",
|
||||
true);
|
||||
Force_Unlock_Mouse.OnValueChanged += (bool value) => UniverseLib.Config.ConfigManager.Force_Unlock_Mouse = value;
|
||||
|
||||
Force_Unlock_Toggle = new ConfigElement<KeyCode>("Force Unlock Toggle Key",
|
||||
"The keybind to toggle the 'Force Unlock Mouse' setting. Only usable when UnityExplorer is open.",
|
||||
KeyCode.None);
|
||||
|
||||
Disable_EventSystem_Override = new ConfigElement<bool>("Disable EventSystem override",
|
||||
"If enabled, UnityExplorer will not override the EventSystem from the game.\n<b>May require restart to take effect.</b>",
|
||||
false);
|
||||
Disable_EventSystem_Override.OnValueChanged += (bool value) => UniverseLib.Config.ConfigManager.Disable_EventSystem_Override = value;
|
||||
|
||||
Log_Unity_Debug = new ConfigElement<bool>("Log Unity Debug",
|
||||
"Should UnityEngine.Debug.Log messages be printed to UnityExplorer's log?",
|
||||
false);
|
||||
|
||||
Default_Output_Path = new ConfigElement<string>("Default Output Path",
|
||||
"The default output path when exporting things from UnityExplorer.",
|
||||
Path.Combine(ExplorerCore.Loader.ExplorerFolder, "Output"));
|
||||
|
||||
Startup_Delay_Time = new ConfigElement<float>("Startup Delay Time",
|
||||
"The delay on startup before the UI is created.",
|
||||
1f);
|
||||
|
||||
Reflection_Signature_Blacklist = new ConfigElement<string>("Member Signature Blacklist",
|
||||
"Use this to blacklist certain member signatures if they are known to cause a crash or other issues.\r\n" +
|
||||
"Seperate signatures with a semicolon ';'.\r\n" +
|
||||
"For example, to blacklist Camera.main, you would add 'UnityEngine.Camera.main;'",
|
||||
"");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace UnityExplorer.Core.Config
|
||||
namespace UnityExplorer.Config
|
||||
{
|
||||
public interface IConfigElement
|
||||
{
|
79
src/Config/InternalConfigHandler.cs
Normal file
79
src/Config/InternalConfigHandler.cs
Normal file
@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.UI;
|
||||
using Tomlet;
|
||||
using Tomlet.Models;
|
||||
|
||||
namespace UnityExplorer.Config
|
||||
{
|
||||
public class InternalConfigHandler : ConfigHandler
|
||||
{
|
||||
internal static string CONFIG_PATH;
|
||||
|
||||
public override void Init()
|
||||
{
|
||||
CONFIG_PATH = Path.Combine(ExplorerCore.Loader.ExplorerFolder, "data.cfg");
|
||||
}
|
||||
|
||||
public override void LoadConfig()
|
||||
{
|
||||
if (!TryLoadConfig())
|
||||
SaveConfig();
|
||||
}
|
||||
|
||||
public override void RegisterConfigElement<T>(ConfigElement<T> element)
|
||||
{
|
||||
// Not necessary
|
||||
}
|
||||
|
||||
public override void SetConfigValue<T>(ConfigElement<T> element, T value)
|
||||
{
|
||||
// Not necessary
|
||||
}
|
||||
|
||||
// Not necessary, just return the value.
|
||||
public override T GetConfigValue<T>(ConfigElement<T> element) => element.Value;
|
||||
|
||||
// Always just auto-save.
|
||||
public override void OnAnyConfigChanged() => SaveConfig();
|
||||
|
||||
public bool TryLoadConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(CONFIG_PATH))
|
||||
return false;
|
||||
|
||||
TomlDocument document = TomlParser.ParseFile(CONFIG_PATH);
|
||||
foreach (var key in document.Keys)
|
||||
{
|
||||
var panelKey = (UIManager.Panels)Enum.Parse(typeof(UIManager.Panels), key);
|
||||
ConfigManager.GetPanelSaveData(panelKey).Value = document.GetString(key);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ExplorerCore.LogWarning("Error loading internal data: " + ex.ToString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override void SaveConfig()
|
||||
{
|
||||
if (UIManager.Initializing)
|
||||
return;
|
||||
|
||||
var tomlDocument = TomlDocument.CreateEmpty();
|
||||
foreach (var entry in ConfigManager.InternalConfigs)
|
||||
tomlDocument.Put(entry.Key, entry.Value.BoxedValue as string, false);
|
||||
|
||||
File.WriteAllText(CONFIG_PATH, tomlDocument.SerializedValue);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
#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
|
@ -1,67 +0,0 @@
|
||||
using System;
|
||||
using Mono.CSharp;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityExplorer.Core.Runtime;
|
||||
using UnityExplorer.UI.Main.CSConsole;
|
||||
using UnityExplorer.UI.Main.Home;
|
||||
using UnityExplorer.UI.Inspectors;
|
||||
|
||||
namespace UnityExplorer.Core.CSharp
|
||||
{
|
||||
public class ScriptInteraction : InteractiveBase
|
||||
{
|
||||
public static void Log(object message)
|
||||
{
|
||||
ExplorerCore.Log(message);
|
||||
}
|
||||
|
||||
public static void StartCoroutine(IEnumerator ienumerator)
|
||||
{
|
||||
RuntimeProvider.Instance.StartConsoleCoroutine(ienumerator);
|
||||
}
|
||||
|
||||
public static void AddUsing(string directive)
|
||||
{
|
||||
CSharpConsole.Instance.AddUsing(directive);
|
||||
}
|
||||
|
||||
public static void GetUsing()
|
||||
{
|
||||
ExplorerCore.Log(CSharpConsole.Instance.Evaluator.GetUsing());
|
||||
}
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
CSharpConsole.Instance.ResetConsole();
|
||||
}
|
||||
|
||||
public static object CurrentTarget()
|
||||
{
|
||||
return InspectorManager.Instance?.m_activeInspector?.Target;
|
||||
}
|
||||
|
||||
public static object[] AllTargets()
|
||||
{
|
||||
int count = InspectorManager.Instance?.m_currentInspectors.Count ?? 0;
|
||||
object[] ret = new object[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
ret[i] = InspectorManager.Instance?.m_currentInspectors[i].Target;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static void Inspect(object obj)
|
||||
{
|
||||
InspectorManager.Instance.Inspect(obj);
|
||||
}
|
||||
|
||||
public static void Inspect(Type type)
|
||||
{
|
||||
InspectorManager.Instance.Inspect(type);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,70 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.Core;
|
||||
using UnityExplorer.UI.Main.CSConsole;
|
||||
|
||||
namespace UnityExplorer.Core.CSharp
|
||||
{
|
||||
public struct Suggestion
|
||||
{
|
||||
public enum Contexts
|
||||
{
|
||||
Namespace,
|
||||
Keyword,
|
||||
Other
|
||||
}
|
||||
|
||||
// ~~~~ Instance ~~~~
|
||||
|
||||
public readonly string Prefix;
|
||||
public readonly string Addition;
|
||||
public readonly Contexts Context;
|
||||
|
||||
public string Full => Prefix + Addition;
|
||||
|
||||
public Color TextColor => GetTextColor();
|
||||
|
||||
public Suggestion(string addition, string prefix, Contexts type)
|
||||
{
|
||||
Addition = addition;
|
||||
Prefix = prefix;
|
||||
Context = type;
|
||||
}
|
||||
|
||||
private Color GetTextColor()
|
||||
{
|
||||
switch (Context)
|
||||
{
|
||||
case Contexts.Namespace: return Color.grey;
|
||||
case Contexts.Keyword: return keywordColor;
|
||||
default: return Color.white;
|
||||
}
|
||||
}
|
||||
|
||||
// ~~~~ Static ~~~~
|
||||
|
||||
public static HashSet<string> Namespaces => m_namespaces ?? GetNamespaces();
|
||||
private static HashSet<string> m_namespaces;
|
||||
|
||||
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);
|
||||
|
||||
private static HashSet<string> GetNamespaces()
|
||||
{
|
||||
HashSet<string> set = new HashSet<string>(
|
||||
AppDomain.CurrentDomain.GetAssemblies()
|
||||
.SelectMany(GetTypes)
|
||||
.Where(x => x.IsPublic && !string.IsNullOrEmpty(x.Namespace))
|
||||
.Select(x => x.Namespace));
|
||||
|
||||
return m_namespaces = set;
|
||||
|
||||
IEnumerable<Type> GetTypes(Assembly asm) => asm.TryGetTypes();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,246 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.UI.Main;
|
||||
using UnityExplorer.UI.Main.Home;
|
||||
|
||||
namespace UnityExplorer.Core.Config
|
||||
{
|
||||
public static class ConfigManager
|
||||
{
|
||||
// Each Mod Loader has its own ConfigHandler.
|
||||
// See the UnityExplorer.Loader namespace for the implementations.
|
||||
public static ConfigHandler Handler { get; private set; }
|
||||
|
||||
public static ConfigElement<KeyCode> Main_Menu_Toggle;
|
||||
public static ConfigElement<bool> Force_Unlock_Mouse;
|
||||
public static ConfigElement<int> Default_Page_Limit;
|
||||
public static ConfigElement<string> Default_Output_Path;
|
||||
public static ConfigElement<bool> Log_Unity_Debug;
|
||||
public static ConfigElement<bool> Hide_On_Startup;
|
||||
|
||||
public static ConfigElement<string> Last_Window_Anchors;
|
||||
public static ConfigElement<string> Last_Window_Position;
|
||||
public static ConfigElement<int> Last_Active_Tab;
|
||||
public static ConfigElement<bool> Last_DebugConsole_State;
|
||||
public static ConfigElement<bool> Last_SceneExplorer_State;
|
||||
|
||||
internal static readonly Dictionary<string, IConfigElement> ConfigElements = new Dictionary<string, IConfigElement>();
|
||||
|
||||
public static void Init(ConfigHandler configHandler)
|
||||
{
|
||||
Handler = configHandler;
|
||||
Handler.Init();
|
||||
|
||||
CreateConfigElements();
|
||||
|
||||
Handler.LoadConfig();
|
||||
|
||||
SceneExplorer.OnToggleShow += SceneExplorer_OnToggleShow;
|
||||
PanelDragger.OnFinishResize += PanelDragger_OnFinishResize;
|
||||
PanelDragger.OnFinishDrag += PanelDragger_OnFinishDrag;
|
||||
MainMenu.OnActiveTabChanged += MainMenu_OnActiveTabChanged;
|
||||
DebugConsole.OnToggleShow += DebugConsole_OnToggleShow;
|
||||
|
||||
InitConsoleCallback();
|
||||
}
|
||||
|
||||
internal static void RegisterConfigElement<T>(ConfigElement<T> configElement)
|
||||
{
|
||||
Handler.RegisterConfigElement(configElement);
|
||||
ConfigElements.Add(configElement.Name, configElement);
|
||||
}
|
||||
|
||||
private static void CreateConfigElements()
|
||||
{
|
||||
Main_Menu_Toggle = new ConfigElement<KeyCode>("Main Menu Toggle",
|
||||
"The UnityEngine.KeyCode to toggle the UnityExplorer Menu.",
|
||||
KeyCode.F7);
|
||||
|
||||
Hide_On_Startup = new ConfigElement<bool>("Hide On Startup",
|
||||
"Should UnityExplorer be hidden on startup?",
|
||||
false);
|
||||
|
||||
Log_Unity_Debug = new ConfigElement<bool>("Log Unity Debug",
|
||||
"Should UnityEngine.Debug.Log messages be printed to UnityExplorer's log?",
|
||||
false);
|
||||
|
||||
Force_Unlock_Mouse = new ConfigElement<bool>("Force Unlock Mouse",
|
||||
"Force the Cursor to be unlocked (visible) when the UnityExplorer menu is open.",
|
||||
true);
|
||||
|
||||
Default_Page_Limit = new ConfigElement<int>("Default Page Limit",
|
||||
"The default maximum number of elements per 'page' in UnityExplorer.",
|
||||
25);
|
||||
|
||||
Default_Output_Path = new ConfigElement<string>("Default Output Path",
|
||||
"The default output path when exporting things from UnityExplorer.",
|
||||
Path.Combine(ExplorerCore.Loader.ExplorerFolder, "Output"));
|
||||
|
||||
// Internal configs
|
||||
|
||||
Last_Window_Anchors = new ConfigElement<string>("Last_Window_Anchors",
|
||||
"For internal use, the last anchors of the UnityExplorer window.",
|
||||
DEFAULT_WINDOW_ANCHORS,
|
||||
true);
|
||||
|
||||
Last_Window_Position = new ConfigElement<string>("Last_Window_Position",
|
||||
"For internal use, the last position of the UnityExplorer window.",
|
||||
DEFAULT_WINDOW_POSITION,
|
||||
true);
|
||||
|
||||
Last_Active_Tab = new ConfigElement<int>("Last_Active_Tab",
|
||||
"For internal use, the last active tab index.",
|
||||
0,
|
||||
true);
|
||||
|
||||
Last_DebugConsole_State = new ConfigElement<bool>("Last_DebugConsole_State",
|
||||
"For internal use, the collapsed state of the Debug Console.",
|
||||
true,
|
||||
true);
|
||||
|
||||
Last_SceneExplorer_State = new ConfigElement<bool>("Last_SceneExplorer_State",
|
||||
"For internal use, the collapsed state of the Scene Explorer.",
|
||||
true,
|
||||
true);
|
||||
}
|
||||
|
||||
// Internal config callback listeners
|
||||
|
||||
private static void PanelDragger_OnFinishResize(RectTransform rect)
|
||||
{
|
||||
Last_Window_Anchors.Value = rect.RectAnchorsToString();
|
||||
}
|
||||
|
||||
private static void PanelDragger_OnFinishDrag(RectTransform rect)
|
||||
{
|
||||
Last_Window_Position.Value = rect.RectPositionToString();
|
||||
}
|
||||
|
||||
private static void MainMenu_OnActiveTabChanged(int page)
|
||||
{
|
||||
Last_Active_Tab.Value = page;
|
||||
}
|
||||
|
||||
private static void DebugConsole_OnToggleShow(bool showing)
|
||||
{
|
||||
Last_DebugConsole_State.Value = showing;
|
||||
}
|
||||
|
||||
private static void SceneExplorer_OnToggleShow(bool showing)
|
||||
{
|
||||
Last_SceneExplorer_State.Value = showing;
|
||||
}
|
||||
|
||||
#region CONSOLE ONEXIT CALLBACK
|
||||
|
||||
internal static void InitConsoleCallback()
|
||||
{
|
||||
handler = new ConsoleEventDelegate(ConsoleEventCallback);
|
||||
SetConsoleCtrlHandler(handler, true);
|
||||
}
|
||||
|
||||
static bool ConsoleEventCallback(int eventType)
|
||||
{
|
||||
// 2 is Console Quit
|
||||
if (eventType == 2)
|
||||
Handler.SaveConfig();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static ConsoleEventDelegate handler;
|
||||
private delegate bool ConsoleEventDelegate(int eventType);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
|
||||
|
||||
#endregion
|
||||
|
||||
#region WINDOW ANCHORS / POSITION HELPERS
|
||||
|
||||
// Window Anchors helpers
|
||||
|
||||
private const string DEFAULT_WINDOW_ANCHORS = "0.25,0.10,0.78,0.95";
|
||||
private const string DEFAULT_WINDOW_POSITION = "0,0";
|
||||
|
||||
internal static CultureInfo _enCulture = new CultureInfo("en-US");
|
||||
|
||||
internal static string RectAnchorsToString(this RectTransform rect)
|
||||
{
|
||||
try
|
||||
{
|
||||
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 void SetAnchorsFromString(this RectTransform panel, string stringAnchors)
|
||||
{
|
||||
Vector4 anchors;
|
||||
try
|
||||
{
|
||||
var split = stringAnchors.Split(',');
|
||||
|
||||
if (split.Length != 4)
|
||||
throw new Exception();
|
||||
|
||||
anchors.x = float.Parse(split[0], _enCulture);
|
||||
anchors.y = float.Parse(split[1], _enCulture);
|
||||
anchors.z = float.Parse(split[2], _enCulture);
|
||||
anchors.w = float.Parse(split[3], _enCulture);
|
||||
}
|
||||
catch
|
||||
{
|
||||
anchors = new Vector4(0.25f, 0.1f, 0.78f, 0.95f);
|
||||
}
|
||||
|
||||
panel.anchorMin = new Vector2(anchors.x, anchors.y);
|
||||
panel.anchorMax = new Vector2(anchors.z, anchors.w);
|
||||
}
|
||||
|
||||
internal static string RectPositionToString(this RectTransform rect)
|
||||
{
|
||||
return string.Format(_enCulture, "{0},{1}", new object[]
|
||||
{
|
||||
rect.localPosition.x, rect.localPosition.y
|
||||
});
|
||||
}
|
||||
|
||||
internal static void SetPositionFromString(this RectTransform rect, string stringPosition)
|
||||
{
|
||||
try
|
||||
{
|
||||
var split = stringPosition.Split(',');
|
||||
|
||||
if (split.Length != 2)
|
||||
throw new Exception();
|
||||
|
||||
Vector3 vector = rect.localPosition;
|
||||
vector.x = float.Parse(split[0], _enCulture);
|
||||
vector.y = float.Parse(split[1], _enCulture);
|
||||
rect.localPosition = vector;
|
||||
}
|
||||
catch //(Exception ex)
|
||||
{
|
||||
//ExplorerCore.LogWarning("Exception setting window position: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,191 +0,0 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.Core.Unity;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityExplorer.Core.Input;
|
||||
using BF = System.Reflection.BindingFlags;
|
||||
using UnityExplorer.Core.Config;
|
||||
using UnityExplorer.Core;
|
||||
using UnityExplorer.UI;
|
||||
#if ML
|
||||
using Harmony;
|
||||
#else
|
||||
using HarmonyLib;
|
||||
#endif
|
||||
|
||||
namespace UnityExplorer.Core.Input
|
||||
{
|
||||
public class CursorUnlocker
|
||||
{
|
||||
public static bool Unlock
|
||||
{
|
||||
get => m_forceUnlock;
|
||||
set
|
||||
{
|
||||
m_forceUnlock = value;
|
||||
UpdateCursorControl();
|
||||
}
|
||||
}
|
||||
private static bool m_forceUnlock;
|
||||
|
||||
public static bool ShouldActuallyUnlock => UIManager.ShowMenu && Unlock;
|
||||
|
||||
private static CursorLockMode m_lastLockMode;
|
||||
private static bool m_lastVisibleState;
|
||||
|
||||
private static bool m_currentlySettingCursor = false;
|
||||
|
||||
private static Type CursorType
|
||||
=> m_cursorType
|
||||
?? (m_cursorType = ReflectionUtility.GetTypeByName("UnityEngine.Cursor"));
|
||||
private static Type m_cursorType;
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
SetupPatches();
|
||||
|
||||
UpdateCursorControl();
|
||||
|
||||
Unlock = ConfigManager.Force_Unlock_Mouse.Value;
|
||||
ConfigManager.Force_Unlock_Mouse.OnValueChanged += (bool val) => { Unlock = val; };
|
||||
}
|
||||
|
||||
public static void UpdateCursorControl()
|
||||
{
|
||||
try
|
||||
{
|
||||
m_currentlySettingCursor = true;
|
||||
|
||||
if (ShouldActuallyUnlock)
|
||||
{
|
||||
Cursor.lockState = CursorLockMode.None;
|
||||
Cursor.visible = true;
|
||||
|
||||
if (UIManager.EventSys)
|
||||
SetEventSystem();
|
||||
}
|
||||
else
|
||||
{
|
||||
Cursor.lockState = m_lastLockMode;
|
||||
Cursor.visible = m_lastVisibleState;
|
||||
|
||||
if (UIManager.EventSys)
|
||||
ReleaseEventSystem();
|
||||
}
|
||||
|
||||
m_currentlySettingCursor = false;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ExplorerCore.Log($"Exception setting Cursor state: {e.GetType()}, {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// Event system overrides
|
||||
|
||||
private static bool m_settingEventSystem;
|
||||
private static EventSystem m_lastEventSystem;
|
||||
private static BaseInputModule m_lastInputModule;
|
||||
|
||||
public static void SetEventSystem()
|
||||
{
|
||||
// temp disabled for new InputSystem
|
||||
if (InputManager.CurrentType == InputType.InputSystem)
|
||||
return;
|
||||
|
||||
// Disable current event system object
|
||||
if (m_lastEventSystem || EventSystem.current)
|
||||
{
|
||||
if (!m_lastEventSystem)
|
||||
m_lastEventSystem = EventSystem.current;
|
||||
|
||||
m_lastEventSystem.enabled = false;
|
||||
}
|
||||
|
||||
// Set to our current system
|
||||
m_settingEventSystem = true;
|
||||
EventSystem.current = UIManager.EventSys;
|
||||
UIManager.EventSys.enabled = true;
|
||||
InputManager.ActivateUIModule();
|
||||
m_settingEventSystem = false;
|
||||
}
|
||||
|
||||
public static void ReleaseEventSystem()
|
||||
{
|
||||
if (InputManager.CurrentType == InputType.InputSystem)
|
||||
return;
|
||||
|
||||
if (m_lastEventSystem)
|
||||
{
|
||||
m_lastEventSystem.enabled = true;
|
||||
|
||||
m_settingEventSystem = true;
|
||||
EventSystem.current = m_lastEventSystem;
|
||||
m_lastInputModule?.ActivateModule();
|
||||
m_settingEventSystem = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Patches
|
||||
|
||||
private static void SetupPatches()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (CursorType == null)
|
||||
throw new Exception("Could not load Type 'UnityEngine.Cursor'!");
|
||||
|
||||
// Get current cursor state and enable cursor
|
||||
m_lastLockMode = (CursorLockMode?)CursorType.GetProperty("lockState", BF.Public | BF.Static)?.GetValue(null, null)
|
||||
?? CursorLockMode.None;
|
||||
|
||||
m_lastVisibleState = (bool?)CursorType.GetProperty("visible", BF.Public | BF.Static)?.GetValue(null, null)
|
||||
?? false;
|
||||
|
||||
ExplorerCore.Loader.SetupPatches();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ExplorerCore.Log($"Error on CursorUnlocker.Init! {e.GetType()}, {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void Prefix_EventSystem_set_current(ref EventSystem value)
|
||||
{
|
||||
if (!m_settingEventSystem)
|
||||
{
|
||||
m_lastEventSystem = value;
|
||||
m_lastInputModule = value?.currentInputModule;
|
||||
|
||||
if (ShouldActuallyUnlock)
|
||||
value = UIManager.EventSys;
|
||||
}
|
||||
}
|
||||
|
||||
// Force mouse to stay unlocked and visible while UnlockMouse and ShowMenu are true.
|
||||
// Also keep track of when anything else tries to set Cursor state, this will be the
|
||||
// value that we set back to when we close the menu or disable force-unlock.
|
||||
|
||||
public static void Prefix_set_lockState(ref CursorLockMode value)
|
||||
{
|
||||
if (!m_currentlySettingCursor)
|
||||
{
|
||||
m_lastLockMode = value;
|
||||
|
||||
if (ShouldActuallyUnlock)
|
||||
value = CursorLockMode.None;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Prefix_set_visible(ref bool value)
|
||||
{
|
||||
if (!m_currentlySettingCursor)
|
||||
{
|
||||
m_lastVisibleState = value;
|
||||
|
||||
if (ShouldActuallyUnlock)
|
||||
value = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
namespace UnityExplorer.Core.Input
|
||||
{
|
||||
public interface IHandleInput
|
||||
{
|
||||
Vector2 MousePosition { get; }
|
||||
|
||||
bool GetKeyDown(KeyCode key);
|
||||
bool GetKey(KeyCode key);
|
||||
|
||||
bool GetMouseButtonDown(int btn);
|
||||
bool GetMouseButton(int btn);
|
||||
|
||||
BaseInputModule UIModule { get; }
|
||||
|
||||
void AddUIInputModule();
|
||||
void ActivateModule();
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
namespace UnityExplorer.Core.Input
|
||||
{
|
||||
public enum InputType
|
||||
{
|
||||
InputSystem,
|
||||
Legacy,
|
||||
None
|
||||
}
|
||||
|
||||
public static class InputManager
|
||||
{
|
||||
public static InputType CurrentType { get; private set; }
|
||||
|
||||
private static IHandleInput m_inputModule;
|
||||
|
||||
public static Vector3 MousePosition => m_inputModule.MousePosition;
|
||||
|
||||
public static bool GetKeyDown(KeyCode key) => m_inputModule.GetKeyDown(key);
|
||||
public static bool GetKey(KeyCode key) => m_inputModule.GetKey(key);
|
||||
|
||||
public static bool GetMouseButtonDown(int btn) => m_inputModule.GetMouseButtonDown(btn);
|
||||
public static bool GetMouseButton(int btn) => m_inputModule.GetMouseButton(btn);
|
||||
|
||||
public static BaseInputModule UIInput => m_inputModule.UIModule;
|
||||
|
||||
public static void ActivateUIModule() => m_inputModule.ActivateModule();
|
||||
|
||||
public static void AddUIModule()
|
||||
{
|
||||
m_inputModule.AddUIInputModule();
|
||||
ActivateUIModule();
|
||||
}
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
if (InputSystem.TKeyboard != null || (ReflectionUtility.LoadModule("Unity.InputSystem") && InputSystem.TKeyboard != null))
|
||||
{
|
||||
m_inputModule = new InputSystem();
|
||||
CurrentType = InputType.InputSystem;
|
||||
}
|
||||
else if (LegacyInput.TInput != null || (ReflectionUtility.LoadModule("UnityEngine.InputLegacyModule") && LegacyInput.TInput != null))
|
||||
{
|
||||
m_inputModule = new LegacyInput();
|
||||
CurrentType = InputType.Legacy;
|
||||
}
|
||||
|
||||
if (m_inputModule == null)
|
||||
{
|
||||
ExplorerCore.LogWarning("Could not find any Input Module Type!");
|
||||
m_inputModule = new NoInput();
|
||||
CurrentType = InputType.None;
|
||||
}
|
||||
|
||||
CursorUnlocker.Init();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,208 +0,0 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using UnityExplorer.Core.Unity;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityExplorer.UI;
|
||||
using System.Collections.Generic;
|
||||
using UnityExplorer.UI.Inspectors;
|
||||
#if CPP
|
||||
using UnhollowerRuntimeLib;
|
||||
#endif
|
||||
|
||||
namespace UnityExplorer.Core.Input
|
||||
{
|
||||
public class InputSystem : IHandleInput
|
||||
{
|
||||
public InputSystem()
|
||||
{
|
||||
ExplorerCore.Log("Initializing new InputSystem support...");
|
||||
|
||||
m_kbCurrentProp = TKeyboard.GetProperty("current");
|
||||
m_kbIndexer = TKeyboard.GetProperty("Item", new Type[] { TKey });
|
||||
|
||||
var btnControl = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Controls.ButtonControl");
|
||||
m_btnIsPressedProp = btnControl.GetProperty("isPressed");
|
||||
m_btnWasPressedProp = btnControl.GetProperty("wasPressedThisFrame");
|
||||
|
||||
m_mouseCurrentProp = TMouse.GetProperty("current");
|
||||
m_leftButtonProp = TMouse.GetProperty("leftButton");
|
||||
m_rightButtonProp = TMouse.GetProperty("rightButton");
|
||||
|
||||
m_positionProp = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Pointer")
|
||||
.GetProperty("position");
|
||||
|
||||
m_readVector2InputMethod = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.InputControl`1")
|
||||
.MakeGenericType(typeof(Vector2))
|
||||
.GetMethod("ReadValue");
|
||||
}
|
||||
|
||||
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 = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Mouse"));
|
||||
private static Type m_tMouse;
|
||||
|
||||
public static Type TKey => m_tKey ?? (m_tKey = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.Key"));
|
||||
private static Type m_tKey;
|
||||
|
||||
private static PropertyInfo m_btnIsPressedProp;
|
||||
private static PropertyInfo m_btnWasPressedProp;
|
||||
|
||||
private static object CurrentKeyboard => m_currentKeyboard ?? (m_currentKeyboard = m_kbCurrentProp.GetValue(null, null));
|
||||
private static object m_currentKeyboard;
|
||||
private static PropertyInfo m_kbCurrentProp;
|
||||
private static PropertyInfo m_kbIndexer;
|
||||
|
||||
private static object CurrentMouse => m_currentMouse ?? (m_currentMouse = m_mouseCurrentProp.GetValue(null, null));
|
||||
private static object m_currentMouse;
|
||||
private static PropertyInfo m_mouseCurrentProp;
|
||||
|
||||
private static object LeftMouseButton => m_lmb ?? (m_lmb = m_leftButtonProp.GetValue(CurrentMouse, null));
|
||||
private static object m_lmb;
|
||||
private static PropertyInfo m_leftButtonProp;
|
||||
|
||||
private static object RightMouseButton => m_rmb ?? (m_rmb = m_rightButtonProp.GetValue(CurrentMouse, null));
|
||||
private static object m_rmb;
|
||||
private static PropertyInfo m_rightButtonProp;
|
||||
|
||||
private static object MousePositionInfo => m_pos ?? (m_pos = m_positionProp.GetValue(CurrentMouse, null));
|
||||
private static object m_pos;
|
||||
private static PropertyInfo m_positionProp;
|
||||
private static MethodInfo m_readVector2InputMethod;
|
||||
|
||||
public Vector2 MousePosition
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
return (Vector2)m_readVector2InputMethod.Invoke(MousePositionInfo, new object[0]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Vector2.zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static Dictionary<KeyCode, object> ActualKeyDict = new Dictionary<KeyCode, object>();
|
||||
|
||||
internal object GetActualKey(KeyCode key)
|
||||
{
|
||||
if (!ActualKeyDict.ContainsKey(key))
|
||||
{
|
||||
var s = key.ToString();
|
||||
if (s.Contains("Control"))
|
||||
s = s.Replace("Control", "Ctrl");
|
||||
else if (s.Contains("Return"))
|
||||
s = "Enter";
|
||||
|
||||
var parsed = Enum.Parse(TKey, s);
|
||||
var actualKey = m_kbIndexer.GetValue(CurrentKeyboard, new object[] { parsed });
|
||||
|
||||
ActualKeyDict.Add(key, actualKey);
|
||||
}
|
||||
|
||||
return ActualKeyDict[key];
|
||||
}
|
||||
|
||||
public bool GetKeyDown(KeyCode key) => (bool)m_btnWasPressedProp.GetValue(GetActualKey(key), null);
|
||||
|
||||
public bool GetKey(KeyCode key) => (bool)m_btnIsPressedProp.GetValue(GetActualKey(key), null);
|
||||
|
||||
public bool GetMouseButtonDown(int btn)
|
||||
{
|
||||
switch (btn)
|
||||
{
|
||||
case 0: return (bool)m_btnWasPressedProp.GetValue(LeftMouseButton, null);
|
||||
case 1: return (bool)m_btnWasPressedProp.GetValue(RightMouseButton, null);
|
||||
// case 2: return (bool)_btnWasPressedProp.GetValue(MiddleMouseButton, null);
|
||||
default: throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public bool GetMouseButton(int btn)
|
||||
{
|
||||
switch (btn)
|
||||
{
|
||||
case 0: return (bool)m_btnIsPressedProp.GetValue(LeftMouseButton, null);
|
||||
case 1: return (bool)m_btnIsPressedProp.GetValue(RightMouseButton, null);
|
||||
// case 2: return (bool)_btnIsPressedProp.GetValue(MiddleMouseButton, null);
|
||||
default: throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
// UI Input
|
||||
|
||||
public Type TInputSystemUIInputModule
|
||||
=> m_tUIInputModule
|
||||
?? (m_tUIInputModule = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.UI.InputSystemUIInputModule"));
|
||||
internal Type m_tUIInputModule;
|
||||
|
||||
public BaseInputModule UIModule => m_newInputModule;
|
||||
internal BaseInputModule m_newInputModule;
|
||||
|
||||
public void AddUIInputModule()
|
||||
{
|
||||
if (TInputSystemUIInputModule == null)
|
||||
{
|
||||
ExplorerCore.LogWarning("Unable to find UI Input Module Type, Input will not work!");
|
||||
return;
|
||||
}
|
||||
|
||||
var assetType = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.InputActionAsset");
|
||||
#if CPP
|
||||
m_newInputModule = UIManager.CanvasRoot.AddComponent(Il2CppType.From(TInputSystemUIInputModule)).TryCast<BaseInputModule>();
|
||||
var asset = ScriptableObject.CreateInstance(Il2CppType.From(assetType));
|
||||
#else
|
||||
m_newInputModule = (BaseInputModule)UIManager.CanvasRoot.AddComponent(TInputSystemUIInputModule);
|
||||
var asset = ScriptableObject.CreateInstance(assetType);
|
||||
#endif
|
||||
inputExtensions = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.InputActionSetupExtensions");
|
||||
|
||||
var addMap = inputExtensions.GetMethod("AddActionMap", new Type[] { assetType, typeof(string) });
|
||||
var map = addMap.Invoke(null, new object[] { asset, "UI" });
|
||||
|
||||
CreateAction(map, "point", new[] { "<Mouse>/position" }, "point");
|
||||
CreateAction(map, "click", new[] { "<Mouse>/leftButton" }, "leftClick");
|
||||
CreateAction(map, "rightClick", new[] { "<Mouse>/rightButton" }, "rightClick");
|
||||
CreateAction(map, "scrollWheel", new[] { "<Mouse>/scroll" }, "scrollWheel");
|
||||
|
||||
UI_Enable = map.GetType().GetMethod("Enable");
|
||||
UI_Enable.Invoke(map, new object[0]);
|
||||
UI_ActionMap = map;
|
||||
}
|
||||
|
||||
private Type inputExtensions;
|
||||
private object UI_ActionMap;
|
||||
private MethodInfo UI_Enable;
|
||||
|
||||
private void CreateAction(object map, string actionName, string[] bindings, string propertyName)
|
||||
{
|
||||
var addAction = inputExtensions.GetMethod("AddAction");
|
||||
var pointAction = addAction.Invoke(null, new object[] { map, actionName, default, null, null, null, null, null });
|
||||
|
||||
var inputActionType = pointAction.GetType();
|
||||
var addBinding = inputExtensions.GetMethod("AddBinding",
|
||||
new Type[] { inputActionType, typeof(string), typeof(string), typeof(string), typeof(string) });
|
||||
|
||||
foreach (string binding in bindings)
|
||||
addBinding.Invoke(null, new object[] { pointAction, binding, null, null, null });
|
||||
|
||||
var inputRef = ReflectionUtility.GetTypeByName("UnityEngine.InputSystem.InputActionReference")
|
||||
.GetMethod("Create")
|
||||
.Invoke(null, new object[] { pointAction });
|
||||
|
||||
TInputSystemUIInputModule
|
||||
.GetProperty(propertyName)
|
||||
.SetValue(m_newInputModule, inputRef, null);
|
||||
}
|
||||
|
||||
public void ActivateModule()
|
||||
{
|
||||
m_newInputModule.ActivateModule();
|
||||
UI_Enable.Invoke(UI_ActionMap, new object[0]);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using UnityExplorer.Core.Unity;
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityExplorer.UI;
|
||||
|
||||
namespace UnityExplorer.Core.Input
|
||||
{
|
||||
public class LegacyInput : IHandleInput
|
||||
{
|
||||
public LegacyInput()
|
||||
{
|
||||
ExplorerCore.Log("Initializing Legacy Input support...");
|
||||
|
||||
m_mousePositionProp = TInput.GetProperty("mousePosition");
|
||||
m_getKeyMethod = TInput.GetMethod("GetKey", new Type[] { typeof(KeyCode) });
|
||||
m_getKeyDownMethod = TInput.GetMethod("GetKeyDown", new Type[] { typeof(KeyCode) });
|
||||
m_getMouseButtonMethod = TInput.GetMethod("GetMouseButton", new Type[] { typeof(int) });
|
||||
m_getMouseButtonDownMethod = TInput.GetMethod("GetMouseButtonDown", new Type[] { typeof(int) });
|
||||
}
|
||||
|
||||
public static Type TInput => m_tInput ?? (m_tInput = ReflectionUtility.GetTypeByName("UnityEngine.Input"));
|
||||
private static Type m_tInput;
|
||||
|
||||
private static PropertyInfo m_mousePositionProp;
|
||||
private static MethodInfo m_getKeyMethod;
|
||||
private static MethodInfo m_getKeyDownMethod;
|
||||
private static MethodInfo m_getMouseButtonMethod;
|
||||
private static MethodInfo m_getMouseButtonDownMethod;
|
||||
|
||||
public Vector2 MousePosition => (Vector3)m_mousePositionProp.GetValue(null, null);
|
||||
|
||||
public bool GetKey(KeyCode key) => (bool)m_getKeyMethod.Invoke(null, new object[] { key });
|
||||
|
||||
public bool GetKeyDown(KeyCode key) => (bool)m_getKeyDownMethod.Invoke(null, new object[] { key });
|
||||
|
||||
public bool GetMouseButton(int btn) => (bool)m_getMouseButtonMethod.Invoke(null, new object[] { btn });
|
||||
|
||||
public bool GetMouseButtonDown(int btn) => (bool)m_getMouseButtonDownMethod.Invoke(null, new object[] { btn });
|
||||
|
||||
// UI Input module
|
||||
|
||||
public BaseInputModule UIModule => m_inputModule;
|
||||
internal StandaloneInputModule m_inputModule;
|
||||
|
||||
public void AddUIInputModule()
|
||||
{
|
||||
m_inputModule = UIManager.CanvasRoot.gameObject.AddComponent<StandaloneInputModule>();
|
||||
}
|
||||
|
||||
public void ActivateModule()
|
||||
{
|
||||
m_inputModule.ActivateModule();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
namespace UnityExplorer.Core.Input
|
||||
{
|
||||
// Just a stub for games where no Input module was able to load at all.
|
||||
|
||||
public class NoInput : IHandleInput
|
||||
{
|
||||
public Vector2 MousePosition => Vector2.zero;
|
||||
|
||||
public bool GetKey(KeyCode key) => false;
|
||||
public bool GetKeyDown(KeyCode key) => false;
|
||||
|
||||
public bool GetMouseButton(int btn) => false;
|
||||
public bool GetMouseButtonDown(int btn) => false;
|
||||
|
||||
public BaseInputModule UIModule => null;
|
||||
public void ActivateModule() { }
|
||||
public void AddUIInputModule() { }
|
||||
}
|
||||
}
|
@ -1,215 +0,0 @@
|
||||
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
|
||||
{
|
||||
public static class ReflectionUtility
|
||||
{
|
||||
public const BF AllFlags = 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 GetActualType(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)
|
||||
=> ReflectionProvider.Instance.Cast(obj, GetActualType(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);
|
||||
|
||||
/// <summary>
|
||||
/// [INTERNAL] Used to load Unhollowed DLLs in IL2CPP.
|
||||
/// </summary>
|
||||
internal 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(GetActualType(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>();
|
||||
}
|
||||
}
|
||||
|
||||
internal static Dictionary<Type, Dictionary<string, FieldInfo>> s_cachedFieldInfos = new Dictionary<Type, Dictionary<string, FieldInfo>>();
|
||||
|
||||
public static FieldInfo GetFieldInfo(Type type, string fieldName)
|
||||
{
|
||||
if (!s_cachedFieldInfos.ContainsKey(type))
|
||||
s_cachedFieldInfos.Add(type, new Dictionary<string, FieldInfo>());
|
||||
|
||||
if (!s_cachedFieldInfos[type].ContainsKey(fieldName))
|
||||
s_cachedFieldInfos[type].Add(fieldName, type.GetField(fieldName, AllFlags));
|
||||
|
||||
return s_cachedFieldInfos[type][fieldName];
|
||||
}
|
||||
|
||||
internal static Dictionary<Type, Dictionary<string, PropertyInfo>> s_cachedPropInfos = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
|
||||
|
||||
public static PropertyInfo GetPropertyInfo(Type type, string propertyName)
|
||||
{
|
||||
if (!s_cachedPropInfos.ContainsKey(type))
|
||||
s_cachedPropInfos.Add(type, new Dictionary<string, PropertyInfo>());
|
||||
|
||||
if (!s_cachedPropInfos[type].ContainsKey(propertyName))
|
||||
s_cachedPropInfos[type].Add(propertyName, type.GetProperty(propertyName, AllFlags));
|
||||
|
||||
return s_cachedPropInfos[type][propertyName];
|
||||
}
|
||||
|
||||
/// <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}";
|
||||
}
|
||||
}
|
||||
}
|
@ -1,76 +0,0 @@
|
||||
#if CPP
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnhollowerBaseLib;
|
||||
using UnhollowerRuntimeLib;
|
||||
using UnityEngine;
|
||||
using UnityExplorer.Core.Runtime.Il2Cpp;
|
||||
|
||||
namespace UnityExplorer
|
||||
{
|
||||
public class AssetBundle
|
||||
{
|
||||
// ~~~~~~~~~~~~ Static ~~~~~~~~~~~~
|
||||
|
||||
internal delegate IntPtr d_LoadFromFile(IntPtr path, uint crc, ulong offset);
|
||||
|
||||
public static AssetBundle LoadFromFile(string path)
|
||||
{
|
||||
var iCall = ICallManager.GetICall<d_LoadFromFile>("UnityEngine.AssetBundle::LoadFromFile_Internal");
|
||||
|
||||
var ptr = iCall.Invoke(IL2CPP.ManagedStringToIl2Cpp(path), 0u, 0UL);
|
||||
|
||||
return new AssetBundle(ptr);
|
||||
}
|
||||
|
||||
private delegate IntPtr d_LoadFromMemory(IntPtr binary, uint crc);
|
||||
|
||||
public static AssetBundle LoadFromMemory(byte[] binary, uint crc = 0)
|
||||
{
|
||||
var iCall = ICallManager.GetICall<d_LoadFromMemory>("UnityEngine.AssetBundle::LoadFromMemory_Internal");
|
||||
|
||||
var ptr = iCall(((Il2CppStructArray<byte>) binary).Pointer, crc);
|
||||
|
||||
return new AssetBundle(ptr);
|
||||
}
|
||||
|
||||
// ~~~~~~~~~~~~ Instance ~~~~~~~~~~~~
|
||||
|
||||
private readonly IntPtr m_bundlePtr = IntPtr.Zero;
|
||||
|
||||
public AssetBundle(IntPtr ptr) { m_bundlePtr = ptr; }
|
||||
|
||||
// LoadAllAssets()
|
||||
|
||||
internal delegate IntPtr d_LoadAssetWithSubAssets_Internal(IntPtr _this, IntPtr name, IntPtr type);
|
||||
|
||||
public UnityEngine.Object[] LoadAllAssets()
|
||||
{
|
||||
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)
|
||||
return new UnityEngine.Object[0];
|
||||
|
||||
return new Il2CppReferenceArray<UnityEngine.Object>(ptr);
|
||||
}
|
||||
|
||||
// LoadAsset<T>(string name, Type type)
|
||||
|
||||
internal delegate IntPtr d_LoadAsset_Internal(IntPtr _this, IntPtr name, IntPtr type);
|
||||
|
||||
public T LoadAsset<T>(string name) where T : UnityEngine.Object
|
||||
{
|
||||
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)
|
||||
return null;
|
||||
|
||||
return new UnityEngine.Object(ptr).TryCast<T>();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
@ -1,72 +0,0 @@
|
||||
#if CPP
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace UnityExplorer.Core.Runtime.Il2Cpp
|
||||
{
|
||||
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "External methods")]
|
||||
public static class ICallManager
|
||||
{
|
||||
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
|
||||
public static extern IntPtr il2cpp_resolve_icall([MarshalAs(UnmanagedType.LPStr)] string name);
|
||||
|
||||
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 find any iCall with the signature '{signature}'!");
|
||||
|
||||
Delegate iCall = Marshal.GetDelegateForFunctionPointer(ptr, typeof(T));
|
||||
iCallCache.Add(signature, iCall);
|
||||
|
||||
return (T)iCall;
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, Delegate> s_unreliableCache = new Dictionary<string, Delegate>();
|
||||
|
||||
/// <summary>
|
||||
/// Get an iCall which may be one of multiple different signatures (ie, it changed in different Unity versions).
|
||||
/// Each possible signature must have the same Type pattern, it can only vary by name.
|
||||
/// </summary>
|
||||
public static T GetICallUnreliable<T>(IEnumerable<string> possibleSignatures) where T : Delegate
|
||||
{
|
||||
// use the first possible signature as the 'key'.
|
||||
string key = possibleSignatures.First();
|
||||
|
||||
if (s_unreliableCache.ContainsKey(key))
|
||||
return (T)s_unreliableCache[key];
|
||||
|
||||
T iCall;
|
||||
IntPtr ptr;
|
||||
foreach (var sig in possibleSignatures)
|
||||
{
|
||||
ptr = il2cpp_resolve_icall(sig);
|
||||
if (ptr != IntPtr.Zero)
|
||||
{
|
||||
iCall = (T)Marshal.GetDelegateForFunctionPointer(ptr, typeof(T));
|
||||
s_unreliableCache.Add(key, iCall);
|
||||
return iCall;
|
||||
}
|
||||
}
|
||||
|
||||
throw new MissingMethodException($"Could not find any iCall from list of provided signatures starting with '{key}'!");
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
@ -1,156 +0,0 @@
|
||||
#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
|
@ -1,184 +0,0 @@
|
||||
#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;
|
||||
using UnityExplorer.Core.Input;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
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>(Application_logMessageReceived) })
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
ExplorerCore.LogWarning("Exception setting up Unity log listener, make sure Unity libraries have been unstripped!");
|
||||
}
|
||||
}
|
||||
|
||||
private void Application_logMessageReceived(string condition, string stackTrace, LogType type)
|
||||
{
|
||||
ExplorerCore.Log(condition, type, true);
|
||||
}
|
||||
|
||||
public override void StartConsoleCoroutine(IEnumerator routine)
|
||||
{
|
||||
Il2CppCoroutine.Start(routine);
|
||||
}
|
||||
|
||||
// Unity API Handlers
|
||||
|
||||
// LayerMask.LayerToName
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
// Resources.FindObjectsOfTypeAll
|
||||
|
||||
internal delegate IntPtr d_FindObjectsOfTypeAll(IntPtr type);
|
||||
|
||||
public override UnityEngine.Object[] FindObjectsOfTypeAll(Type type)
|
||||
{
|
||||
var iCall = ICallManager.GetICallUnreliable<d_FindObjectsOfTypeAll>(new[]
|
||||
{
|
||||
"UnityEngine.Resources::FindObjectsOfTypeAll",
|
||||
"UnityEngine.ResourcesAPIInternal::FindObjectsOfTypeAll" // Unity 2020+ updated to this
|
||||
});
|
||||
|
||||
return new Il2CppReferenceArray<UnityEngine.Object>(iCall.Invoke(Il2CppType.From(type).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)
|
||||
{
|
||||
if (!scene.isLoaded)
|
||||
return new GameObject[0];
|
||||
|
||||
int handle = scene.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);
|
||||
}
|
||||
|
||||
internal static bool? s_doPropertiesExist;
|
||||
|
||||
public override ColorBlock SetColorBlock(ColorBlock colors, Color? normal = null, Color? highlighted = null, Color? pressed = null)
|
||||
{
|
||||
if (s_doPropertiesExist == null)
|
||||
{
|
||||
var prop = ReflectionUtility.GetPropertyInfo(typeof(ColorBlock), "normalColor") as PropertyInfo;
|
||||
s_doPropertiesExist = prop != null && prop.CanWrite;
|
||||
}
|
||||
|
||||
colors.colorMultiplier = 1;
|
||||
|
||||
object boxed = (object)colors;
|
||||
|
||||
if (s_doPropertiesExist == true)
|
||||
{
|
||||
if (normal != null)
|
||||
ReflectionUtility.GetPropertyInfo(typeof(ColorBlock), "normalColor").SetValue(boxed, (Color)normal);
|
||||
if (pressed != null)
|
||||
ReflectionUtility.GetPropertyInfo(typeof(ColorBlock), "pressedColor").SetValue(boxed, (Color)pressed);
|
||||
if (highlighted != null)
|
||||
ReflectionUtility.GetPropertyInfo(typeof(ColorBlock), "highlightedColor").SetValue(boxed, (Color)highlighted);
|
||||
}
|
||||
else if (s_doPropertiesExist == false)
|
||||
{
|
||||
if (normal != null)
|
||||
ReflectionUtility.GetFieldInfo(typeof(ColorBlock), "m_NormalColor").SetValue(boxed, (Color)normal);
|
||||
if (pressed != null)
|
||||
ReflectionUtility.GetFieldInfo(typeof(ColorBlock), "m_PressedColor").SetValue(boxed, (Color)pressed);
|
||||
if (highlighted != null)
|
||||
ReflectionUtility.GetFieldInfo(typeof(ColorBlock), "m_HighlightedColor").SetValue(boxed, (Color)highlighted);
|
||||
}
|
||||
|
||||
colors = (ColorBlock)boxed;
|
||||
|
||||
return colors;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
@ -1,373 +0,0 @@
|
||||
#if CPP
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnhollowerBaseLib;
|
||||
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);
|
||||
|
||||
// Thanks to Slaynash for this deobfuscation snippet!
|
||||
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 cppObj))
|
||||
return obj;
|
||||
|
||||
if (!Il2CppTypeNotNull(castTo, out IntPtr castToPtr))
|
||||
return obj;
|
||||
|
||||
IntPtr castFromPtr = il2cpp_object_get_class(cppObj.Pointer);
|
||||
|
||||
if (!il2cpp_class_is_assignable_from(castToPtr, castFromPtr))
|
||||
return null;
|
||||
|
||||
if (RuntimeSpecificsStore.IsInjected(castToPtr))
|
||||
return UnhollowerBaseLib.Runtime.ClassInjectorBase.GetMonoObjectFromIl2CppPointer(cppObj.Pointer);
|
||||
|
||||
if (castTo == typeof(string))
|
||||
return cppObj.ToString();
|
||||
|
||||
return Activator.CreateInstance(castTo, cppObj.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;
|
||||
}
|
||||
|
||||
public override void BoxStringToType(ref object value, Type castTo)
|
||||
{
|
||||
if (castTo == typeof(Il2CppSystem.String))
|
||||
value = (Il2CppSystem.String)(value as string);
|
||||
else
|
||||
value = (Il2CppSystem.Object)(value as string);
|
||||
}
|
||||
|
||||
// ~~~~~~~~~~ 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
|
@ -1,77 +0,0 @@
|
||||
#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
|
@ -1,120 +0,0 @@
|
||||
#if MONO
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
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 += Application_logMessageReceived;
|
||||
}
|
||||
|
||||
private void Application_logMessageReceived(string condition, string stackTrace, LogType type)
|
||||
{
|
||||
ExplorerCore.Log(condition, type, true);
|
||||
}
|
||||
|
||||
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.AllFlags);
|
||||
|
||||
public override int GetSceneHandle(Scene scene)
|
||||
{
|
||||
return (int)fi_Scene_handle.GetValue(scene);
|
||||
}
|
||||
|
||||
public override GameObject[] GetRootGameObjects(Scene scene)
|
||||
{
|
||||
if (!scene.isLoaded)
|
||||
return new GameObject[0];
|
||||
|
||||
return scene.GetRootGameObjects();
|
||||
}
|
||||
|
||||
public override int GetRootCount(Scene scene)
|
||||
{
|
||||
return scene.rootCount;
|
||||
}
|
||||
|
||||
public override ColorBlock SetColorBlock(ColorBlock colors, Color? normal = null, Color? highlighted = null, Color? pressed = null)
|
||||
{
|
||||
if (normal != null)
|
||||
colors.normalColor = (Color)normal;
|
||||
|
||||
if (highlighted != null)
|
||||
colors.highlightedColor = (Color)highlighted;
|
||||
|
||||
if (pressed != null)
|
||||
colors.pressedColor = (Color)pressed;
|
||||
|
||||
return colors;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class MonoExtensions
|
||||
{
|
||||
public static void AddListener(this UnityEvent _event, Action listener)
|
||||
{
|
||||
_event.AddListener(new UnityAction(listener));
|
||||
}
|
||||
|
||||
public static void AddListener<T>(this UnityEvent<T> _event, Action<T> listener)
|
||||
{
|
||||
_event.AddListener(new UnityAction<T>(listener));
|
||||
}
|
||||
|
||||
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
|
@ -1,36 +0,0 @@
|
||||
#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;
|
||||
|
||||
// not necessary
|
||||
public override void BoxStringToType(ref object _string, Type castTo) { }
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
@ -1,66 +0,0 @@
|
||||
#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.AllFlags);
|
||||
|
||||
var method = typeof(Texture2D).GetMethod("EncodeToPNG", ReflectionUtility.AllFlags);
|
||||
if (method != null)
|
||||
return m_encodeToPNGMethod = method;
|
||||
|
||||
ExplorerCore.Log("ERROR: Cannot get any EncodeToPNG method!");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user