-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathManageUI.cs
More file actions
1921 lines (1630 loc) · 77.7 KB
/
Copy pathManageUI.cs
File metadata and controls
1921 lines (1630 loc) · 77.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using MCPForUnity.Editor.Helpers;
using MCPForUnity.Runtime.Helpers;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace MCPForUnity.Editor.Tools
{
[McpForUnityTool("manage_ui", AutoRegister = false, Group = "ui")]
public static class ManageUI
{
private static readonly HashSet<string> ValidExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".uxml", ".uss"
};
// UTF-8 without BOM — UI Builder in Unity 6 can fail to open UXML files with a BOM.
private static readonly Encoding Utf8NoBom = new UTF8Encoding(false);
static ManageUI()
{
EditorApplication.quitting += CleanupRenderTextures;
AssemblyReloadEvents.beforeAssemblyReload += CleanupRenderTextures;
}
private static void CleanupRenderTextures()
{
foreach (var kvp in s_panelRTs)
{
if (kvp.Value == null) continue;
string assetPath = AssetDatabase.GetAssetPath(kvp.Value);
kvp.Value.Release();
if (!string.IsNullOrEmpty(assetPath))
AssetDatabase.DeleteAsset(assetPath);
else
UnityEngine.Object.DestroyImmediate(kvp.Value);
}
s_panelRTs.Clear();
}
public static object HandleCommand(JObject @params)
{
string action = @params["action"]?.ToString()?.ToLowerInvariant();
if (string.IsNullOrEmpty(action))
{
return new ErrorResponse("Action is required");
}
try
{
switch (action)
{
case "ping":
return new SuccessResponse("pong", new { tool = "manage_ui" });
case "create":
return CreateFile(@params);
case "read":
return ReadFile(@params);
case "update":
return UpdateFile(@params);
case "attach_ui_document":
return AttachUIDocument(@params);
case "create_panel_settings":
return CreatePanelSettings(@params);
case "update_panel_settings":
return UpdatePanelSettings(@params);
case "get_visual_tree":
return GetVisualTree(@params);
case "render_ui":
return RenderUI(@params);
case "link_stylesheet":
return LinkStylesheet(@params);
case "delete":
return DeleteFile(@params);
case "list":
return ListUIAssets(@params);
case "detach_ui_document":
return DetachUIDocument(@params);
case "modify_visual_element":
return ModifyVisualElement(@params);
default:
return new ErrorResponse($"Unknown action: {action}");
}
}
catch (Exception ex)
{
return new ErrorResponse(ex.Message, new { stackTrace = ex.StackTrace });
}
}
private static string ValidatePath(string path, out string error)
{
error = null;
if (string.IsNullOrEmpty(path))
{
error = "'path' parameter is required.";
return null;
}
path = AssetPathUtility.SanitizeAssetPath(path);
if (path == null)
{
error = "Invalid path: contains traversal sequences.";
return null;
}
string ext = Path.GetExtension(path);
if (!ValidExtensions.Contains(ext))
{
error = $"Invalid file extension '{ext}'. Must be .uxml or .uss.";
return null;
}
return path;
}
private static object CreateFile(JObject @params)
{
var p = new ToolParams(@params);
string path = ValidatePath(p.Get("path"), out string pathError);
if (pathError != null) return new ErrorResponse(pathError);
string contents;
try
{
contents = GetDecodedContents(p);
}
catch (ArgumentException ex)
{
return new ErrorResponse(ex.Message);
}
if (contents == null)
{
return new ErrorResponse("'contents' parameter is required for create.");
}
string fullPath = Path.Combine(Application.dataPath,
path.Substring("Assets/".Length));
fullPath = fullPath.Replace('/', Path.DirectorySeparatorChar);
if (File.Exists(fullPath))
{
return new ErrorResponse($"File already exists at {path}. Use 'update' action to overwrite.");
}
string dir = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
bool isUxml = path.EndsWith(".uxml", StringComparison.OrdinalIgnoreCase);
var validationWarnings = new List<string>();
if (isUxml)
{
string xmlError = ValidateUxmlContent(contents, validationWarnings);
if (xmlError != null)
{
return new ErrorResponse($"UXML validation failed — file was NOT written. {xmlError}");
}
contents = EnsureEditorExtensionMode(contents);
}
File.WriteAllText(fullPath, contents, Utf8NoBom);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
if (isUxml)
{
ValidateUxmlPostImport(path, validationWarnings);
}
string ext = Path.GetExtension(path).TrimStart('.');
if (validationWarnings.Count > 0)
{
return new SuccessResponse(
$"Created {ext} file at {path} with {validationWarnings.Count} warning(s)",
new { path, validationWarnings });
}
return new SuccessResponse($"Created {ext} file at {path}",
new { path });
}
private static object ReadFile(JObject @params)
{
var p = new ToolParams(@params);
string path = ValidatePath(p.Get("path"), out string pathError);
if (pathError != null) return new ErrorResponse(pathError);
string fullPath = Path.Combine(Application.dataPath,
path.Substring("Assets/".Length));
fullPath = fullPath.Replace('/', Path.DirectorySeparatorChar);
if (!File.Exists(fullPath))
{
return new ErrorResponse($"File not found: {path}");
}
string contents = File.ReadAllText(fullPath, Encoding.UTF8);
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(contents));
return new SuccessResponse($"Read {Path.GetExtension(path).TrimStart('.')} file at {path}",
new
{
path,
contents,
encodedContents = encoded,
contentsEncoded = true,
lengthBytes = Encoding.UTF8.GetByteCount(contents)
});
}
private static object UpdateFile(JObject @params)
{
var p = new ToolParams(@params);
string path = ValidatePath(p.Get("path"), out string pathError);
if (pathError != null) return new ErrorResponse(pathError);
string contents;
try
{
contents = GetDecodedContents(p);
}
catch (ArgumentException ex)
{
return new ErrorResponse(ex.Message);
}
if (contents == null)
{
return new ErrorResponse("'contents' parameter is required for update.");
}
string fullPath = Path.Combine(Application.dataPath,
path.Substring("Assets/".Length));
fullPath = fullPath.Replace('/', Path.DirectorySeparatorChar);
if (!File.Exists(fullPath))
{
return new ErrorResponse($"File not found: {path}. Use 'create' action for new files.");
}
bool isUxml = path.EndsWith(".uxml", StringComparison.OrdinalIgnoreCase);
var validationWarnings = new List<string>();
if (isUxml)
{
string xmlError = ValidateUxmlContent(contents, validationWarnings);
if (xmlError != null)
{
return new ErrorResponse($"UXML validation failed — file was NOT updated. {xmlError}");
}
contents = EnsureEditorExtensionMode(contents);
}
File.WriteAllText(fullPath, contents, Utf8NoBom);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
if (isUxml)
{
ValidateUxmlPostImport(path, validationWarnings);
}
string ext = Path.GetExtension(path).TrimStart('.');
if (validationWarnings.Count > 0)
{
return new SuccessResponse(
$"Updated {ext} file at {path} with {validationWarnings.Count} warning(s)",
new { path, validationWarnings });
}
return new SuccessResponse($"Updated {ext} file at {path}",
new { path });
}
private static object AttachUIDocument(JObject @params)
{
var p = new ToolParams(@params);
var targetResult = p.GetRequired("target");
var targetError = targetResult.GetOrError(out string target);
if (targetError != null) return targetError;
var sourceResult = p.GetRequired("source_asset");
var sourceError = sourceResult.GetOrError(out string sourceAssetPath);
if (sourceError != null) return sourceError;
sourceAssetPath = AssetPathUtility.SanitizeAssetPath(sourceAssetPath);
if (sourceAssetPath == null)
{
return new ErrorResponse("Invalid source_asset path.");
}
// Find the GameObject
var goInstruction = new JObject { ["find"] = target };
GameObject go = ObjectResolver.Resolve(goInstruction, typeof(GameObject)) as GameObject;
if (go == null)
{
return new ErrorResponse($"Could not find target GameObject: {target}");
}
// Load the VisualTreeAsset
var vta = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(sourceAssetPath);
if (vta == null)
{
return new ErrorResponse($"Could not load VisualTreeAsset at: {sourceAssetPath}");
}
// Load or create PanelSettings
string panelSettingsPath = p.Get("panel_settings") ?? p.Get("panelSettings");
PanelSettings panelSettings = null;
if (!string.IsNullOrEmpty(panelSettingsPath))
{
panelSettingsPath = AssetPathUtility.SanitizeAssetPath(panelSettingsPath);
if (panelSettingsPath != null)
{
panelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>(panelSettingsPath);
}
if (panelSettings == null)
{
return new ErrorResponse($"Could not load PanelSettings at: {panelSettingsPath}");
}
}
else
{
// Find existing or create default PanelSettings
string[] guids = AssetDatabase.FindAssets("t:PanelSettings");
if (guids.Length > 0)
{
string existingPath = AssetDatabase.GUIDToAssetPath(guids[0]);
panelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>(existingPath);
}
if (panelSettings == null)
{
panelSettings = CreateDefaultPanelSettings("Assets/UI/DefaultPanelSettings.asset");
if (panelSettings == null)
{
return new ErrorResponse("Failed to create default PanelSettings.");
}
}
}
Undo.RecordObject(go, "Attach UIDocument");
// Add or get UIDocument component
var uiDoc = go.GetComponent<UIDocument>();
if (uiDoc == null)
{
uiDoc = Undo.AddComponent<UIDocument>(go);
}
uiDoc.visualTreeAsset = vta;
uiDoc.panelSettings = panelSettings;
int sortOrder = p.GetInt("sort_order") ?? 0;
uiDoc.sortingOrder = sortOrder;
EditorUtility.SetDirty(go);
return new SuccessResponse($"Attached UIDocument to {go.name}",
new
{
gameObject = go.name,
sourceAsset = sourceAssetPath,
panelSettings = AssetDatabase.GetAssetPath(panelSettings),
sortOrder
});
}
private static object CreatePanelSettings(JObject @params)
{
var p = new ToolParams(@params);
var pathResult = p.GetRequired("path");
var pathError = pathResult.GetOrError(out string path);
if (pathError != null) return pathError;
path = AssetPathUtility.SanitizeAssetPath(path);
if (path == null)
{
return new ErrorResponse("Invalid path: contains traversal sequences.");
}
if (!path.EndsWith(".asset", StringComparison.OrdinalIgnoreCase))
{
path += ".asset";
}
if (AssetDatabase.LoadAssetAtPath<PanelSettings>(path) != null)
{
return new ErrorResponse($"PanelSettings already exists at {path}");
}
var ps = CreateDefaultPanelSettings(path);
if (ps == null)
{
return new ErrorResponse("Failed to create PanelSettings asset.");
}
// Apply any settings passed as a flat dict
JToken settingsToken = p.GetRaw("settings");
var changes = new List<string>();
if (settingsToken is JObject settingsObj)
{
ApplyPanelSettingsProperties(ps, settingsObj, changes);
}
else
{
// Legacy: support top-level scale_mode / reference_resolution
string scaleMode = p.Get("scale_mode");
if (!string.IsNullOrEmpty(scaleMode))
{
if (Enum.TryParse<PanelScaleMode>(scaleMode, true, out var mode))
{
ps.scaleMode = mode;
changes.Add("scaleMode");
}
}
JToken refResToken = p.GetRaw("reference_resolution");
if (refResToken is JObject refRes)
{
int w = refRes["width"]?.ToObject<int>() ?? 1920;
int h = refRes["height"]?.ToObject<int>() ?? 1080;
ps.referenceResolution = new Vector2Int(w, h);
changes.Add("referenceResolution");
}
}
EditorUtility.SetDirty(ps);
AssetDatabase.SaveAssets();
return new SuccessResponse($"Created PanelSettings at {path}",
new { path, applied = changes });
}
private static object UpdatePanelSettings(JObject @params)
{
var p = new ToolParams(@params);
var pathResult = p.GetRequired("path");
var pathError = pathResult.GetOrError(out string path);
if (pathError != null) return pathError;
path = AssetPathUtility.SanitizeAssetPath(path);
if (path == null)
return new ErrorResponse("Invalid path: contains traversal sequences.");
if (!path.EndsWith(".asset", StringComparison.OrdinalIgnoreCase))
path += ".asset";
var ps = AssetDatabase.LoadAssetAtPath<PanelSettings>(path);
if (ps == null)
return new ErrorResponse($"No PanelSettings found at {path}");
JToken settingsToken = p.GetRaw("settings");
if (settingsToken is not JObject settingsObj || settingsObj.Count == 0)
return new ErrorResponse("'settings' dict is required with at least one property to update.");
var changes = new List<string>();
ApplyPanelSettingsProperties(ps, settingsObj, changes);
if (changes.Count == 0)
return new ErrorResponse("No recognised properties were applied. Check the key names.");
EditorUtility.SetDirty(ps);
AssetDatabase.SaveAssets();
return new SuccessResponse($"Updated PanelSettings at {path}",
new { path, applied = changes });
}
private static PanelSettings CreateDefaultPanelSettings(string path)
{
string dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir))
{
EnsureFolderExists(dir);
}
var ps = ScriptableObject.CreateInstance<PanelSettings>();
AssetDatabase.CreateAsset(ps, path);
AssetDatabase.SaveAssets();
return ps;
}
/// <summary>
/// Generic, data-driven applicator for PanelSettings properties.
/// Accepts a flat JObject where each key maps to a PanelSettings property.
/// Recognised keys (case-insensitive matching via snake_case/camelCase):
/// scaleMode, referenceResolution, screenMatchMode, match,
/// referenceDpi, fallbackDpi, sortingOrder, targetDisplay,
/// clearColor, colorClearValue, clearDepthStencil,
/// themeStyleSheet, dynamicAtlasSettings.
/// </summary>
private static void ApplyPanelSettingsProperties(PanelSettings ps, JObject settings, List<string> changes)
{
foreach (var prop in settings)
{
string key = NormalizeKey(prop.Key);
JToken val = prop.Value;
switch (key)
{
// ── Enum properties ─────────────────────────────────────
case "scalemode":
if (TryParseEnum<PanelScaleMode>(val, out var sm)) { ps.scaleMode = sm; changes.Add("scaleMode"); }
break;
case "screenmatchmode":
if (TryParseEnum<PanelScreenMatchMode>(val, out var smm)) { ps.screenMatchMode = smm; changes.Add("screenMatchMode"); }
break;
// ── Numeric properties ──────────────────────────────────
case "match":
if (TryFloat(val, out float matchVal)) { ps.match = Mathf.Clamp01(matchVal); changes.Add("match"); }
break;
case "referencedpi":
if (TryFloat(val, out float refDpi)) { ps.referenceDpi = refDpi; changes.Add("referenceDpi"); }
break;
case "fallbackdpi":
if (TryFloat(val, out float fbDpi)) { ps.fallbackDpi = fbDpi; changes.Add("fallbackDpi"); }
break;
case "sortingorder":
if (TryInt(val, out int so)) { ps.sortingOrder = so; changes.Add("sortingOrder"); }
break;
case "targetdisplay":
if (TryInt(val, out int td)) { ps.targetDisplay = td; changes.Add("targetDisplay"); }
break;
// ── Bool properties ──────────────────────────────────────
case "clearcolor":
ps.clearColor = ParamCoercion.CoerceBool(val, false);
changes.Add("clearColor");
break;
case "cleardepthstencil":
ps.clearDepthStencil = ParamCoercion.CoerceBool(val, false);
changes.Add("clearDepthStencil");
break;
// ── Composite properties ────────────────────────────────
case "referenceresolution":
if (val is JObject resObj)
{
int w = resObj["width"]?.ToObject<int>() ?? ps.referenceResolution.x;
int h = resObj["height"]?.ToObject<int>() ?? ps.referenceResolution.y;
ps.referenceResolution = new Vector2Int(w, h);
changes.Add("referenceResolution");
}
break;
case "colorclearvalue":
if (TryParseColor(val, out Color clr)) { ps.colorClearValue = clr; changes.Add("colorClearValue"); }
break;
case "dynamicatlassettings":
if (val is JObject daObj) { ApplyDynamicAtlasSettings(ps, daObj, changes); }
break;
// ── Asset reference properties ──────────────────────────
case "themestylesheet":
{
string tsPath = val?.ToString();
if (!string.IsNullOrEmpty(tsPath))
{
var ts = AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(tsPath);
if (ts != null) { ps.themeStyleSheet = ts; changes.Add("themeStyleSheet"); }
}
break;
}
// unknown keys are silently ignored
}
}
}
private static void ApplyDynamicAtlasSettings(PanelSettings ps, JObject da, List<string> changes)
{
var daCopy = ps.dynamicAtlasSettings;
if (da["minAtlasSize"] != null && TryInt(da["minAtlasSize"], out int minSize))
daCopy.minAtlasSize = minSize;
if (da["maxAtlasSize"] != null && TryInt(da["maxAtlasSize"], out int maxSize))
daCopy.maxAtlasSize = maxSize;
if (da["maxSubTextureSize"] != null && TryInt(da["maxSubTextureSize"], out int maxSub))
daCopy.maxSubTextureSize = maxSub;
if (da["activeFilters"] != null && TryParseEnum<DynamicAtlasFilters>(da["activeFilters"], out var af))
daCopy.activeFilters = af;
ps.dynamicAtlasSettings = daCopy;
changes.Add("dynamicAtlasSettings");
}
// ── Tiny helpers to keep the switch compact ─────────────────────────
private static string NormalizeKey(string key)
{
// Strip underscores and lowercase so "scale_mode", "scaleMode", "ScaleMode"
// all match the same case label.
return key.Replace("_", "").ToLowerInvariant();
}
private static bool TryParseEnum<T>(JToken token, out T result) where T : struct, Enum
{
result = default;
string s = token?.ToString();
return !string.IsNullOrEmpty(s) && Enum.TryParse(s, true, out result);
}
private static bool TryFloat(JToken token, out float result)
{
result = 0f;
if (token == null) return false;
if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
{
result = token.ToObject<float>();
return true;
}
return float.TryParse(token.ToString(), out result);
}
private static bool TryInt(JToken token, out int result)
{
result = 0;
if (token == null) return false;
if (token.Type == JTokenType.Integer)
{
result = token.ToObject<int>();
return true;
}
return int.TryParse(token.ToString(), out result);
}
private static bool TryParseColor(JToken token, out Color color)
{
color = Color.clear;
if (token == null) return false;
// Accept "#RRGGBB", "#RRGGBBAA", or {r,g,b,a} object
if (token.Type == JTokenType.String)
{
return ColorUtility.TryParseHtmlString(token.ToString(), out color);
}
if (token is JObject cObj)
{
color = new Color(
cObj["r"]?.ToObject<float>() ?? 0f,
cObj["g"]?.ToObject<float>() ?? 0f,
cObj["b"]?.ToObject<float>() ?? 0f,
cObj["a"]?.ToObject<float>() ?? 1f
);
return true;
}
return false;
}
private static void EnsureFolderExists(string assetFolderPath)
{
if (AssetDatabase.IsValidFolder(assetFolderPath))
return;
string[] parts = assetFolderPath.Replace('\\', '/').Split('/');
string current = parts[0]; // "Assets"
for (int i = 1; i < parts.Length; i++)
{
string next = current + "/" + parts[i];
if (!AssetDatabase.IsValidFolder(next))
{
AssetDatabase.CreateFolder(current, parts[i]);
}
current = next;
}
}
private static object GetVisualTree(JObject @params)
{
var p = new ToolParams(@params);
var targetResult = p.GetRequired("target");
var targetError = targetResult.GetOrError(out string target);
if (targetError != null) return targetError;
int maxDepth = p.GetInt("max_depth") ?? 10;
var goInstruction = new JObject { ["find"] = target };
GameObject go = ObjectResolver.Resolve(goInstruction, typeof(GameObject)) as GameObject;
if (go == null)
{
return new ErrorResponse($"Could not find target GameObject: {target}");
}
var uiDoc = go.GetComponent<UIDocument>();
if (uiDoc == null)
{
return new ErrorResponse($"GameObject {go.name} has no UIDocument component.");
}
var root = uiDoc.rootVisualElement;
if (root == null)
{
return new SuccessResponse($"UIDocument on {go.name} has no visual tree (not yet built).",
new
{
gameObject = go.name,
sourceAsset = uiDoc.visualTreeAsset != null
? AssetDatabase.GetAssetPath(uiDoc.visualTreeAsset)
: null,
tree = (object)null
});
}
var tree = SerializeVisualElement(root, 0, maxDepth);
return new SuccessResponse($"Visual tree for UIDocument on {go.name}",
new
{
gameObject = go.name,
sourceAsset = uiDoc.visualTreeAsset != null
? AssetDatabase.GetAssetPath(uiDoc.visualTreeAsset)
: null,
tree
});
}
private static object SerializeVisualElement(VisualElement element, int depth, int maxDepth)
{
var result = new Dictionary<string, object>
{
["type"] = element.GetType().Name,
["name"] = element.name ?? "",
["classes"] = new List<string>(element.GetClasses()),
};
// Include basic computed style info
var style = new Dictionary<string, object>();
var resolved = element.resolvedStyle;
if (resolved.width > 0) style["width"] = resolved.width;
if (resolved.height > 0) style["height"] = resolved.height;
if (resolved.color != Color.clear)
style["color"] = ColorToHex(resolved.color);
if (resolved.backgroundColor != Color.clear)
style["backgroundColor"] = ColorToHex(resolved.backgroundColor);
if (resolved.fontSize > 0) style["fontSize"] = resolved.fontSize;
if (style.Count > 0)
result["resolvedStyle"] = style;
// Include text content for labels/buttons
if (element is TextElement textEl && !string.IsNullOrEmpty(textEl.text))
{
result["text"] = textEl.text;
}
// Serialize children
if (depth < maxDepth && element.childCount > 0)
{
var children = new List<object>();
foreach (var child in element.Children())
{
children.Add(SerializeVisualElement(child, depth + 1, maxDepth));
}
result["children"] = children;
}
else if (element.childCount > 0)
{
result["childCount"] = element.childCount;
result["truncated"] = true;
}
return result;
}
// ---- Render UI ----
// Persistent RenderTextures keyed by PanelSettings instance ID so the panel
// renders into them automatically every frame.
private static readonly Dictionary<int, RenderTexture> s_panelRTs = new();
// Play-mode coroutine capture state. Only one capture is in-flight at a
// time; concurrent render_ui calls while a capture is pending are rejected
// with an explicit error. Only used when the Screen Capture module is present.
#if MCP_HAS_SCREEN_CAPTURE
private static Texture2D s_pendingCaptureTex;
private static bool s_pendingCaptureDone;
private static bool s_pendingCaptureStarted;
#endif
private static object RenderUI(JObject @params)
{
var p = new ToolParams(@params);
string target = p.Get("target");
string uxmlPath = p.Get("path");
int width = p.GetInt("width") ?? 1920;
int height = p.GetInt("height") ?? 1080;
bool includeImage = p.GetBool("include_image") || p.GetBool("includeImage");
int maxResolution = p.GetInt("max_resolution") ?? p.GetInt("maxResolution") ?? 640;
string fileName = p.Get("file_name") ?? p.Get("fileName");
string outputFolderOverride = p.Get("output_folder") ?? p.Get("outputFolder");
if (string.IsNullOrEmpty(target) && string.IsNullOrEmpty(uxmlPath))
{
return new ErrorResponse("Either 'target' (GameObject with UIDocument) or 'path' (UXML asset path) is required.");
}
string resolvedFolderSpec = ScreenshotPreferences.Resolve(outputFolderOverride);
string resolvedFolderAbs;
try
{
resolvedFolderAbs = ScreenshotUtility.ResolveFolderAbsolute(resolvedFolderSpec);
}
catch (InvalidOperationException ex)
{
return new ErrorResponse(ex.Message);
}
// ── Play-mode capture via ScreenCapture coroutine ──────────────────────
// PanelSettings.targetTexture is read in the same frame it is assigned,
// so the RT is always blank in a synchronous tool call. In play mode we
// dispatch a WaitForEndOfFrame coroutine that uses ScreenCapture, which
// captures the fully-composited game view (including UI Toolkit overlays).
// First call: queues the capture and returns "pending".
// Second call: result is ready – save PNG and return data.
if (Application.isPlaying)
{
#if MCP_HAS_SCREEN_CAPTURE
// Build the output paths (used by both the pending and ready branches)
string resolvedPlayName = string.IsNullOrWhiteSpace(fileName)
? $"ui-render-{DateTime.Now:yyyyMMdd-HHmmss}.png"
: fileName.Trim();
if (!resolvedPlayName.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
resolvedPlayName += ".png";
Directory.CreateDirectory(resolvedFolderAbs);
string playFullPath = Path.Combine(resolvedFolderAbs, resolvedPlayName).Replace('\\', '/');
playFullPath = EnsureUniqueFilePath(playFullPath);
string playProjectRelPath = ScreenshotUtility.ToProjectRelativePath(playFullPath);
// ── Case 1: capture is ready ──────────────────────────────────────
if (s_pendingCaptureDone && s_pendingCaptureTex != null)
{
var captureTex = s_pendingCaptureTex;
s_pendingCaptureDone = false;
s_pendingCaptureTex = null;
int captureW = captureTex.width;
int captureH = captureTex.height;
byte[] capturePng = captureTex.EncodeToPNG();
UnityEngine.Object.DestroyImmediate(captureTex);
File.WriteAllBytes(playFullPath, capturePng);
if (ScreenshotUtility.IsUnderAssets(playProjectRelPath))
AssetDatabase.ImportAsset(playProjectRelPath, ImportAssetOptions.ForceSynchronousImport);
var playData = new Dictionary<string, object>
{
{ "path", playProjectRelPath },
{ "fullPath", playFullPath },
{ "width", captureW },
{ "height", captureH },
{ "hasContent", true },
};
if (!string.IsNullOrEmpty(target)) playData["gameObject"] = target;
if (!string.IsNullOrEmpty(uxmlPath)) playData["sourceAsset"] = uxmlPath;
if (includeImage)
{
int targetMax = maxResolution > 0 ? maxResolution : 640;
Texture2D downscaled = null;
try
{
var fullTex = new Texture2D(captureW, captureH, TextureFormat.RGBA32, false);
fullTex.LoadImage(capturePng);
if (captureW > targetMax || captureH > targetMax)
{
downscaled = ScreenshotUtility.DownscaleTexture(fullTex, targetMax);
playData["imageBase64"] = Convert.ToBase64String(downscaled.EncodeToPNG());
playData["imageWidth"] = downscaled.width;
playData["imageHeight"] = downscaled.height;
}
else
{
playData["imageBase64"] = Convert.ToBase64String(capturePng);
playData["imageWidth"] = captureW;
playData["imageHeight"] = captureH;
}
UnityEngine.Object.DestroyImmediate(fullTex);
}
finally
{
if (downscaled != null) UnityEngine.Object.DestroyImmediate(downscaled);
}
}
return new SuccessResponse($"UI render saved to '{playProjectRelPath}'.", playData);
}
// ── Case 2: start a new capture ───────────────────────────────────
// Only one capture in flight at a time. If one is already pending,
// reject rather than silently overwriting the state.
if (s_pendingCaptureStarted)
{
return new ErrorResponse(
"Cannot capture: another capture is already in progress.",
new { retry_after_ms = 100, reason = "capture_in_progress" });
}
s_pendingCaptureDone = false;
s_pendingCaptureTex = null;
s_pendingCaptureStarted = true;
ScreenshotCapturer.Begin(1, tex =>
{
s_pendingCaptureTex = tex;
s_pendingCaptureDone = true;
s_pendingCaptureStarted = false;
});
return new SuccessResponse(
"Play-mode screenshot capture queued (WaitForEndOfFrame). Call render_ui again to retrieve the rendered image.",
new Dictionary<string, object>
{
{ "pending", true },
{ "gameObject", (object)target ?? uxmlPath },
{ "note", "A screen capture was scheduled for the end of this frame. Call render_ui once more to get the result." }
});
#else
return new ErrorResponse(
"Play-mode UI capture requires the Screen Capture module (com.unity.modules.screencapture), " +
"which is not installed. Enable it via Window > Package Manager > Built-in > Screen Capture, " +
"or render the UI outside Play mode (which captures via a RenderTexture instead).");
#endif
}
// ── End play-mode branch ────────────────────────────────────────────────
// Resolve UIDocument
UIDocument uiDoc = null;
GameObject tempGo = null;
PanelSettings tempPs = null;
try
{
if (!string.IsNullOrEmpty(target))
{
var goInstruction = new JObject { ["find"] = target };
GameObject go = ObjectResolver.Resolve(goInstruction, typeof(GameObject)) as GameObject;
if (go == null)
return new ErrorResponse($"Could not find target GameObject: {target}");
uiDoc = go.GetComponent<UIDocument>();
if (uiDoc == null)
return new ErrorResponse($"GameObject '{go.name}' has no UIDocument component.");
}
else
{
uxmlPath = AssetPathUtility.SanitizeAssetPath(uxmlPath);
if (uxmlPath == null)
return new ErrorResponse("Invalid UXML path.");
var vta = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxmlPath);
if (vta == null)
return new ErrorResponse($"Could not load VisualTreeAsset at: {uxmlPath}");
tempGo = new GameObject("__MCP_UI_Render_Temp__");
tempGo.hideFlags = HideFlags.HideAndDontSave;
uiDoc = tempGo.AddComponent<UIDocument>();