-
Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathUnityEditorEx.cs
1066 lines (884 loc) · 41.4 KB
/
UnityEditorEx.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
///Ref
/// https://github.com/Unity-Technologies/UnityCsReference/tree/e740821767d2290238ea7954457333f06e952bad/Editor/Mono/SerializedProperty
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEditor.IMGUI.Controls;
using UnityEngine.Profiling;
namespace UnityEditorEx
{
internal class SerializedPropertyDataStore
{
internal class Data
{
UnityEngine.Object m_Object;
SerializedObject m_SerializedObject;
SerializedProperty[] m_Properties;
public Data(UnityEngine.Object obj, string[] props)
{
m_Object = obj;
m_SerializedObject = new SerializedObject(obj);
m_Properties = new SerializedProperty[props.Length];
for (int i = 0; i < props.Length; i++)
m_Properties[i] = m_SerializedObject.FindProperty(props[i]);
}
public void Dispose()
{
foreach (var prop in m_Properties)
{
if (prop != null)
prop.Dispose();
}
m_SerializedObject.Dispose();
m_Object = null;
m_SerializedObject = null;
m_Properties = null;
}
public string name { get { return m_Object != null ? m_Object.name : string.Empty; } }
public SerializedObject serializedObject { get { return m_SerializedObject; } }
public SerializedProperty[] properties { get { return m_Properties; } }
public int objectId
{
get
{
if (!m_Object)
return 0;
Component comp = m_Object as Component;
return comp != null ? comp.gameObject.GetInstanceID() : m_Object.GetInstanceID();
}
}
public bool activeInHierarchy
{
get
{
if (m_Object != null && m_Object is Component)
{
return ((Component)m_Object).gameObject.activeInHierarchy;
}
if (m_Object != null && m_Object is Material) // Materials can't be shown in the hierarchy
{
return true;
}
return false;
}
}
public bool Update() { return m_Object != null ? m_SerializedObject.UpdateIfRequiredOrScript() : false; }
public void Store() { if (m_Object != null) { m_SerializedObject.ApplyModifiedProperties(); } }
}
// LightTreeDataStore members
internal delegate UnityEngine.Object[] GatherDelegate();
UnityEngine.Object[] m_Objects; // only used to keep track of changes
bool[] m_ActiveObjects;
Data[] m_Elements;
string[] m_PropNames;
GatherDelegate m_GatherDel;
public Data[] GetElements() { return m_Elements; }
public SerializedPropertyDataStore(string[] propNames, GatherDelegate gatherDel)
{
m_PropNames = propNames;
m_GatherDel = gatherDel;
bool needsReload;
Repopulate(out needsReload);
}
~SerializedPropertyDataStore()
{
Clear();
}
public bool Repopulate(out bool needsReload)
{
// this is done due to optimization reasons. we want to know if any major changes has happened to the data
// without having to refetch it in another place and loop through it there
needsReload = false;
Profiler.BeginSample("SerializedPropertyDataStore.Repopulate.GatherDelegate");
UnityEngine.Object[] objs = m_GatherDel();
Profiler.EndSample();
if (m_Objects != null)
{
// If nothing's changed -> bail
if (objs.Length == m_Objects.Length && ArrayUtility.ArrayReferenceEquals(objs, m_Objects))
{
// The list of objects is the same, but since some should now potentially be hidden, we need to request a reload
if (!ActiveObjectsEquals(objs, m_ActiveObjects))
{
UpdateActiveObjects(objs);
needsReload = true;
}
return false;
}
Clear();
}
UpdateActiveObjects(objs);
// Recreate data store
m_Objects = objs;
m_Elements = new Data[objs.Length];
int elementIndex = 0;
for (int i = 0; i < objs.Length; i++)
{
// we don't want to list hidden objects
if (objs[i] == null || objs[i].hideFlags == HideFlags.HideAndDontSave || objs[i].hideFlags == HideFlags.HideInHierarchy)
continue;
m_Elements[elementIndex] = new Data(objs[i], m_PropNames);
elementIndex++;
}
if (elementIndex < objs.Length)
System.Array.Resize(ref m_Elements, elementIndex);
needsReload = true;
return true;
}
// Updates the cached active objects array (m_ActiveObjects) to reflect the current state of the passed objects
private void UpdateActiveObjects(Object[] objs)
{
m_ActiveObjects = new bool[objs.Length];
for (int i = 0; i < objs.Length; i++)
{
if (objs[i] == null || objs[i].hideFlags == HideFlags.HideAndDontSave || objs[i].hideFlags == HideFlags.HideInHierarchy)
continue;
if (objs[i] is Component)
{
m_ActiveObjects[i] = ((Component)objs[i]).gameObject.activeInHierarchy;
}
}
}
private void Clear()
{
// Clear current
for (int i = 0; i < m_Elements.Length; i++)
m_Elements[i].Dispose();
m_Objects = null;
m_Elements = null;
m_ActiveObjects = null;
}
private static bool ActiveObjectsEquals(Object[] objects, bool[] activeObjects)
{
if (activeObjects != null && objects.Length != activeObjects.Length)
return true;
for (int i = 0; i < objects.Length; i++)
{
if (objects[i] != null && objects[i] is Component)
{
if (((Component)objects[i]).gameObject.activeInHierarchy != activeObjects[i])
return false;
}
}
return true;
}
}
internal class SerializedPropertyTreeView : TreeView
{
internal static class Styles
{
public static readonly GUIStyle entryEven = "OL EntryBackEven";
public static readonly GUIStyle entryOdd = "OL EntryBackOdd";
public static readonly string focusHelper = "SerializedPropertyTreeViewFocusHelper";
public static readonly string serializeFilterSelection = "_FilterSelection";
public static readonly string serializeFilterDisable = "_FilterDisable";
public static readonly string serializeFilterInvert = "_FilterInvert";
public static readonly string serializeTreeViewState = "_TreeViewState";
public static readonly string serializeColumnHeaderState = "_ColumnHeaderState";
public static readonly string serializeFilter = "_Filter_";
public static readonly GUIContent filterSelection = EditorGUIUtility.TrTextContent("Isolate Selection", "Limits the table contents to the active selection.");
public static readonly GUIContent showInactiveObjects = EditorGUIUtility.TrTextContent("Show Inactive Objects", "Show objects that are not active in the hierarchy but contains the component.");
}
// this gets stuffed into the view and displayed on screen. It is a visible subset of the actual data
internal class SerializedPropertyItem : TreeViewItem
{
SerializedPropertyDataStore.Data m_Data;
public SerializedPropertyItem(int id, int depth, SerializedPropertyDataStore.Data ltd) : base(id, depth, ltd != null ? ltd.name : "root")
{
m_Data = ltd;
}
public SerializedPropertyDataStore.Data GetData() { return m_Data; }
}
internal class Column : MultiColumnHeaderState.Column
{
public delegate void DrawEntry(Rect r, SerializedProperty prop, SerializedProperty[] dependencies);
public delegate int CompareEntry(SerializedProperty lhs, SerializedProperty rhs);
public delegate void CopyDelegate(SerializedProperty target, SerializedProperty source);
public string propertyName;
public int[] dependencyIndices;
public DrawEntry drawDelegate;
public CompareEntry compareDelegate;
public CopyDelegate copyDelegate;
public SerializedPropertyFilters.IFilter filter;
public static void OverwriteSerializedFields(MultiColumnHeaderState source, MultiColumnHeaderState destination)
{
destination.visibleColumns = source.visibleColumns;
destination.sortedColumns = source.sortedColumns;
for (int i = 0; i < destination.columns.Length; ++i)
{
destination.columns[i].sortedAscending = source.columns[i].sortedAscending;
var sourceColumn = source.columns[i] as Column;
var destColumn = destination.columns[i] as Column;
if ((sourceColumn == null || destColumn == null) || string.Equals(sourceColumn.propertyName, destColumn.propertyName))
{
// Only makes sense if the property is the same property name
destination.columns[i].width = source.columns[i].width;
}
}
}
}
private struct ColumnInternal
{
public SerializedProperty[] dependencyProps; // helper array, must be the same size as dependencyIndices
}
internal class DefaultDelegates
{
public static readonly Column.DrawEntry DrawDefault = (Rect r, SerializedProperty prop, SerializedProperty[] dependencies) =>
{
Profiler.BeginSample("PropDrawDefault");
EditorGUI.PropertyField(r, prop, GUIContent.none);
Profiler.EndSample();
};
public static readonly Column.DrawEntry DrawCheckbox = (Rect r, SerializedProperty prop, SerializedProperty[] dependencies) =>
{
Profiler.BeginSample("PropDrawCheckbox");
float off = System.Math.Max(0.0f, ((r.width / 2) - 8));
r.x += off;
r.width -= off;
EditorGUI.PropertyField(r, prop, GUIContent.none);
Profiler.EndSample();
};
public static readonly Column.DrawEntry DrawName = (Rect r, SerializedProperty prop, SerializedProperty[] dependencies) => {};
public static readonly Column.CompareEntry CompareFloat = (SerializedProperty lhs, SerializedProperty rhs) =>
{
return lhs.floatValue.CompareTo(rhs.floatValue);
};
public static readonly Column.CompareEntry CompareCheckbox = (SerializedProperty lhs, SerializedProperty rhs) =>
{
return lhs.boolValue.CompareTo(rhs.boolValue);
};
public static readonly Column.CompareEntry CompareEnum = (SerializedProperty lhs, SerializedProperty rhs) =>
{
return lhs.enumValueIndex.CompareTo(rhs.enumValueIndex);
};
public static readonly Column.CompareEntry CompareInt = (SerializedProperty lhs, SerializedProperty rhs) =>
{
return lhs.intValue.CompareTo(rhs.intValue);
};
public static readonly Column.CompareEntry CompareColor = (SerializedProperty lhs, SerializedProperty rhs) =>
{
float lh, ls, lv, rh, rs, rv;
Color.RGBToHSV(lhs.colorValue, out lh, out ls, out lv);
Color.RGBToHSV(rhs.colorValue, out rh, out rs, out rv);
return lh.CompareTo(rh);
};
public static readonly Column.CompareEntry CompareName = (SerializedProperty lhs, SerializedProperty rhs) =>
{
return 0;
};
public static readonly Column.CopyDelegate CopyDefault = (SerializedProperty target, SerializedProperty source) =>
{
target.serializedObject.CopyFromSerializedProperty(source);
};
}
// reference to the data store (not owned by this class)
SerializedPropertyDataStore m_DataStore;
ColumnInternal[] m_ColumnsInternal;
List<TreeViewItem> m_Items;
int m_ChangedId;
bool m_bFilterSelection;
bool m_ShowInactiveObjects;
int[] m_SelectionFilter;
bool m_ShowFilterGUI;
public SerializedPropertyTreeView(TreeViewState state, MultiColumnHeader multicolumnHeader, SerializedPropertyDataStore dataStore, bool showFilterGUI) : base(state, multicolumnHeader)
{
m_DataStore = dataStore;
// initialize internal data for the columns
int colcnt = multiColumnHeader.state.columns.Length;
m_ColumnsInternal = new ColumnInternal[colcnt];
for (int i = 0; i < colcnt; i++)
{
Column c = Col(i);
if (c.propertyName != null)
m_ColumnsInternal[i].dependencyProps = new SerializedProperty[c.propertyName.Length];
}
multiColumnHeader.sortingChanged += OnSortingChanged;
multiColumnHeader.visibleColumnsChanged += OnVisibleColumnChanged;
showAlternatingRowBackgrounds = true;
showBorder = true;
rowHeight = EditorGUIUtility.singleLineHeight;
m_ShowFilterGUI = showFilterGUI;
}
public void SerializeState(string uid)
{
SessionState.SetBool(uid + Styles.serializeFilterSelection, m_bFilterSelection);
SessionState.SetBool(uid + Styles.showInactiveObjects, m_ShowInactiveObjects);
for (int i = 0; i < multiColumnHeader.state.columns.Length; i++)
{
var filter = Col(i).filter;
if (filter == null)
continue;
string filterState = filter.SerializeState();
if (string.IsNullOrEmpty(filterState))
continue;
SessionState.SetString(uid + Styles.serializeFilter + i, filterState);
}
SessionState.SetString(uid + Styles.serializeTreeViewState, JsonUtility.ToJson(state));
EditorPrefs.SetString(uid + Styles.serializeColumnHeaderState, JsonUtility.ToJson(multiColumnHeader.state));
}
public void DeserializeState(string uid)
{
m_bFilterSelection = SessionState.GetBool(uid + Styles.serializeFilterSelection, false);
m_ShowInactiveObjects = SessionState.GetBool(uid + Styles.showInactiveObjects, false);
MultiColumnHeaderState headerState = new MultiColumnHeaderState(multiColumnHeader.state.columns);
string columnHeaderState = EditorPrefs.GetString(uid + Styles.serializeColumnHeaderState, "");
if (!string.IsNullOrEmpty(columnHeaderState))
JsonUtility.FromJsonOverwrite(columnHeaderState, headerState);
if (MultiColumnHeaderState.CanOverwriteSerializedFields(headerState, multiColumnHeader.state))
Column.OverwriteSerializedFields(headerState, multiColumnHeader.state);
for (int i = 0; i < multiColumnHeader.state.columns.Length; i++)
{
var filter = Col(i).filter;
if (filter == null)
continue;
string filterState = SessionState.GetString(uid + Styles.serializeFilter + i, null);
if (string.IsNullOrEmpty(filterState))
continue;
filter.DeserializeState(filterState);
}
string treeViewState = SessionState.GetString(uid + Styles.serializeTreeViewState, "");
if (!string.IsNullOrEmpty(treeViewState))
JsonUtility.FromJsonOverwrite(treeViewState, state);
}
public bool IsFilteredDirty()
{
return m_ChangedId != 0 && (m_ChangedId != GUIUtility.keyboardControl || !EditorGUIUtility.editingTextField);
}
public void Update()
{
bool needsReload = false;
if (m_DataStore != null)
{
// If we re-populated all data, we need to clear the cached items
// The data can also be fine, but needs a reload without having to rebuild it all (inactive/active objects changed)
if (m_DataStore.Repopulate(out needsReload))
m_Items = null;
if (needsReload)
{
Reload();
return;
}
}
var rows = GetRows();
int first, last;
GetFirstAndLastVisibleRows(out first, out last);
bool changed = false;
if (last != -1)
{
for (int i = first; i <= last; i++)
{
changed = changed || ((SerializedPropertyItem)rows[i]).GetData().Update();
}
}
if (changed)
Repaint();
}
protected override TreeViewItem BuildRoot()
{
return new SerializedPropertyItem(-1, -1, null);
}
// this gets called whenever someone issues a reload() call to the parent
protected override IList<TreeViewItem> BuildRows(TreeViewItem root)
{
if (m_Items == null)
{
var rawData = m_DataStore.GetElements();
m_Items = new List<TreeViewItem>(rawData.Length);
for (int i = 0; i < rawData.Length; i++)
{
var item = new SerializedPropertyItem(rawData[i].objectId, 0, rawData[i]);
m_Items.Add(item);
}
}
// filtering
IEnumerable<TreeViewItem> tmprows = m_Items;
if (!m_ShowInactiveObjects && m_ShowFilterGUI)
tmprows = m_Items.Where((TreeViewItem item) => { return ((SerializedPropertyItem)item).GetData().activeInHierarchy; });
if (m_bFilterSelection && m_ShowFilterGUI)
{
if (m_SelectionFilter == null)
m_SelectionFilter = Selection.instanceIDs;
tmprows = m_Items.Where((TreeViewItem item) => { return m_SelectionFilter.Contains(item.id); });
}
else
m_SelectionFilter = null;
tmprows = Filter(tmprows);
var rows = tmprows.ToList();
if (multiColumnHeader.sortedColumnIndex >= 0)
Sort(rows, multiColumnHeader.sortedColumnIndex);
m_ChangedId = 0;
// We still need to setup the child parent information for the rows since this
// information is used by the TreeView internal logic (navigation, dragging etc)
TreeViewUtility.SetParentAndChildrenForItems(rows, root);
return rows;
}
protected override void RowGUI(RowGUIArgs args)
{
var item = (SerializedPropertyItem)args.item;
for (int i = 0; i < args.GetNumVisibleColumns(); ++i)
{
CellGUI(args.GetCellRect(i), item, args.GetColumn(i), ref args);
}
}
void CellGUI(Rect cellRect, SerializedPropertyItem item, int columnIndex, ref RowGUIArgs args)
{
Profiler.BeginSample("SerializedPropertyTreeView.CellGUI");
CenterRectUsingSingleLineHeight(ref cellRect);
var ltd = item.GetData();
Column column = (Column)this.multiColumnHeader.GetColumn(columnIndex);
if (column.drawDelegate == DefaultDelegates.DrawName)
{
// default drawing
Profiler.BeginSample("SerializedPropertyTreeView.OnItemGUI.LabelField");
using (new EditorGUI.DisabledScope(!ltd.activeInHierarchy))
{
DefaultGUI.Label(cellRect, ltd.name, IsSelected(args.item.id), false);
}
Profiler.EndSample();
}
else if (column.drawDelegate != null)
{
SerializedProperty[] props = ltd.properties;
int depcnt = column.dependencyIndices != null ? column.dependencyIndices.Length : 0;
for (int i = 0; i < depcnt; i++)
m_ColumnsInternal[columnIndex].dependencyProps[i] = props[column.dependencyIndices[i]];
// allow to capture tabs
if (args.item.id == state.lastClickedID && HasFocus() && columnIndex == multiColumnHeader.state.visibleColumns[multiColumnHeader.state.visibleColumns[0] == 0 ? 1 : 0])
GUI.SetNextControlName(Styles.focusHelper);
SerializedProperty prop = ltd.properties[columnIndex];
EditorGUI.BeginChangeCheck();
Profiler.BeginSample("SerializedPropertyTreeView.OnItemGUI.drawDelegate");
column.drawDelegate(cellRect, prop, m_ColumnsInternal[columnIndex].dependencyProps);
Profiler.EndSample();
if (EditorGUI.EndChangeCheck())
{
// if we changed a value in a filtered column we'll have to reload the table
m_ChangedId = ((column.filter != null) && column.filter.Active()) ? GUIUtility.keyboardControl : m_ChangedId;
// update all selected items if the current row was part of the selection list
ltd.Store();
var selIds = GetSelection();
if (selIds.Contains(ltd.objectId))
{
IList<TreeViewItem> rows = FindRows(selIds);
Undo.RecordObjects(rows.Select(r => ((SerializedPropertyItem)r).GetData().serializedObject.targetObject).ToArray(), "Modify Multiple Properties");
foreach (var r in rows)
{
if (r.id == args.item.id)
continue;
var data = ((SerializedPropertyItem)r).GetData();
if (!IsEditable(data.serializedObject.targetObject))
continue;
if (column.copyDelegate != null)
column.copyDelegate(data.properties[columnIndex], prop);
else
DefaultDelegates.CopyDefault(data.properties[columnIndex], prop);
data.Store();
}
}
}
}
Profiler.EndSample();
}
private static bool IsEditable(Object target)
{
return ((target.hideFlags & HideFlags.NotEditable) == 0);
}
protected override void BeforeRowsGUI()
{
var rows = GetRows();
int first, last;
GetFirstAndLastVisibleRows(out first, out last);
if (last != -1)
{
for (int i = first; i <= last; i++)
((SerializedPropertyItem)rows[i]).GetData().Update();
}
// don't forget to refresh selected objects that got shoved off screen
var selected = FindRows(GetSelection());
foreach (SerializedPropertyItem sel in selected)
sel.GetData().Update();
base.BeforeRowsGUI();
}
public void OnFilterGUI(Rect r)
{
EditorGUI.BeginChangeCheck();
float fullWidth = r.width;
float windowPadding = r.x;
float toggleWidth = 16;
if (m_ShowFilterGUI)
{
r.width = toggleWidth;
m_bFilterSelection = EditorGUI.Toggle(r, m_bFilterSelection);
r.x += toggleWidth;
r.width = GUI.skin.label.CalcSize(SerializedPropertyTreeView.Styles.filterSelection).x;
EditorGUI.LabelField(r, SerializedPropertyTreeView.Styles.filterSelection);
r.x += r.width + 10;
r.width = toggleWidth;
m_ShowInactiveObjects = EditorGUI.Toggle(r, m_ShowInactiveObjects);
r.x += toggleWidth;
r.width = GUI.skin.label.CalcSize(SerializedPropertyTreeView.Styles.showInactiveObjects).x;
EditorGUI.LabelField(r, SerializedPropertyTreeView.Styles.showInactiveObjects);
r.width = Mathf.Min(fullWidth - (r.x + r.width), 300);
r.x = fullWidth - r.width + windowPadding;
}
else
{
r.width = 300;
r.x = fullWidth - r.width + windowPadding;
}
for (int i = 0; i < multiColumnHeader.state.columns.Length; i++)
{
if (!IsColumnVisible(i))
continue;
Column c = Col(i);
if (c.filter != null && c.filter.GetType().Equals(typeof(SerializedPropertyFilters.Name)))
{
c.filter.OnGUI(r);
}
}
if (EditorGUI.EndChangeCheck())
Reload();
}
protected override void SelectionChanged(IList<int> selectedIds)
{
Selection.instanceIDs = selectedIds.ToArray();
}
protected override void KeyEvent()
{
if (Event.current.type != EventType.KeyDown)
return;
// We always focus as this callback only fires when the name column is selected.
// Tabbing through the property columns never goes through here.
// Also note that we're not capturing the KeyCode Tab. There are 2 tab events,
// one for the keycode, and one for the character code. The keycode comes first,
// so if we change the focus based on the keycode, we never get the second character code
// event as the treeview loses focus and doesn't fire the callback. The second tab event
// then gets handled as an ordinary tab, leading to a double tab.
if (Event.current.character == '\t')
{
GUI.FocusControl(Styles.focusHelper);
Event.current.Use();
}
}
void OnVisibleColumnChanged(MultiColumnHeader header)
{
Reload();
}
void OnSortingChanged(MultiColumnHeader multiColumnHeader)
{
var rows = GetRows();
Sort(rows, multiColumnHeader.sortedColumnIndex);
}
void Sort(IList<TreeViewItem> rows, int sortIdx)
{
Debug.Assert(sortIdx >= 0);
bool ascend = multiColumnHeader.IsSortedAscending(sortIdx);
var comp = Col(sortIdx).compareDelegate;
var myRows = rows as List<TreeViewItem>;
System.Comparison<TreeViewItem> sortAscend, sortDescend;
if (comp == null)
{
return;
}
else if (comp == DefaultDelegates.CompareName) // special case for sorting by the object name
{
sortAscend = (TreeViewItem lhs, TreeViewItem rhs) =>
{
return EditorUtility.NaturalCompare(((SerializedPropertyItem)lhs).GetData().name, ((SerializedPropertyItem)rhs).GetData().name);
};
sortDescend = (TreeViewItem lhs, TreeViewItem rhs) =>
{
return -EditorUtility.NaturalCompare(((SerializedPropertyItem)lhs).GetData().name, ((SerializedPropertyItem)rhs).GetData().name);
};
}
else
{
sortAscend = (TreeViewItem lhs, TreeViewItem rhs) =>
{
return comp(((SerializedPropertyItem)lhs).GetData().properties[sortIdx], ((SerializedPropertyItem)rhs).GetData().properties[sortIdx]);
};
sortDescend = (TreeViewItem lhs, TreeViewItem rhs) =>
{
return -comp(((SerializedPropertyItem)lhs).GetData().properties[sortIdx], ((SerializedPropertyItem)rhs).GetData().properties[sortIdx]);
};
}
myRows.Sort(ascend ? sortAscend : sortDescend);
}
IEnumerable<TreeViewItem> Filter(IEnumerable<TreeViewItem> rows)
{
var tmp = rows;
int cnt = m_ColumnsInternal.Length;
for (int i = 0; i < cnt; i++)
{
if (!IsColumnVisible(i))
continue;
Column c = Col(i);
int idx = i;
if (c.filter != null)
{
if (!c.filter.Active())
continue;
if (c.filter.GetType().Equals(typeof(SerializedPropertyFilters.Name)))
{
var f = (SerializedPropertyFilters.Name)c.filter;
tmp = tmp.Where((TreeViewItem item) => { return f.Filter(((SerializedPropertyItem)item).GetData().name); });
}
else
{
tmp = tmp.Where((TreeViewItem item) => { return c.filter.Filter(((SerializedPropertyItem)item).GetData().properties[idx]); });
}
}
}
return tmp;
}
private bool IsColumnVisible(int idx)
{
for (int i = 0; i < multiColumnHeader.state.visibleColumns.Length; i++)
if (multiColumnHeader.state.visibleColumns[i] == idx)
return true;
return false;
}
// casting helper
private Column Col(int idx) { return (Column)multiColumnHeader.state.columns[idx]; }
}
internal class SerializedPropertyTable
{
internal delegate SerializedPropertyTreeView.Column[] HeaderDelegate();
SerializedPropertyDataStore.GatherDelegate m_GatherDelegate;
HeaderDelegate m_HeaderDelegate;
bool m_Initialized;
TreeViewState m_TreeViewState;
MultiColumnHeaderState m_MultiColumnHeaderState;
SerializedPropertyTreeView m_TreeView;
SerializedPropertyDataStore m_DataStore;
float m_ColumnHeaderHeight;
string m_SerializationUID;
readonly float m_FilterHeight = 20;
bool m_ShowFilterGUI;
public SerializedPropertyTable(string serializationUID, SerializedPropertyDataStore.GatherDelegate gatherDelegate, HeaderDelegate headerDelegate, bool showFilterGUI)
{
m_SerializationUID = serializationUID;
m_GatherDelegate = gatherDelegate;
m_HeaderDelegate = headerDelegate;
m_ShowFilterGUI = showFilterGUI;
}
void InitIfNeeded()
{
if (m_Initialized)
return;
if (m_TreeViewState == null)
m_TreeViewState = new TreeViewState();
if (m_MultiColumnHeaderState == null)
{
SerializedPropertyTreeView.Column[] columns = m_HeaderDelegate();
string[] propNames = GetPropertyNames(columns);
m_MultiColumnHeaderState = new MultiColumnHeaderState(columns);
m_DataStore = new SerializedPropertyDataStore(propNames, m_GatherDelegate);
}
var header = new MultiColumnHeader(m_MultiColumnHeaderState);
m_ColumnHeaderHeight = header.height;
m_TreeView = new SerializedPropertyTreeView(m_TreeViewState, header, m_DataStore, m_ShowFilterGUI);
m_TreeView.DeserializeState(m_SerializationUID);
m_TreeView.Reload();
m_Initialized = true;
}
string[] GetPropertyNames(SerializedPropertyTreeView.Column[] columns)
{
string[] propNames = new string[columns.Length];
for (int i = 0; i < columns.Length; i++)
propNames[i] = columns[i].propertyName;
return propNames;
}
public void OnInspectorUpdate()
{
if (m_TreeView != null)
{
m_TreeView.Update();
}
}
public void OnHierarchyChange()
{
if (m_TreeView != null)
{
m_TreeView.Update();
}
}
public void OnSelectionChange()
{
OnSelectionChange(Selection.instanceIDs);
}
public void OnSelectionChange(int[] instanceIDs)
{
if (m_TreeView != null)
{
m_TreeView.SetSelection(instanceIDs);
}
}
public void OnGUI()
{
Profiler.BeginSample("SerializedPropertyTable.OnGUI");
InitIfNeeded();
Rect r = GUILayoutUtility.GetRect(0, float.MaxValue, 0, float.MaxValue);
if (Event.current.type == EventType.Layout)
{
Profiler.EndSample();
return;
}
float tableHeight = r.height - m_FilterHeight;
// filter rect
r.height = m_FilterHeight;
Rect filterRect = r;
// table rect
r.height = tableHeight;
r.y += m_FilterHeight;
Rect tableRect = r;
// table
Profiler.BeginSample("TreeView.OnGUI");
m_TreeView.OnGUI(tableRect);
Profiler.EndSample();
m_TreeView.OnFilterGUI(filterRect);
if (m_TreeView.IsFilteredDirty())
m_TreeView.Reload();
Profiler.EndSample();
}
public void OnDisable()
{
if (m_TreeView != null)
m_TreeView.SerializeState(m_SerializationUID);
}
}
internal class SerializedPropertyFilters
{
internal interface IFilter
{
bool Active(); // returns true if filter is active, false otherwise
bool Filter(SerializedProperty prop); // returns true if filtering passes
void OnGUI(Rect r); // draws the filter control
string SerializeState(); // returns null if there's nothing to serialize
void DeserializeState(string state); // state must not be null
}
internal abstract class SerializableFilter : IFilter
{
public abstract bool Active(); // returns true if filter is active, false otherwise
public abstract bool Filter(SerializedProperty prop); // returns true if filtering passes
public abstract void OnGUI(Rect r); // draws the filter control
public string SerializeState() { return JsonUtility.ToJson(this); }
public void DeserializeState(string state) { JsonUtility.FromJsonOverwrite(state, this); }
}
internal class String : SerializableFilter
{
static class Styles
{
public static readonly GUIStyle searchField = "SearchTextField";
public static readonly GUIStyle searchFieldCancelButton = "SearchCancelButton";
public static readonly GUIStyle searchFieldCancelButtonEmpty = "SearchCancelButtonEmpty";
}
[SerializeField] protected string m_Text = "";
public override bool Active() { return !string.IsNullOrEmpty(m_Text); }
public override bool Filter(SerializedProperty prop) { return prop.stringValue.IndexOf(m_Text, 0, System.StringComparison.OrdinalIgnoreCase) >= 0; }
public override void OnGUI(Rect r)
{
bool empty = string.IsNullOrEmpty(m_Text);
Rect buttonRect = r;
buttonRect.x += (r.width - 15);
buttonRect.width = 15;
GUIStyle buttonStyle = empty ? Styles.searchFieldCancelButtonEmpty : Styles.searchFieldCancelButton;
if (GUI.Button(buttonRect, GUIContent.none, buttonStyle) && !empty)
{
m_Text = "";
GUIUtility.keyboardControl = 0;
}
m_Text = EditorGUI.TextField(r, GUIContent.none, m_Text, Styles.searchField);
GUI.Button(buttonRect, GUIContent.none, buttonStyle);
}
}
internal sealed class Name : String
{
public bool Filter(string str) { return str.IndexOf(m_Text, 0, System.StringComparison.OrdinalIgnoreCase) >= 0; }
}
internal sealed class None : IFilter
{
public bool Active() { return false; }
public bool Filter(SerializedProperty prop) { return true; }
public void OnGUI(Rect r) {}
public string SerializeState() { return null; }
public void DeserializeState(string state) {}
}
internal static readonly None s_FilterNone = new None();
}
public class TreeViewUtility
{
public static void SetParentAndChildrenForItems(IList<TreeViewItem> rows, TreeViewItem root) => TreeViewUtility.SetChildParentReferences(rows, root);
internal static void SetChildParentReferences(
IList<TreeViewItem> visibleItems,
TreeViewItem root)
{
for (int index = 0; index < visibleItems.Count; ++index)
visibleItems[index].parent = (TreeViewItem) null;
int capacity = 0;