-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
PropertyEditor.cs
1947 lines (1658 loc) · 79.9 KB
/
PropertyEditor.cs
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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.AddComponent;
using UnityEditor.VersionControl;
using UnityEngine;
using UnityEditorInternal;
using UnityEditorInternal.VersionControl;
using UnityEditor.StyleSheets;
using UnityEngine.Assertions.Comparers;
using UnityEngine.UIElements;
using UnityEditor.SceneManagement;
using Object = UnityEngine.Object;
using AssetImporterEditor = UnityEditor.Experimental.AssetImporters.AssetImporterEditor;
using JetBrains.Annotations;
namespace UnityEditor
{
interface IPropertyView
{
ActiveEditorTracker tracker { get; }
InspectorMode inspectorMode { get; }
bool useUIElementsDefaultInspector { get; }
HashSet<int> editorsWithImportedObjectLabel { get; }
Editor lastInteractedEditor { get; set; }
GUIView parent { get; }
EditorDragging editorDragging { get; }
IMGUIContainer CreateIMGUIContainer(Action headerOnGUI, string v);
bool IsMultiEditingSupported(Editor editor, Object target);
bool WasEditorVisible(Editor[] editors, int editorIndex, Object target);
bool ShouldCullEditor(Editor[] editors, int editorIndex);
void Repaint();
}
interface IPropertySourceOpener
{
Object hoveredObject { get; }
}
class PropertyEditor : EditorWindow, IPropertyView, IHasCustomMenu
{
internal const string k_AssetPropertiesMenuItemName = "Assets/Properties... _&P";
protected const string s_MultiEditClassName = "unity-inspector-no-multi-edit-warning";
protected const string s_EditorListClassName = "unity-inspector-editors-list";
protected const string s_AddComponentClassName = "unity-inspector-add-component-button";
protected const string s_HeaderInfoClassName = "unity-inspector-header-info";
protected const string s_FooterInfoClassName = "unity-inspector-footer-info";
internal const string s_MainContainerClassName = "unity-inspector-main-container";
protected const float kBottomToolbarHeight = 21f;
protected const float kAddComponentButtonHeight = 45f;
internal const float kEditorElementPaddingBottom = 2f;
protected const float k_MinAreaAbovePreview = 130;
protected const float k_InspectorPreviewMinHeight = 130;
protected const float k_InspectorPreviewMinTotalHeight = k_InspectorPreviewMinHeight + kBottomToolbarHeight;
protected const int k_MinimumRootVisualHeight = 81;
protected const int k_MinimumWindowWidth = 275;
protected const int k_AutoScrollZoneHeight = 24;
protected const long delayRepaintWhilePlayingAnimation = 150; // Delay between repaints in milliseconds while playing animation
protected long m_LastUpdateWhilePlayingAnimation = 0;
[SerializeField] protected List<Object> m_ObjectsLockedBeforeSerialization = new List<Object>();
[SerializeField] protected List<int> m_InstanceIDsLockedBeforeSerialization = new List<int>();
[SerializeField] protected PreviewResizer m_PreviewResizer = new PreviewResizer();
[SerializeField] protected LabelGUI m_LabelGUI = new LabelGUI();
[SerializeField] protected int m_LastInspectedObjectInstanceID = -1;
[SerializeField] protected float m_LastVerticalScrollValue = 0;
[SerializeField] protected string m_AssetGUID = "";
[SerializeField] protected int m_InstanceID = 0;
private Object m_InspectedObject;
private static PropertyEditor s_LastPropertyEditor;
protected int m_LastInitialEditorInstanceID;
protected Component[] m_ComponentsInPrefabSource;
protected HashSet<Component> m_RemovedComponents;
protected bool m_ResetKeyboardControl;
internal bool m_OpenAddComponentMenu = false;
protected ActiveEditorTracker m_Tracker;
protected AssetBundleNameGUI m_AssetBundleNameGUI = new AssetBundleNameGUI();
protected TypeSelectionList m_TypeSelectionList = null;
protected double m_lastRenderedTime;
protected List<IPreviewable> m_Previews;
protected Dictionary<Type, List<Type>> m_PreviewableTypes;
protected IPreviewable m_SelectedPreview;
protected VisualElement m_EditorsElement;
protected VisualElement editorsElement => m_EditorsElement ?? (m_EditorsElement = FindVisualElementInTreeByClassName(s_EditorListClassName));
protected VisualElement m_RemovedPrefabComponentsElement;
protected VisualElement m_PreviewAndLabelElement;
protected VisualElement previewAndLabelElement => m_PreviewAndLabelElement ?? (m_PreviewAndLabelElement = FindVisualElementInTreeByClassName(s_FooterInfoClassName));
protected VisualElement m_VersionControlElement;
protected VisualElement versionControlElement => m_VersionControlElement ?? (m_VersionControlElement = FindVisualElementInTreeByClassName(s_HeaderInfoClassName));
protected static Dictionary<Editor, VersionControlBarState> m_VersionControlBarState = new Dictionary<Editor, VersionControlBarState>();
protected VisualElement m_MultiEditLabel;
protected ScrollView m_ScrollView;
protected bool m_TrackerResetInserted;
internal bool m_FirstInitialize;
protected float m_PreviousFooterHeight = -1;
protected bool m_PreviousPreviewExpandedState;
protected bool m_HasPreview;
protected HashSet<int> m_DrawnSelection = new HashSet<int>();
protected InspectorMode m_InspectorMode = InspectorMode.Normal;
public GUIView parent => m_Parent;
public HashSet<int> editorsWithImportedObjectLabel { get; } = new HashSet<int>();
public EditorDragging editorDragging { get; }
public bool useUIElementsDefaultInspector { get; internal set; } = false;
public Editor lastInteractedEditor { get; set; }
internal static PropertyEditor CurrentPropertyEditor { get; private set; }
public InspectorMode inspectorMode
{
get { return m_InspectorMode; }
set { SetMode(value); }
}
public ActiveEditorTracker tracker
{
get
{
CreateTracker();
return m_Tracker;
}
}
protected Rect bottomAreaDropRectangle
{
get
{
var worldEditorRect = editorsElement.LocalToWorld(editorsElement.rect);
var worldRootRect = rootVisualElement.LocalToWorld(rootVisualElement.rect);
return new Rect(
worldEditorRect.x,
worldEditorRect.y + worldEditorRect.height,
worldEditorRect.width,
worldRootRect.y + worldRootRect.height - worldEditorRect.height - worldEditorRect.y);
}
}
protected static class Styles
{
public static readonly GUIStyle preToolbar = "preToolbar";
public static readonly GUIStyle preToolbar2 = "preToolbar2";
public static readonly GUIStyle preToolbarLabel = "ToolbarBoldLabel";
public static readonly GUIStyle preDropDown = "preDropDown";
public static readonly GUIStyle dragHandle = "RL DragHandle";
public static readonly GUIStyle lockButton = "IN LockButton";
public static readonly GUIStyle insertionMarker = "InsertionMarker";
public static readonly GUIContent preTitle = EditorGUIUtility.TrTextContent("Preview");
public static readonly GUIContent labelTitle = EditorGUIUtility.TrTextContent("Asset Labels");
public static readonly GUIContent addComponentLabel = EditorGUIUtility.TrTextContent("Add Component");
public static GUIStyle preBackground = "preBackground";
public static GUIStyle footer = "IN Footer";
public static GUIStyle preMargins = new GUIStyle() {margin = new RectOffset(0, 0, 0, 4)};
public static GUIStyle preOptionsButton = new GUIStyle(EditorStyles.toolbarButtonRight) { padding = new RectOffset(), contentOffset = new Vector2(1, 0) };
public static GUIStyle addComponentArea = EditorStyles.inspectorTitlebar;
public static GUIStyle addComponentButtonStyle = "AC Button";
public static readonly GUIContent menuIcon = EditorGUIUtility.TrIconContent("_Menu");
public static GUIStyle previewMiniLabel = EditorStyles.whiteMiniLabel;
public static GUIStyle typeSelection = "IN TypeSelection";
public static readonly GUIContent vcsCheckoutHint = EditorGUIUtility.TrTextContent("Under Version Control\nCheck out this asset in order to make changes.", EditorGUIUtility.GetHelpIcon(MessageType.Info));
public static readonly GUIContent vcsNotConnected = EditorGUIUtility.TrTextContent("VCS ({0}) is not connected");
public static readonly GUIContent vcsOffline = EditorGUIUtility.TrTextContent("Work Offline option is active");
public static readonly GUIContent vcsSettings = EditorGUIUtility.TrTextContent("Settings");
public static readonly GUIContent vcsCheckout = EditorGUIUtility.TrTextContent("Check Out");
public static readonly GUIContent vcsCheckoutMeta = EditorGUIUtility.TrTextContent("Check Out Meta");
public static readonly GUIContent vcsAdd = EditorGUIUtility.TrTextContent("Add");
public static readonly GUIContent vcsLock = EditorGUIUtility.TrTextContent("Lock");
public static readonly GUIContent vcsUnlock = EditorGUIUtility.TrTextContent("Unlock");
public static readonly GUIContent vcsSubmit = EditorGUIUtility.TrTextContent("Submit");
public static readonly GUIContent vcsRevert = EditorGUIUtility.TrTextContent("Revert");
public static readonly GUIContent vcsRevertUnchanged = EditorGUIUtility.TrTextContent("Revert Unchanged");
public static readonly GUIContent[] vcsRevertMenuNames = {vcsRevertUnchanged};
public static readonly GenericMenu.MenuFunction2[] vcsRevertMenuActions = {DoRevertUnchanged};
public static readonly GUIStyle vcsButtonStyle = EditorStyles.miniButton;
public static GUIStyle vcsRevertStyle = new GUIStyle(EditorStyles.dropDownList);
public static readonly GUIStyle vcsBarStyleOneRow = EditorStyles.toolbar;
public static GUIStyle vcsBarStyleTwoRows = new GUIStyle(EditorStyles.toolbar);
public static readonly string objectDisabledModuleWarningFormat = L10n.Tr(
"The built-in package '{0}', which implements this component type, has been disabled in Package Manager. This object will be removed in play mode and from any builds you make."
);
public static readonly string objectDisabledModuleWithDependencyWarningFormat = L10n.Tr(
"The built-in package '{0}', which is required by the package '{1}', which implements this component type, has been disabled in Package Manager. This object will be removed in play mode and from any builds you make."
);
public static SVC<float> lineSeparatorOffset = new SVC<float>("AC-Button", "--separator-line-top-offset");
public static SVC<Color> lineSeparatorColor = new SVC<Color>("--theme-line-separator-color", Color.red);
static Styles()
{
vcsRevertStyle.padding.right = 15;
vcsBarStyleTwoRows.fixedHeight *= 2;
}
}
protected class VersionControlBarState
{
public bool settings;
public bool revert;
public bool revertUnchanged;
public bool checkout;
public bool add;
public bool submit;
public bool @lock;
public bool unlock;
public Editor editor;
public AssetList assets = new AssetList();
public int GetButtonCount()
{
var c = 0;
if (settings) ++c;
if (revert) ++c; // revertUnchanged is same button in a drop-down
if (checkout) ++c;
if (add) ++c;
if (submit) ++c;
if (@lock) ++c;
if (unlock) ++c;
return c;
}
public static VersionControlBarState Calculate(Editor assetEditor, Asset asset, bool connected)
{
var res = new VersionControlBarState();
if (!connected)
{
res.settings = true;
return res;
}
var isFolder = asset.isFolder && !Provider.isVersioningFolders;
res.assets.AddRange(assetEditor.targets.Select(o => Provider.GetAssetByPath(AssetDatabase.GetAssetPath(o))));
res.assets = Provider.ConsolidateAssetList(res.assets, CheckoutMode.Both);
res.editor = assetEditor;
res.revert = Provider.RevertIsValid(res.assets, RevertMode.Normal);
res.revertUnchanged = Provider.RevertIsValid(res.assets, RevertMode.Unchanged);
bool checkoutBoth = assetEditor.target == null || Provider.NeedToCheckOutBoth(assetEditor.target);
res.checkout = isFolder || Provider.CheckoutIsValid(res.assets, checkoutBoth ? CheckoutMode.Both : CheckoutMode.Meta);
res.add = Provider.AddIsValid(res.assets);
res.submit = Provider.SubmitIsValid(null, res.assets);
res.@lock = Provider.hasLockingSupport && !isFolder && Provider.LockIsValid(res.assets);
res.unlock = Provider.hasLockingSupport && !isFolder && Provider.UnlockIsValid(res.assets);
return res;
}
}
internal PropertyEditor()
{
editorDragging = new EditorDragging(this);
minSize = new Vector2(k_MinimumWindowWidth, minSize.y);
}
[UsedImplicitly]
protected virtual void OnDestroy()
{
if (m_Tracker != null)
m_Tracker.Destroy();
}
[UsedImplicitly]
protected virtual void OnFocusChanged(bool focus)
{
// focusing away from the editor flushes VCS state cache and might get
// updated states from external clients; make sure to recalculate which VCS
// buttons should be visible
ClearVersionControlBarState();
}
[UsedImplicitly]
protected virtual void OnEnable()
{
LoadVisualTreeFromUxml();
m_PreviewResizer.localFrame = true;
m_PreviewResizer.Init("InspectorPreview");
m_LabelGUI.OnEnable();
m_FirstInitialize = true;
CreateTracker();
EditorApplication.focusChanged += OnFocusChanged;
}
[UsedImplicitly]
protected virtual void OnDisable()
{
// save vertical scroll position
m_LastInspectedObjectInstanceID = GetInspectedObject()?.GetInstanceID() ?? -1;
m_LastVerticalScrollValue = m_ScrollView?.verticalScroller.value ?? 0;
EditorApplication.focusChanged -= OnFocusChanged;
}
[UsedImplicitly]
protected virtual void OnLostFocus()
{
m_LabelGUI.OnLostFocus();
}
protected virtual bool CloseIfEmpty()
{
// It should never close if its tracker is not locked.
if (!tracker.isLocked)
{
return false;
}
// We can rely on the tracker to always keep valid Objects
// even after an assemblyreload or assetdatabase refresh.
List<Object> locked = new List<Object>();
tracker.GetObjectsLockedByThisTracker(locked);
if (locked.Any(o => o != null))
return false;
EditorApplication.delayCall += Close;
return true;
}
[UsedImplicitly]
protected virtual void OnInspectorUpdate()
{
if (CloseIfEmpty())
return;
// Check if scripts have changed without calling set dirty
tracker.VerifyModifiedMonoBehaviours();
if (!tracker.isDirty || !ReadyToRepaint())
return;
Repaint();
}
[UsedImplicitly]
protected virtual void OnGUI()
{
if (m_FirstInitialize)
RebuildContentsContainers();
}
static Editor[] s_Editors = new Editor[10];
[UsedImplicitly]
protected virtual void Update()
{
ActiveEditorTracker.Internal_GetActiveEditorsNonAlloc(tracker, s_Editors);
if (s_Editors.Length == 0)
return;
bool wantsRepaint = false;
foreach (var myEditor in s_Editors)
{
if (myEditor != null && myEditor.RequiresConstantRepaint() && !myEditor.hideInspector)
wantsRepaint = true;
}
if (wantsRepaint && m_lastRenderedTime + 0.033f < EditorApplication.timeSinceStartup)
{
m_lastRenderedTime = EditorApplication.timeSinceStartup;
Repaint();
}
}
protected void SetMode(InspectorMode mode)
{
if (m_InspectorMode != mode)
{
m_InspectorMode = mode;
RefreshTitle();
// Clear the editors Element so that a real rebuild is done
editorsElement.Clear();
tracker.inspectorMode = mode;
m_ResetKeyboardControl = true;
}
}
protected void SetTitle(Object obj)
{
var objTitle = ObjectNames.GetInspectorTitle(obj);
var titleTooltip = objTitle;
if (!String.IsNullOrEmpty(m_AssetGUID))
titleTooltip = AssetDatabase.GUIDToAssetPath(m_AssetGUID);
else
{
var go = obj as GameObject;
if (go)
titleTooltip = EditorUtility.GetHierarchyPath(go);
else if (obj is Component c)
titleTooltip = $"{EditorUtility.GetHierarchyPath(c.gameObject)} ({objTitle})";
}
titleContent = EditorGUIUtility.TrTextContentWithIcon(obj.name, titleTooltip, "UnityEditor.InspectorWindow");
titleContent.image = AssetPreview.GetMiniThumbnail(obj);
}
protected virtual void RefreshTitle()
{
var obj = GetInspectedObject();
if (!obj)
return;
SetTitle(obj);
}
private VisualElement FindVisualElementInTreeByClassName(string elementClassName)
{
return rootVisualElement.Q(className: elementClassName);
}
internal static void ClearVersionControlBarState()
{
m_VersionControlBarState.Clear();
}
protected void LoadVisualTreeFromUxml()
{
var tpl = EditorGUIUtility.Load("UXML/InspectorWindow/InspectorWindow.uxml") as VisualTreeAsset;
var fContainer = rootVisualElement.Query(null, s_MainContainerClassName).First();
VisualElement container = fContainer ?? tpl.Instantiate();
container.AddToClassList(s_MainContainerClassName);
rootVisualElement.hierarchy.Add(container);
m_ScrollView = container.Q<ScrollView>();
var multiContainer = rootVisualElement.Q(className: s_MultiEditClassName);
multiContainer.Query<TextElement>().ForEach((label) => label.text = L10n.Tr(label.text));
multiContainer.RemoveFromHierarchy();
m_MultiEditLabel = multiContainer;
rootVisualElement.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
rootVisualElement.AddStyleSheetPath("StyleSheets/InspectorWindow/InspectorWindow.uss");
}
private void OnGeometryChanged(GeometryChangedEvent e)
{
if (m_PreviewResizer.GetExpanded())
{
if (previewAndLabelElement.layout.height > 0 &&
rootVisualElement.layout.height <= k_MinimumRootVisualHeight + m_PreviewResizer.containerMinimumHeightExpanded)
{
m_PreviewResizer.SetExpanded(false);
}
}
RestoreVerticalScrollIfNeeded();
}
public virtual void AddItemsToMenu(GenericMenu menu)
{
if (IsAnyComponentCollapsed())
menu.AddItem(EditorGUIUtility.TrTextContent("Expand All Components"), false, ExpandAllComponents);
else
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Expand All Components"));
if (IsAnyComponentExpanded())
menu.AddItem(EditorGUIUtility.TrTextContent("Collapse All Components"), false, CollapseAllComponents);
else
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Collapse All Components"));
if (m_Tracker != null)
{
bool addedSeparator = false;
foreach (var editor in m_Tracker.activeEditors)
{
var menuContainer = editor as IHasCustomMenu;
if (menuContainer != null)
{
if (!addedSeparator)
{
menu.AddSeparator(String.Empty);
addedSeparator = true;
}
menuContainer.AddItemsToMenu(menu);
}
}
}
menu.AddSeparator("");
menu.AddItem(EditorGUIUtility.TrTextContent("Ping"), false, () => EditorGUIUtility.PingObject(GetInspectedObject()));
}
protected void ExpandAllComponents()
{
var editors = tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
tracker.SetVisible(i, 1);
}
protected bool IsAnyComponentCollapsed()
{
if (Selection.activeGameObject == null)
return false; // If the selection is not a game object then disable the option.
var editors = tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
{
if (tracker.GetVisible(i) == 0)
return true;
}
return false;
}
protected void CollapseAllComponents()
{
var editors = tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
tracker.SetVisible(i, 0);
}
protected bool IsAnyComponentExpanded()
{
if (Selection.activeGameObject == null)
return false;
var editors = this.tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
{
if (this.tracker.GetVisible(i) == 1)
return true;
}
return false;
}
protected bool LoadPersistedObject()
{
if (String.IsNullOrEmpty(m_AssetGUID) && m_InstanceID == 0)
return false;
if (!String.IsNullOrEmpty(m_AssetGUID))
{
var assetPath = AssetDatabase.GUIDToAssetPath(m_AssetGUID);
m_InspectedObject = AssetDatabase.LoadAssetAtPath<Object>(assetPath);
}
else if (m_InstanceID != 0)
{
m_InspectedObject = FindObjectFromInstanceID(m_InstanceID) ?? ForceLoadFromInstanceID(m_InstanceID);
}
if (m_InspectedObject)
{
SetTitle(m_InspectedObject);
m_Tracker.SetObjectsLockedByThisTracker(new List<Object> { m_InspectedObject });
}
else
{
// Failed to load object, lets close this property editor.
EditorApplication.delayCall += Close;
return false;
}
return true;
}
protected virtual void CreateTracker()
{
if (m_Tracker != null)
return;
m_Tracker = new ActiveEditorTracker { inspectorMode = InspectorMode.Normal };
if (LoadPersistedObject())
m_Tracker.RebuildIfNecessary();
}
private void OnTrackerRebuilt()
{
ExtractPrefabComponents();
// tracker gets rebuilt when selection or objects change; make sure to recalc which VCS
// buttons are shown
ClearVersionControlBarState();
}
private void ExtractPrefabComponents()
{
m_LastInitialEditorInstanceID = m_Tracker.activeEditors[0].GetInstanceID();
m_ComponentsInPrefabSource = null;
if (m_RemovedComponents == null)
m_RemovedComponents = new HashSet<Component>();
m_RemovedComponents.Clear();
if (m_Tracker.activeEditors.Length == 0)
return;
if (m_Tracker.activeEditors[0].targets.Length != 1)
return;
GameObject go = m_Tracker.activeEditors[0].target as GameObject;
if (go == null && m_Tracker.activeEditors[0] is PrefabImporterEditor)
go = m_Tracker.activeEditors[1].target as GameObject;
if (go == null)
return;
GameObject sourceGo = PrefabUtility.GetCorrespondingConnectedObjectFromSource(go);
if (sourceGo == null)
return;
m_ComponentsInPrefabSource = sourceGo.GetComponents<Component>();
var removedComponentsList = PrefabOverridesUtility.GetRemovedComponentsForSingleGameObject(go);
for (int i = 0; i < removedComponentsList.Count; i++)
{
m_RemovedComponents.Add(removedComponentsList[i].assetComponent);
}
}
protected void CreatePreviewables()
{
if (m_Previews != null)
return;
m_Previews = new List<IPreviewable>();
var activeEditors = tracker?.activeEditors;
if (activeEditors == null || activeEditors.Length == 0)
return;
foreach (var editor in activeEditors)
{
IEnumerable<IPreviewable> previews = GetPreviewsForType(editor);
foreach (var preview in previews)
{
m_Previews.Add(preview);
}
}
}
private Dictionary<Type, List<Type>> GetPreviewableTypes()
{
// We initialize this list once per PropertyEditor, instead of globally.
// This means that if the user is debugging an IPreviewable structure,
// the PropertyEditor can be closed and reopened to refresh this list.
//
if (m_PreviewableTypes == null)
{
InspectorWindowUtils.GetPreviewableTypes(out m_PreviewableTypes);
}
return m_PreviewableTypes;
}
private IEnumerable<IPreviewable> GetPreviewsForType(Editor editor)
{
List<IPreviewable> previews = new List<IPreviewable>();
// Retrieve the type we are looking for.
if (editor == null || editor.target == null)
return previews;
Type targetType = editor.target.GetType();
if (!GetPreviewableTypes().ContainsKey(targetType))
return previews;
var previewerList = GetPreviewableTypes()[targetType];
if (previewerList == null)
return previews;
foreach (var previewerType in previewerList)
{
var preview = Activator.CreateInstance(previewerType) as IPreviewable;
preview.Initialize(editor.targets);
previews.Add(preview);
}
return previews;
}
private void ClearTrackerDirtyOnRepaint()
{
if (Event.current.type == EventType.Repaint)
{
tracker.ClearDirty();
}
}
public IMGUIContainer CreateIMGUIContainer(Action onGUIHandler, string name = null)
{
IMGUIContainer result = null;
if (m_TrackerResetInserted)
{
result = new IMGUIContainer(onGUIHandler);
}
else
{
m_TrackerResetInserted = true;
result = new IMGUIContainer(() =>
{
ClearTrackerDirtyOnRepaint();
onGUIHandler();
});
}
if (name != null)
{
result.name = name;
}
return result;
}
protected virtual void BeginRebuildContentContainers() {}
protected virtual void EndRebuildContentContainers() {}
internal virtual void RebuildContentsContainers()
{
m_Previews = null;
m_SelectedPreview = null;
m_TypeSelectionList = null;
m_FirstInitialize = false;
editorsWithImportedObjectLabel.Clear();
m_LastInitialEditorInstanceID = 0;
if (m_RemovedPrefabComponentsElement != null)
{
m_RemovedPrefabComponentsElement.RemoveFromHierarchy();
m_RemovedPrefabComponentsElement = null;
}
BeginRebuildContentContainers();
ResetKeyboardControl();
var addComponentButton = rootVisualElement.Q(className: s_AddComponentClassName);
if (addComponentButton != null)
addComponentButton.Clear();
if (versionControlElement != null)
versionControlElement.Clear();
if (previewAndLabelElement != null)
previewAndLabelElement.Clear();
Editor[] editors = tracker.activeEditors;
if (editors.Any() && versionControlElement != null)
{
versionControlElement.Add(CreateIMGUIContainer(
() => VersionControlBar(InspectorWindowUtils.GetFirstNonImportInspectorEditor(editors))));
}
DrawEditors(editors);
var labelMustBeAdded = editorsElement != null && m_MultiEditLabel.parent != editorsElement;
// The PrefabImporterEditor can hide its imported objects if it detects missing scripts. In this case
// do not add the multi editing warning
var assetImporter = GetAssetImporter(editors);
if (assetImporter != null && !assetImporter.showImportedObject)
labelMustBeAdded = false;
if (tracker.hasComponentsWhichCannotBeMultiEdited)
{
if (editors.Length == 0 && !tracker.isLocked && Selection.objects.Length > 0 && editorsElement != null)
{
editorsElement.Add(CreateIMGUIContainer(DrawSelectionPickerList));
}
else
{
if (labelMustBeAdded && editorsElement != null)
{
editorsElement.Add(m_MultiEditLabel);
}
}
}
else if (m_MultiEditLabel != null)
{
m_MultiEditLabel.RemoveFromHierarchy();
}
if (addComponentButton != null && editors.Any() && RootEditorUtils.SupportsAddComponent(editors))
{
addComponentButton.Add(CreateIMGUIContainer(() =>
{
EditorGUI.indentLevel = 0;
AddComponentButton(editors);
}));
}
if (m_PreviewResizer != null && editors.Any())
{
var previewAndLabelsContainer = CreateIMGUIContainer(DrawPreviewAndLabels, "preview-container");
m_PreviewResizer.SetContainer(previewAndLabelsContainer, kBottomToolbarHeight);
if (previewAndLabelElement != null)
previewAndLabelElement.Add(previewAndLabelsContainer);
}
rootVisualElement.MarkDirtyRepaint();
ScriptAttributeUtility.ClearGlobalCache();
rootVisualElement.RegisterCallback<DragUpdatedEvent>(DragOverBottomArea);
rootVisualElement.RegisterCallback<DragPerformEvent>(DragPerformInBottomArea);
rootVisualElement.RegisterCallback<MouseEnterEvent>((e) => { CurrentPropertyEditor = this; });
rootVisualElement.RegisterCallback<MouseLeaveEvent>((e) => { CurrentPropertyEditor = null; });
EndRebuildContentContainers();
Repaint();
RefreshTitle();
}
internal void AutoScroll(Vector2 mousePosition)
{
if (m_ScrollView != null)
{
// implement auto-scroll for easier component drag'n'drop,
// we define a zone of height = k_AutoScrollZoneHeight
// at the top/bottom of the scrollView viewport,
// while dragging, when the mouse moves in these zones,
// we automatically scroll up/down
var localDragPosition = m_ScrollView.contentViewport.WorldToLocal(mousePosition);
if (localDragPosition.y < k_AutoScrollZoneHeight)
m_ScrollView.verticalScroller.ScrollPageUp();
else if (localDragPosition.y > m_ScrollView.contentViewport.rect.height - k_AutoScrollZoneHeight)
m_ScrollView.verticalScroller.ScrollPageDown();
}
}
private void DragOverBottomArea(DragUpdatedEvent dragUpdatedEvent)
{
if (DragAndDrop.objectReferences.Any())
{
if (editorsElement != null && editorsElement.ContainsPoint(editorsElement.WorldToLocal(dragUpdatedEvent.mousePosition)))
{
AutoScroll(dragUpdatedEvent.mousePosition);
return;
}
if (editorsElement != null)
{
var lastChild = editorsElement.Children().LastOrDefault();
if (lastChild == null)
return;
editorDragging.HandleDraggingInBottomArea(tracker.activeEditors, bottomAreaDropRectangle, lastChild.layout);
}
}
}
private void DragPerformInBottomArea(DragPerformEvent dragPerformedEvent)
{
if (editorsElement == null)
return;
if (editorsElement.ContainsPoint(editorsElement.WorldToLocal(dragPerformedEvent.mousePosition)))
return;
var lastChild = editorsElement.Children().LastOrDefault();
if (lastChild == null)
return;
editorDragging.HandleDragPerformInBottomArea(tracker.activeEditors, bottomAreaDropRectangle, lastChild.layout);
}
internal virtual Editor GetLastInteractedEditor()
{
return lastInteractedEditor;
}
protected IPreviewable GetEditorThatControlsPreview(IPreviewable[] editors)
{
if (editors.Length == 0)
return null;
if (m_SelectedPreview != null)
{
return m_SelectedPreview;
}
// Find last interacted editor, if not found check if we had an editor of similar type,
// if not found use first editor that can show a preview otherwise return null.
IPreviewable lastInteractedEditor = GetLastInteractedEditor();
Type lastType = lastInteractedEditor?.GetType();
IPreviewable firstEditorThatHasPreview = null;
IPreviewable similarEditorAsLast = null;
foreach (IPreviewable e in editors)
{
if (e == null || e.target == null)
continue;
// If target is an asset, but not the same asset as the asset
// of the first editor, then ignore it. This will prevent showing
// preview of materials attached to a GameObject but should cover
// future use cases as well.
if (EditorUtility.IsPersistent(e.target) &&
AssetDatabase.GetAssetPath(e.target) != AssetDatabase.GetAssetPath(editors[0].target))
continue;
// If main editor is an asset importer editor and this is an editor of the imported object, ignore.
if (editors[0] is AssetImporterEditor && !(e is AssetImporterEditor))
continue;
if (e.HasPreviewGUI())
{
if (e == lastInteractedEditor)
return e;
if (similarEditorAsLast == null && e.GetType() == lastType)
similarEditorAsLast = e;
if (firstEditorThatHasPreview == null)
firstEditorThatHasPreview = e;
}
}
if (similarEditorAsLast != null)
return similarEditorAsLast;
if (firstEditorThatHasPreview != null)
return firstEditorThatHasPreview;
// Found no valid editor
return null;
}
protected IPreviewable[] GetEditorsWithPreviews(Editor[] editors)
{
IList<IPreviewable> editorsWithPreview = new List<IPreviewable>();
int i = -1;
foreach (Editor e in editors)
{
++i;
if (e.target == null)
continue;
// If target is an asset, but not the same asset as the asset
// of the first editor, then ignore it. This will prevent showing
// preview of materials attached to a GameObject but should cover
// future use cases as well.
if (EditorUtility.IsPersistent(e.target) &&
AssetDatabase.GetAssetPath(e.target) != AssetDatabase.GetAssetPath(editors[0].target))
continue;
if (!EditorUtility.IsPersistent(editors[0].target) && EditorUtility.IsPersistent(e.target))
continue;
if (ShouldCullEditor(editors, i))
continue;
// If main editor is an asset importer editor and this is an editor of the imported object, ignore.
if (editors[0] is AssetImporterEditor && !(e is AssetImporterEditor))
continue;
if (e.HasPreviewGUI())
{
editorsWithPreview.Add(e);
}
}
if (m_Previews == null) return new IPreviewable[] {};
foreach (var previewable in m_Previews)
{
if (previewable.HasPreviewGUI())
editorsWithPreview.Add(previewable);
}
return editorsWithPreview.ToArray();
}
internal virtual Object GetInspectedObject()
{
return m_InspectedObject;
}
private void ResetKeyboardControl()
{
if (m_ResetKeyboardControl)
{
GUIUtility.keyboardControl = 0;
m_ResetKeyboardControl = false;
}
}
private static bool HasLabel(Object target)
{
return HasLabel(target, AssetDatabase.GetAssetPath(target));
}
private static bool HasLabel(Object target, string assetPath)
{
return EditorUtility.IsPersistent(target) && assetPath.StartsWith("assets", StringComparison.OrdinalIgnoreCase);
}
private Object[] GetInspectedAssets()
{
// We use this technique to support locking of the inspector. An inspector locks via an editor, so we need to use an editor to get the selection
Editor assetEditor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(tracker.activeEditors);
if (assetEditor != null && assetEditor.targets.Length == 1)
{
string assetPath = AssetDatabase.GetAssetPath(assetEditor.target);
if (HasLabel(assetEditor.target, assetPath) && !Directory.Exists(assetPath))
return assetEditor.targets;
}
// This is used if more than one asset is selected