forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeViewController.cs
More file actions
1331 lines (1129 loc) · 51.1 KB
/
Copy pathTreeViewController.cs
File metadata and controls
1331 lines (1129 loc) · 51.1 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
// 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.Linq;
using UnityEditor.AnimatedValues;
using UnityEngine;
using UnityEditorInternal;
namespace UnityEditor.IMGUI.Controls
{
/*
Description:
The TreeViewController requires implementations from the following three interfaces:
ITreeViewDataSource: Should handle data fetching and data structure
ITreeViewGUI: Should handle visual representation of TreeView and mouse input on row controls
ITreeViewDragging: Should handle dragging, temp expansion of items, allow/disallow dropping
The TreeViewController handles: Navigation, Item selection and initiates dragging
Important concepts:
1) The Item Tree: the DataSource should create the tree structure of items with parent and children references
2) Rows: the DataSource should be able to provide the visible items; a simple list that will become the rows we render.
3) The root item might not be visible; its up to the data source to deliver a set of visible items from the tree
*/
[System.Serializable]
public class TreeViewState
{
public List<int> selectedIDs { get { return m_SelectedIDs; } set { m_SelectedIDs = value; } }
public int lastClickedID { get { return m_LastClickedID; } set { m_LastClickedID = value; } }
public List<int> expandedIDs { get { return m_ExpandedIDs; } set { m_ExpandedIDs = value; } }
internal RenameOverlay renameOverlay { get { return m_RenameOverlay; } set { m_RenameOverlay = value; } }
public string searchString { get { return m_SearchString; } set { m_SearchString = value; } }
public Vector2 scrollPos;
// Selection state
[SerializeField] private List<int> m_SelectedIDs = new List<int>();
[SerializeField] private int m_LastClickedID; // used for navigation
// Expanded state (assumed sorted)
[SerializeField] private List<int> m_ExpandedIDs = new List<int>();
// Rename and create asset state
[SerializeField] private RenameOverlay m_RenameOverlay = new RenameOverlay();
// Search state (can be used by Datasource to filter tree when reloading)
[SerializeField] private string m_SearchString;
internal virtual void OnAwake()
{
// Clear state that should not survive closing/starting Unity (If TreeViewState is in EditorWindow that are serialized in a layout file)
m_RenameOverlay.Clear();
}
}
internal struct TreeViewSelectState
{
public List<int> selectedIDs;
public int lastClickedID;
public bool keepMultiSelection;
public bool useShiftAsActionKey;
}
internal class TreeViewController
{
public System.Action<int[]> selectionChangedCallback { get; set; } // ids
public System.Action<int> itemSingleClickedCallback { get; set; } // id
public System.Action<int> itemDoubleClickedCallback { get; set; } // id
public System.Action<int[], bool> dragEndedCallback { get; set; } // dragged ids, if null then drag was not allowed, bool == true if dragging tree view items from own treeview, false if drag was started outside
public System.Action<int> contextClickItemCallback { get; set; } // clicked item id
public System.Action contextClickOutsideItemsCallback { get; set; }
public System.Action keyboardInputCallback { get; set; }
public System.Action expandedStateChanged { get; set; }
public System.Action<string> searchChanged { get; set; }
public System.Action<Vector2> scrollChanged { get; set; }
public System.Action<int, Rect> onGUIRowCallback { get; set; } // <id, Rect of row>
internal System.Action<int, Rect> onFoldoutButton { get; set; } // <id, Rect of row>
// Main state
GUIView m_GUIView; // Containing view for this tree: used for checking if we have focus and for requesting repaints
public ITreeViewDataSource data { get; set; } // Data provider for this tree: handles data fetching
public ITreeViewDragging dragging { get; set; } // Handle dragging
public ITreeViewGUI gui { get; set; } // Handles GUI (input and rendering)
public TreeViewState state { get; set; } // State that persists script reloads
public GUIStyle horizontalScrollbarStyle { get; set; }
public GUIStyle verticalScrollbarStyle { get; set; }
public GUIStyle scrollViewStyle { get; set; }
public TreeViewItemExpansionAnimator expansionAnimator { get { return m_ExpansionAnimator; } }
readonly TreeViewItemExpansionAnimator m_ExpansionAnimator = new TreeViewItemExpansionAnimator();
AnimFloat m_FramingAnimFloat;
bool m_StopIteratingItems;
public bool deselectOnUnhandledMouseDown { get; set; }
public bool enableItemHovering { get; set; }
List<int> m_DragSelection = new List<int>(); // Temp id state while dragging (not serialized)
bool m_UseScrollView = true; // Internal scrollview can be omitted when e.g mulitple tree views in one scrollview is wanted
bool m_ConsumeKeyDownEvents = true;
bool m_AllowRenameOnMouseUp = true;
internal const string kExpansionAnimationPrefKey = "TreeViewExpansionAnimation";
bool m_UseExpansionAnimation = EditorPrefs.GetBool(kExpansionAnimationPrefKey, true);
public bool useExpansionAnimation { get { return m_UseExpansionAnimation; } set { m_UseExpansionAnimation = value; } }
// Cached values during one event (for convenience)
bool m_GrabKeyboardFocus;
Rect m_TotalRect;
Rect m_VisibleRect;
Rect m_ContentRect;
bool m_HadFocusLastEvent; // Cached from last event for keyboard focus changed event
int m_KeyboardControlID;
const double kSlowSelectTimeout = 0.2;
const float kSpaceForScrollBar = 16f;
public TreeViewItem hoveredItem { get; set; }
public TreeViewController(EditorWindow editorWindow, TreeViewState treeViewState)
{
m_GUIView = editorWindow ? editorWindow.m_Parent : GUIView.current;
state = treeViewState;
}
public void Init(Rect rect, ITreeViewDataSource data, ITreeViewGUI gui, ITreeViewDragging dragging)
{
this.data = data;
this.gui = gui;
this.dragging = dragging;
m_VisibleRect = m_TotalRect = rect; // We initialize the total rect because it might be needed for framing selection when reloading data the first time.
// Allow sub systems to set up delegates etc after treeview references have been set up
data.OnInitialize();
gui.OnInitialize();
if (dragging != null)
dragging.OnInitialize();
expandedStateChanged += ExpandedStateHasChanged;
m_FramingAnimFloat = new AnimFloat(state.scrollPos.y, AnimatedScrollChanged);
}
void ExpandedStateHasChanged()
{
m_StopIteratingItems = true;
}
public bool isSearching
{
get { return !string.IsNullOrEmpty(state.searchString); }
}
public bool isDragging
{
get { return m_DragSelection != null && m_DragSelection.Count > 0; }
}
public bool showingVerticalScrollBar
{
get { return m_VisibleRect.height > 0 && m_ContentRect.height > m_VisibleRect.height; }
}
public bool showingHorizontalScrollBar
{
get { return m_VisibleRect.width > 0 && m_ContentRect.width > m_VisibleRect.width; }
}
public string searchString
{
get
{
return state.searchString;
}
set
{
if (string.ReferenceEquals(state.searchString, value))
return;
if (state.searchString == value)
return;
state.searchString = value;
data.OnSearchChanged();
if (searchChanged != null)
searchChanged(state.searchString);
}
}
public bool useScrollView
{
get { return m_UseScrollView; }
set { m_UseScrollView = value; }
}
public Rect visibleRect
{
get { return m_VisibleRect; }
}
public bool IsSelected(int id)
{
return state.selectedIDs.Contains(id);
}
public bool HasSelection()
{
return state.selectedIDs.Count > 0;
}
public int[] GetSelection()
{
return state.selectedIDs.ToArray();
}
public int[] GetRowIDs()
{
return (from item in data.GetRows() select item.id).ToArray();
}
public void SetSelection(int[] selectedIDs, bool revealSelectionAndFrameLastSelected)
{
const bool animatedFraming = false;
SetSelection(selectedIDs, revealSelectionAndFrameLastSelected, animatedFraming);
}
public void SetSelection(int[] selectedIDs, bool revealSelectionAndFrameLastSelected, bool animatedFraming)
{
// Keep for debugging
//Debug.Log ("SetSelection: new selection: " + DebugUtils.ListToString(new List<int>(selectedIDs)));
// Init new state
if (selectedIDs.Length > 0)
{
if (revealSelectionAndFrameLastSelected)
{
data.RevealItems(selectedIDs);
}
state.selectedIDs = new List<int>(selectedIDs);
// Ensure that our key navigation is setup
bool hasLastClicked = state.selectedIDs.IndexOf(state.lastClickedID) >= 0;
if (!hasLastClicked)
{
// See if we can find a valid id, we check the last selected (selectedids might contain invalid ids e.g scene objects in project browser and vice versa)
int lastSelectedID = selectedIDs.Last();
if (data.GetRow(lastSelectedID) != -1)
{
state.lastClickedID = lastSelectedID;
hasLastClicked = true;
}
else
state.lastClickedID = 0;
}
if (revealSelectionAndFrameLastSelected && hasLastClicked)
Frame(state.lastClickedID, true, false, animatedFraming);
}
else
{
state.selectedIDs.Clear();
state.lastClickedID = 0;
}
// Should not fire callback since this is called from outside
// NotifyListenersThatSelectionChanged ()
}
public TreeViewItem FindItem(int id)
{
return data.FindItem(id);
}
[System.Obsolete("SetUseScrollView has been deprecated. Use property useScrollView instead.")]
public void SetUseScrollView(bool useScrollView)
{
m_UseScrollView = useScrollView;
}
public void SetConsumeKeyDownEvents(bool consume)
{
m_ConsumeKeyDownEvents = consume;
}
public void Repaint()
{
if (m_GUIView != null)
m_GUIView.Repaint();
}
public void ReloadData()
{
// Do not clear rename data here, we could be reloading due to assembly reload
// and we want to let our rename session survive that
data.ReloadData();
Repaint();
m_StopIteratingItems = true;
}
public bool HasFocus()
{
bool hasKeyFocus = (m_GUIView != null) ? m_GUIView.hasFocus : EditorGUIUtility.HasCurrentWindowKeyFocus();
return hasKeyFocus && (GUIUtility.keyboardControl == m_KeyboardControlID);
}
static internal int GetItemControlID(TreeViewItem item)
{
return ((item != null) ? item.id : 0) + 10000000;
}
public void HandleUnusedMouseEventsForItem(Rect rect, TreeViewItem item, int row)
{
int itemControlID = GetItemControlID(item);
Event evt = Event.current;
switch (evt.GetTypeForControl(itemControlID))
{
case EventType.MouseDown:
if (rect.Contains(Event.current.mousePosition))
{
// Handle mouse down on entire line
if (Event.current.button == 0)
{
// Grab keyboard
GUIUtility.keyboardControl = m_KeyboardControlID;
Repaint(); // Ensure repaint so we can show we have keyboard focus
// Let client handle double click
if (Event.current.clickCount == 2)
{
if (itemDoubleClickedCallback != null)
itemDoubleClickedCallback(item.id);
}
else
{
double selectStartTime = Time.realtimeSinceStartup;
var dragSelection = GetNewSelection(item, true, false);
bool dragAbortedBySlowSelect = (Time.realtimeSinceStartup - selectStartTime) > kSlowSelectTimeout;
bool canStartDrag = !dragAbortedBySlowSelect && dragging != null && dragSelection.Count != 0 && dragging.CanStartDrag(item, dragSelection, Event.current.mousePosition);
if (canStartDrag)
{
// Prepare drag and drop delay (we start the drag after a couple of pixels mouse drag: See the case MouseDrag below)
m_DragSelection = dragSelection;
DragAndDropDelay delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), GetItemControlID(item));
delay.mouseDownPosition = Event.current.mousePosition;
}
else
{
// If dragging is not supported or not allowed for the drag selection then handle selection on mouse down
// (when dragging is handled we handle selection on mouse up to e.g allow to drag to object fields in the inspector)
m_DragSelection.Clear();
if (m_AllowRenameOnMouseUp)
m_AllowRenameOnMouseUp = (state.selectedIDs.Count == 1 && state.selectedIDs[0] == item.id); // If first time selection then prevent starting a rename on the following mouse up after this mouse down
SelectionClick(item, false);
// Notify about single click
if (itemSingleClickedCallback != null)
itemSingleClickedCallback(item.id);
}
GUIUtility.hotControl = GetItemControlID(item);
}
evt.Use();
}
else if (Event.current.button == 1)
{
// Right mouse down selects;
bool keepMultiSelection = true;
SelectionClick(item, keepMultiSelection);
}
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == itemControlID && dragging != null && m_DragSelection.Count > 0)
{
DragAndDropDelay delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), itemControlID);
if (delay.CanStartDrag() && dragging.CanStartDrag(item, m_DragSelection, delay.mouseDownPosition))
{
dragging.StartDrag(item, m_DragSelection);
GUIUtility.hotControl = 0;
}
evt.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == itemControlID)
{
// When having the temp dragging selection delay the the selection until mouse up
bool useMouseUpSelection = m_DragSelection.Count > 0;
// Clear state before SelectionClick since it can ExitGUI early
GUIUtility.hotControl = 0;
m_DragSelection.Clear();
evt.Use();
// On Mouse up either start name editing or change selection (if not done on mouse down)
if (rect.Contains(evt.mousePosition))
{
Rect renameActivationRect = gui.GetRenameRect(rect, row, item);
List<int> selected = state.selectedIDs;
if (m_AllowRenameOnMouseUp && selected != null && selected.Count == 1 && selected[0] == item.id && renameActivationRect.Contains(evt.mousePosition) && !EditorGUIUtility.HasHolddownKeyModifiers(evt))
{
BeginNameEditing(0.5f);
}
else if (useMouseUpSelection)
{
SelectionClick(item, false);
// Notify about single click
if (itemSingleClickedCallback != null)
itemSingleClickedCallback(item.id);
}
}
}
break;
case EventType.DragUpdated:
case EventType.DragPerform:
{
//bool firstItem = row == 0;
if (dragging != null && dragging.DragElement(item, rect, row))
GUIUtility.hotControl = 0;
}
break;
case EventType.ContextClick:
if (rect.Contains(evt.mousePosition))
{
// Do not use the event so the client can react to the context click (here we just handled the treeview selection)
if (contextClickItemCallback != null)
contextClickItemCallback(item.id);
}
break;
}
}
public void GrabKeyboardFocus()
{
m_GrabKeyboardFocus = true;
}
public void NotifyListenersThatSelectionChanged()
{
if (selectionChangedCallback != null)
selectionChangedCallback(state.selectedIDs.ToArray());
}
public void NotifyListenersThatDragEnded(int[] draggedIDs, bool draggedItemsFromOwnTreeView)
{
if (dragEndedCallback != null)
dragEndedCallback(draggedIDs, draggedItemsFromOwnTreeView);
}
public Vector2 GetContentSize()
{
return gui.GetTotalSize();
}
public Rect GetTotalRect()
{
return m_TotalRect;
}
public void SetTotalRect(Rect rect)
{
m_TotalRect = rect;
}
public bool IsItemDragSelectedOrSelected(TreeViewItem item)
{
return m_DragSelection.Count > 0 ? m_DragSelection.Contains(item.id) : state.selectedIDs.Contains(item.id);
}
public bool animatingExpansion { get { return m_UseExpansionAnimation && m_ExpansionAnimator.isAnimating; } }
void DoItemGUI(TreeViewItem item, int row, float rowWidth, bool hasFocus)
{
// Check valid row
if (row < 0 || row >= data.rowCount)
{
Debug.LogError("Invalid. Org row: " + (row) + " Num rows " + data.rowCount);
return;
}
bool selected = IsItemDragSelectedOrSelected(item);
Rect rowRect = gui.GetRowRect(row, rowWidth);
// 1. Before row GUI
if (animatingExpansion)
rowRect = m_ExpansionAnimator.OnBeginRowGUI(row, rowRect);
// 2. Do row GUI
if (animatingExpansion)
m_ExpansionAnimator.OnRowGUI(row);
gui.OnRowGUI(rowRect, item, row, selected, hasFocus);
// 3. Draw extra gui callbacks
if (onGUIRowCallback != null)
{
float indent = gui.GetContentIndent(item);
Rect indentedRect = new Rect(rowRect.x + indent, rowRect.y, rowRect.width - indent, rowRect.height);
onGUIRowCallback(item.id, indentedRect);
}
// 4. After row GUI
if (animatingExpansion)
m_ExpansionAnimator.OnEndRowGUI(row);
HandleUnusedMouseEventsForItem(rowRect, item, row);
}
public void OnGUI(Rect rect, int keyboardControlID)
{
m_KeyboardControlID = keyboardControlID;
Event evt = Event.current;
if (evt.type == EventType.Repaint)
m_TotalRect = rect;
m_GUIView = GUIView.current;
// End rename if the window do not have focus
if (m_GUIView != null && !m_GUIView.hasFocus && state.renameOverlay.IsRenaming())
{
EndNameEditing(true);
}
// Grab keyboard focus if requested
if (m_GrabKeyboardFocus)
{
m_GrabKeyboardFocus = false;
GUIUtility.keyboardControl = m_KeyboardControlID;
Repaint(); // Ensure repaint so we can show we have keyboard focus
}
bool isMouseDownInTotalRect = evt.type == EventType.MouseDown && m_TotalRect.Contains(evt.mousePosition);
if (isMouseDownInTotalRect)
{
m_AllowRenameOnMouseUp = true; // reset value (can be changed later in this event if the TreeView gets focus)
}
// Might change expanded state so call before InitIfNeeded (delayed collapse until animation is done)
if (animatingExpansion)
m_ExpansionAnimator.OnBeforeAllRowsGUI();
data.InitIfNeeded();
// Calc content size
Vector2 contentSize = gui.GetTotalSize();
m_ContentRect = new Rect(0, 0, contentSize.x, contentSize.y);
if (m_UseScrollView)
{
state.scrollPos = GUI.BeginScrollView(m_TotalRect, state.scrollPos, m_ContentRect, false, false,
horizontalScrollbarStyle != null ? horizontalScrollbarStyle : GUI.skin.horizontalScrollbar,
verticalScrollbarStyle != null ? verticalScrollbarStyle : GUI.skin.verticalScrollbar, scrollViewStyle != null ? scrollViewStyle : EditorStyles.scrollViewAlt);
}
else
GUI.BeginClip(m_TotalRect);
if (evt.type == EventType.Repaint)
{
if (m_UseScrollView)
{
m_VisibleRect = GUI.GetTopScrollView().visibleRect;
}
else
{
// We may be inside of a scroll view.
var scrollView = GUI.GetTopScrollView();
if (scrollView != null)
{
// Calculate the visible area of the TreeView inside of the ScrollView taking into account
// that the TreeView may not be contained within the whole ScrollView area.
state.scrollPos = Vector2.Max(Vector2.zero, scrollView.scrollPosition - m_TotalRect.min - scrollView.position.min);
m_VisibleRect = scrollView.visibleRect;
m_VisibleRect.size = Vector2.Max(Vector2.zero, Vector2.Min(m_VisibleRect.size, (m_TotalRect.size - state.scrollPos)));
}
else
{
m_VisibleRect = m_TotalRect;
}
}
}
gui.BeginRowGUI();
// Iterate visible items
int firstRow, lastRow;
gui.GetFirstAndLastRowVisible(out firstRow, out lastRow);
if (lastRow >= 0)
{
int numVisibleRows = lastRow - firstRow + 1;
float rowWidth = Mathf.Max(GUIClip.visibleRect.width, m_ContentRect.width);
IterateVisibleItems(firstRow, numVisibleRows, rowWidth, HasFocus());
}
// Call before gui.EndRowGUI() so stuff we render in EndRowGUI does not end up
// in the the animation clip rect
if (animatingExpansion)
m_ExpansionAnimator.OnAfterAllRowsGUI();
gui.EndRowGUI();
// Keep inside clip region so callbacks that might want to get
// rects of rows have correct context.
KeyboardGUI();
if (m_UseScrollView)
GUI.EndScrollView(showingVerticalScrollBar);
else
GUI.EndClip();
HandleUnusedEvents();
// Call after iterating rows since selecting a row takes keyboard focus
HandleTreeViewGotFocus(isMouseDownInTotalRect);
// Prevent controlID inconsistency for the controls following this tree view: We use the hint parameter of GetControlID to
// fast forward to a fixed entry in the id list so the following controls always start from there regardless of the rows that have been
// culled.
GUIUtility.GetControlID(33243602, FocusType.Passive);
if (Event.current.type == EventType.MouseLeaveWindow)
hoveredItem = null;
}
void HandleTreeViewGotFocus(bool isMouseDownInTotalRect)
{
if (Event.current.type == EventType.Layout)
return;
// Detect if TreeView got keyboard focus (ignore layout event which gets fired infront of mousedown)
bool hasFocus = HasFocus();
if (hasFocus != m_HadFocusLastEvent)
{
m_HadFocusLastEvent = hasFocus;
if (hasFocus && isMouseDownInTotalRect)
{
// If we got focus this event by mouse down then we do not want to begin renaming
// if clicking on an already selected item in the up coming MouseUp event.
m_AllowRenameOnMouseUp = false;
}
}
}
void IterateVisibleItems(int firstRow, int numVisibleRows, float rowWidth, bool hasFocus)
{
// We stop iterating items if datasource state changes while iterating its items.
// This can happen e.g when dragging items or items are expanding/collapsing.
m_StopIteratingItems = false;
TreeViewItem currentHoveredItem = null;
int rowOffset = 0;
for (int i = 0; i < numVisibleRows; ++i)
{
int row = firstRow + i;
if (animatingExpansion)
{
// If we are animating expansion/collapsing then ensure items
// that are culled by the animation clip rect gets 'converted' into
// items after the expanding/collapsing items. When no more items can get culled
// then keep adding the offset (to not handle already handled items).
int endAnimRow = m_ExpansionAnimator.endRow;
if (m_ExpansionAnimator.CullRow(row, gui))
{
rowOffset++;
row = endAnimRow + rowOffset;
}
else
{
row += rowOffset;
}
// Ensure row is still valid after adding the rowOffset?
if (row >= data.rowCount)
{
continue;
}
}
else
{
// When not animating cull rows outside scroll rect
float screenSpaceRowY = gui.GetRowRect(row, rowWidth).y - state.scrollPos.y;
if (screenSpaceRowY > m_TotalRect.height)
{
continue;
}
}
if (enableItemHovering)
{
Rect rowRect = gui.GetRowRect(row, showingVerticalScrollBar ? rowWidth - kSpaceForScrollBar : rowWidth);
if (rowRect.Contains(Event.current.mousePosition))
currentHoveredItem = data.GetItem(row);
m_GUIView.MarkHotRegion(GUIClip.UnclipToWindow(rowRect));
}
// Item GUI
// Note that DoItemGUI() needs to be called right before checking m_StopIteratingItems since
// UI in the current row can issue a reload of the TreeView data
DoItemGUI(data.GetItem(row), row, rowWidth, hasFocus);
if (m_StopIteratingItems)
break;
}
hoveredItem = currentHoveredItem;
}
private void ExpansionAnimationEnded(TreeViewAnimationInput setup)
{
// When collapsing we delay the actual collapse until the animation is done
if (!setup.expanding)
{
ChangeExpandedState(setup.item, false, setup.includeChildren);
}
}
float GetAnimationDuration(float height)
{
// Speed up animation linearly for heights below kThreshold.
// We have found from usability testing that for smaller height changes (e.g 3-4 rows)
// we want a faster animation
const float kThreshold = 60f;
const float kMaxDuration = 0.07f;
return (height > kThreshold) ? kMaxDuration : (height * kMaxDuration / kThreshold);
}
public void UserInputChangedExpandedState(TreeViewItem item, int row, bool expand)
{
var includeChildren = Event.current.alt;
if (useExpansionAnimation)
{
// We need to expand prior to starting animation so we have the expanded state ready
if (expand)
ChangeExpandedState(item, true, includeChildren);
int rowStart = row + 1;
int rowEnd = GetLastChildRowUnder(row);
float rowWidth = GUIClip.visibleRect.width;
Rect allRowsRect = GetRectForRows(rowStart, rowEnd, rowWidth);
float duration = GetAnimationDuration(allRowsRect.height);
var input = new TreeViewAnimationInput
{
animationDuration = duration,
startRow = rowStart,
endRow = rowEnd,
startRowRect = gui.GetRowRect(rowStart, rowWidth),
rowsRect = allRowsRect,
expanding = expand,
includeChildren = includeChildren,
animationEnded = ExpansionAnimationEnded,
item = item,
treeView = this
};
expansionAnimator.BeginAnimating(input);
}
else
{
ChangeExpandedState(item, expand, includeChildren);
}
}
void ChangeExpandedState(TreeViewItem item, bool expand, bool includeChildren)
{
if (includeChildren)
data.SetExpandedWithChildren(item, expand);
else
data.SetExpanded(item, expand);
}
int GetLastChildRowUnder(int row)
{
var rows = data.GetRows();
int rowDepth = rows[row].depth;
for (int i = row + 1; i < rows.Count; ++i)
if (rows[i].depth <= rowDepth)
return i - 1;
return rows.Count - 1; // end row
}
protected virtual Rect GetRectForRows(int startRow, int endRow, float rowWidth)
{
Rect startRect = gui.GetRowRect(startRow, rowWidth);
Rect endRect = gui.GetRowRect(endRow, rowWidth);
return new Rect(startRect.x, startRect.y, rowWidth, endRect.yMax - startRect.yMin);
}
void HandleUnusedEvents()
{
switch (Event.current.type)
{
case EventType.DragUpdated:
if (dragging != null && m_TotalRect.Contains(Event.current.mousePosition))
{
dragging.DragElement(null, new Rect(), -1);
Repaint();
Event.current.Use();
}
break;
case EventType.DragPerform:
if (dragging != null && m_TotalRect.Contains(Event.current.mousePosition))
{
m_DragSelection.Clear();
dragging.DragElement(null, new Rect(), -1);
Repaint();
Event.current.Use();
}
break;
case EventType.DragExited:
if (dragging != null)
{
m_DragSelection.Clear();
dragging.DragCleanup(true);
Repaint();
}
break;
case EventType.MouseDown:
bool containsMouse = m_TotalRect.Contains(Event.current.mousePosition);
if (containsMouse)
{
GUIUtility.keyboardControl = m_KeyboardControlID;
Repaint();
}
if (deselectOnUnhandledMouseDown && containsMouse && Event.current.button == 0 && state.selectedIDs.Count > 0)
{
SetSelection(new int[0], false);
NotifyListenersThatSelectionChanged();
}
break;
case EventType.ContextClick:
if (m_TotalRect.Contains(Event.current.mousePosition))
{
if (contextClickOutsideItemsCallback != null)
contextClickOutsideItemsCallback();
}
break;
}
}
public void OnEvent()
{
state.renameOverlay.OnEvent();
}
public bool BeginNameEditing(float delay)
{
// No items selected for rename
if (state.selectedIDs.Count == 0)
return false;
var visibleItems = data.GetRows();
TreeViewItem visibleAndSelectedItem = null;
foreach (int id in state.selectedIDs)
{
TreeViewItem item = visibleItems.FirstOrDefault(i => i.id == id);
if (visibleAndSelectedItem == null)
visibleAndSelectedItem = item;
else if (item != null)
return false; // Don't allow rename if more than one item is both visible and selected
}
if (visibleAndSelectedItem != null && data.IsRenamingItemAllowed(visibleAndSelectedItem))
return gui.BeginRename(visibleAndSelectedItem, delay);
return false;
}
// Let client end renaming from outside
public void EndNameEditing(bool acceptChanges)
{
if (state.renameOverlay.IsRenaming())
{
state.renameOverlay.EndRename(acceptChanges);
gui.EndRename();
}
}
TreeViewItem GetItemAndRowIndex(int id, out int row)
{
row = data.GetRow(id);
if (row == -1)
return null;
return data.GetItem(row);
}
void HandleFastCollapse(TreeViewItem item, int row)
{
if (item.depth == 0)
{
// At depth 0 traverse upwards until a parent is found and select that item
for (int i = row - 1; i >= 0; --i)
{
if (data.GetItem(i).hasChildren)
{
OffsetSelection(i - row);
return;
}
}
}
else if (item.depth > 0)
{
// Traverse upwards until parent of item is found and select that parent (users want this behavior)
for (int i = row - 1; i >= 0; --i)
{
if (data.GetItem(i).depth < item.depth)
{
OffsetSelection(i - row);
return;
}
}
}
}
void HandleFastExpand(TreeViewItem item, int row)
{
int rowCount = data.rowCount;
// Traverse downwards until a parent is found and select that parent
for (int i = row + 1; i < rowCount; ++i)
{
if (data.GetItem(i).hasChildren)
{
OffsetSelection(i - row);
break;
}
}
}
private void ChangeFolding(int[] ids, bool expand)
{
// Handle folding of single item and multiple items separately
// Animation is only supported for folding of single item
if (ids.Length == 1)
ChangeFoldingForSingleItem(ids[0], expand);
else if (ids.Length > 1)
ChangeFoldingForMultipleItems(ids, expand);
}
private void ChangeFoldingForSingleItem(int id, bool expand)
{
int row;
TreeViewItem item = GetItemAndRowIndex(id, out row);
if (item != null)
{
if (data.IsExpandable(item) && data.IsExpanded(item) != expand)
UserInputChangedExpandedState(item, row, expand);
else
{
expansionAnimator.SkipAnimating();
if (expand)
HandleFastExpand(item, row); // Move selection to next parent
else
HandleFastCollapse(item, row); // Move selection to parent
}
}
}
private void ChangeFoldingForMultipleItems(int[] ids, bool expand)
{
// Collect items that should be expanded/collapsed
var parents = new HashSet<int>();
foreach (var id in ids)
{
int row;
TreeViewItem item = GetItemAndRowIndex(id, out row);
if (item != null)
{
if (data.IsExpandable(item) && data.IsExpanded(item) != expand)
parents.Add(id);
}
}