forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPackageImportTreeView.cs
669 lines (550 loc) · 26.4 KB
/
PackageImportTreeView.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
// 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.IMGUI.Controls;
using UnityEditor.Utils;
using UnityEngine;
using UnityEditorInternal;
using UnityEditor.Experimental;
namespace UnityEditor
{
internal class PackageImportTreeView
{
TreeViewController m_TreeView;
List<PackageImportTreeViewItem> m_Selection = new List<PackageImportTreeViewItem>();
static readonly bool s_UseFoldouts = true;
public enum EnabledState
{
NotSet = -1,
None = 0,
All = 1,
Mixed = 2
}
private PackageImport m_PackageImport;
public ImportPackageItem[] packageItems { get { return m_PackageImport.packageItems; } }
public PackageImportTreeView(PackageImport packageImport, TreeViewState treeViewState, Rect startRect)
{
m_PackageImport = packageImport;
m_TreeView = new TreeViewController(m_PackageImport, treeViewState);
var dataSource = new PackageImportTreeViewDataSource(m_TreeView, this);
var gui = new PackageImportTreeViewGUI(m_TreeView, this);
m_TreeView.Init(startRect, dataSource, gui, null);
m_TreeView.ReloadData();
m_TreeView.selectionChangedCallback += SelectionChanged;
gui.itemWasToggled += ItemWasToggled;
ComputeEnabledStateForFolders();
}
void ComputeEnabledStateForFolders()
{
var root = m_TreeView.data.root as PackageImportTreeViewItem;
var done = new HashSet<PackageImportTreeViewItem>();
done.Add(root); // Dont compute for root: mark it as done
RecursiveComputeEnabledStateForFolders(root, done);
}
void RecursiveComputeEnabledStateForFolders(PackageImportTreeViewItem pitem, HashSet<PackageImportTreeViewItem> done)
{
if (pitem.item != null && !pitem.item.isFolder)
return;
// Depth first recursion to allow parent folders be dependant on child folders
// Recurse
if (pitem.hasChildren)
{
foreach (var child in pitem.children)
{
RecursiveComputeEnabledStateForFolders(child as PackageImportTreeViewItem, done);
}
}
// Now do logic
if (!done.Contains(pitem))
{
EnabledState amount = GetFolderChildrenEnabledState(pitem);
pitem.enableState = amount;
// If 'item' is mixed then all of its parents will also be mixed
if (amount == EnabledState.Mixed)
{
done.Add(pitem);
var current = pitem.parent as PackageImportTreeViewItem;
while (current != null)
{
if (!done.Contains(current))
{
current.enableState = EnabledState.Mixed;
done.Add(current);
}
current = current.parent as PackageImportTreeViewItem;
}
}
}
}
bool ItemShouldBeConsideredForEnabledCheck(PackageImportTreeViewItem pitem)
{
// Not even an item
if (pitem == null)
return false;
// item was a folder that had to be created
// in this treeview.
if (pitem.item == null)
return true;
var item = pitem.item;
// Its a package asset or its changed
if (item.projectAsset || !(item.isFolder || item.assetChanged))
return false;
return true;
}
EnabledState GetFolderChildrenEnabledState(PackageImportTreeViewItem folder)
{
if (folder.item != null && !folder.item.isFolder)
Debug.LogError("Should be a folder item!");
if (!folder.hasChildren)
return EnabledState.None;
EnabledState amount = EnabledState.NotSet;
int i = 0;
for (; i < folder.children.Count; ++i)
{
// We dont want to consider project assets in this calculation as they are
// ignored
var firstValidChild = folder.children[i] as PackageImportTreeViewItem;
if (ItemShouldBeConsideredForEnabledCheck(firstValidChild))
{
amount = firstValidChild.enableState;
break;
}
}
++i;
for (; i < folder.children.Count; ++i)
{
// We dont want to consider project assets in this calculation as they are
// ignored
var childItem = folder.children[i] as PackageImportTreeViewItem;
if (ItemShouldBeConsideredForEnabledCheck(childItem))
{
if (amount != childItem.enableState)
{
amount = EnabledState.Mixed;
break;
}
}
}
if (amount == EnabledState.NotSet)
return EnabledState.None;
return amount;
}
void SelectionChanged(int[] selectedIDs)
{
// Cache selected tree view items (from ids)
m_Selection = new List<PackageImportTreeViewItem>();
var visibleItems = m_TreeView.data.GetRows();
foreach (var visibleItem in visibleItems)
{
if (selectedIDs.Contains(visibleItem.id))
{
var pitem = visibleItem as PackageImportTreeViewItem;
if (pitem != null)
m_Selection.Add(pitem);
}
}
// Show preview on selection
var selectedItem = m_Selection[0].item;
if (m_Selection.Count == 1 && selectedItem != null && !string.IsNullOrEmpty(selectedItem.previewPath))
{
var gui = m_TreeView.gui as PackageImportTreeViewGUI;
gui.showPreviewForID = m_Selection[0].id;
}
else
{
PopupWindowWithoutFocus.Hide();
}
}
public void OnGUI(Rect rect)
{
// Remove preview popup on mouse scroll wheel events
if (Event.current.type == EventType.ScrollWheel)
PopupWindowWithoutFocus.Hide();
int keyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard);
m_TreeView.OnGUI(rect, keyboardControlID);
// Keyboard space toggles selection enabledness
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Space &&
m_Selection != null && m_Selection.Count > 0 && GUIUtility.keyboardControl == keyboardControlID)
{
var pitem = m_Selection[0];
if (pitem != null)
{
EnabledState newEnabled = (pitem.enableState == EnabledState.None) ? EnabledState.All : EnabledState.None;
pitem.enableState = newEnabled;
ItemWasToggled(m_Selection[0]);
}
Event.current.Use();
}
}
public void SetAllEnabled(EnabledState state)
{
EnableChildrenRecursive(m_TreeView.data.root, state);
ComputeEnabledStateForFolders();
}
void ItemWasToggled(PackageImportTreeViewItem pitem)
{
if (m_Selection.Count <= 1)
{
EnableChildrenRecursive(pitem, pitem.enableState);
}
else
{
foreach (var childPItem in m_Selection)
{
childPItem.enableState = pitem.enableState;
}
}
ComputeEnabledStateForFolders();
}
void EnableChildrenRecursive(TreeViewItem parentItem, EnabledState state)
{
if (!parentItem.hasChildren)
return;
foreach (TreeViewItem tvitem in parentItem.children)
{
var pitem = tvitem as PackageImportTreeViewItem;
pitem.enableState = state;
EnableChildrenRecursive(pitem, state);
}
}
// Item
private class PackageImportTreeViewItem : TreeViewItem
{
public ImportPackageItem item { get; set; }
public EnabledState enableState
{
get { return m_EnableState; }
set
{
// We only want to set the enabled state if the item
// is not a project asset.
if (item == null || !item.projectAsset)
{
m_EnableState = value;
if (item != null)
item.enabledStatus = (int)value;
}
}
}
public PackageImportTreeViewItem(ImportPackageItem itemIn, int id, int depth, TreeViewItem parent, string displayName)
: base(id, depth, parent, displayName)
{
item = itemIn;
if (item == null)
m_EnableState = EnabledState.All;
else
m_EnableState = (EnabledState)item.enabledStatus;
}
private EnabledState m_EnableState;
}
// Gui
private class PackageImportTreeViewGUI : TreeViewGUI
{
internal static class Constants
{
public static Texture2D folderIcon = EditorGUIUtility.FindTexture(EditorResources.folderIconName);
public static GUIContent badgeNew = EditorGUIUtility.TrIconContent("PackageBadgeNew", "This is a new Asset");
public static GUIContent badgeDelete = EditorGUIUtility.TrIconContent("PackageBadgeDelete", "These files will be deleted!");
public static GUIContent badgeWarn = EditorGUIUtility.TrIconContent("console.warnicon", "Warning: File exists in project, but with different GUID. Will override existing asset which may be undesired.");
public static GUIContent badgeChange = EditorGUIUtility.TrIconContent("playLoopOff", "This file is new or has changed.");
public static GUIStyle paddinglessStyle;
static Constants()
{
paddinglessStyle = new GUIStyle();
paddinglessStyle.padding = new RectOffset(0, 0, 0, 0);
}
}
public Action<PackageImportTreeViewItem> itemWasToggled;
public int showPreviewForID { get; set; }
private PackageImportTreeView m_PackageImportView;
protected float k_FoldoutWidth = 12f;
public PackageImportTreeViewGUI(TreeViewController treeView, PackageImportTreeView view)
: base(treeView)
{
m_PackageImportView = view;
k_BaseIndent = 4f;
if (!s_UseFoldouts)
k_FoldoutWidth = 0f;
}
override public void OnRowGUI(Rect rowRect, TreeViewItem tvItem, int row, bool selected, bool focused)
{
k_IndentWidth = 18;
k_FoldoutWidth = 18;
const float k_ToggleWidth = 18f;
var pitem = tvItem as PackageImportTreeViewItem;
var item = pitem.item;
bool repainting = Event.current.type == EventType.Repaint;
// 0. Selection row rect
if (selected && repainting)
selectionStyle.Draw(rowRect, false, false, true, focused);
bool validItem = (item != null);
bool isFolder = (item != null) ? item.isFolder : true;
bool assetChanged = (item != null) ? item.assetChanged : false;
bool pathConflict = (item != null) ? item.pathConflict : false;
bool exists = (item != null) ? item.exists : true;
bool projectAsset = (item != null) ? item.projectAsset : false;
// 1. Foldout
if (m_TreeView.data.IsExpandable(tvItem))
DoFoldout(rowRect, tvItem, row);
// 2. Toggle only for items that are actually in the package.
Rect toggleRect = new Rect(k_BaseIndent + tvItem.depth * indentWidth + k_FoldoutWidth, rowRect.y, k_ToggleWidth, rowRect.height);
if ((isFolder && !projectAsset) || (validItem && !projectAsset && assetChanged))
DoToggle(pitem, toggleRect);
using (new EditorGUI.DisabledScope(!validItem || projectAsset))
{
// 3. Icon & Text
Rect contentRect = new Rect(toggleRect.xMax, rowRect.y, rowRect.width, rowRect.height);
DoIconAndText(tvItem, contentRect, selected, focused);
// 4. Preview popup
DoPreviewPopup(pitem, rowRect);
// 4.5 Warning about file clashing.
if (repainting && validItem && pathConflict)
{
Rect labelRect = new Rect(rowRect.xMax - 58, rowRect.y, rowRect.height, rowRect.height);
EditorGUIUtility.SetIconSize(new Vector2(rowRect.height, rowRect.height));
GUI.Label(labelRect, Constants.badgeWarn);
EditorGUIUtility.SetIconSize(Vector2.zero);
}
// 5. Optional badge ("New")
if (repainting && validItem && !(exists || pathConflict))
{
// FIXME: Need to enable tooltips here.
Texture badge = Constants.badgeNew.image;
Rect labelRect = new Rect(rowRect.xMax - badge.width - 6, rowRect.y + (rowRect.height - badge.height) / 2, badge.width, badge.height);
GUI.Label(labelRect, Constants.badgeNew, Constants.paddinglessStyle);
}
// 5. Optional badge ("Delete")
if (repainting && projectAsset)
{
// FIXME: Need to enable tooltips here.
Texture badge = Constants.badgeDelete.image;
Rect labelRect = new Rect(rowRect.xMax - badge.width - 6, rowRect.y + (rowRect.height - badge.height) / 2, badge.width, badge.height);
GUI.Label(labelRect, Constants.badgeDelete, Constants.paddinglessStyle);
}
// 7. Show what stuff has changed
if (repainting && validItem && (exists || pathConflict) && assetChanged)
{
Texture badge = Constants.badgeChange.image;
Rect labelRect = new Rect(rowRect.xMax - badge.width - 6, rowRect.y, rowRect.height, rowRect.height);
GUI.Label(labelRect, Constants.badgeChange, Constants.paddinglessStyle);
}
}
}
static void Toggle(ImportPackageItem[] items, PackageImportTreeViewItem pitem, Rect toggleRect)
{
bool enabled = (int)pitem.enableState > 0;
bool isFolder = (pitem.item == null) || pitem.item.isFolder;
GUIStyle style = EditorStyles.toggle;
bool setMixed = isFolder && (pitem.enableState == EnabledState.Mixed);
if (setMixed)
style = EditorStyles.toggleMixed;
bool newEnabled = GUI.Toggle(toggleRect, enabled, GUIContent.none, style);
if (newEnabled != enabled)
pitem.enableState = newEnabled ? EnabledState.All : EnabledState.None;
}
void DoToggle(PackageImportTreeViewItem pitem, Rect toggleRect)
{
// Toggle on/off
EditorGUI.BeginChangeCheck();
Toggle(m_PackageImportView.packageItems, pitem, toggleRect);
if (EditorGUI.EndChangeCheck())
{
// Only change selection if we already have single selection (Keep multi-selection when toggling)
if (m_TreeView.GetSelection().Length <= 1 || !m_TreeView.GetSelection().Contains(pitem.id))
{
m_TreeView.SetSelection(new int[] { pitem.id }, false);
m_TreeView.NotifyListenersThatSelectionChanged();
}
if (itemWasToggled != null)
itemWasToggled(pitem);
Event.current.Use();
}
}
void DoPreviewPopup(PackageImportTreeViewItem pitem, Rect rowRect)
{
var item = pitem.item;
if (item != null)
{
// Ensure preview is shown when clicking on an already selected item (the preview might have been closed)
if (Event.current.type == EventType.MouseDown && rowRect.Contains(Event.current.mousePosition) && !PopupWindowWithoutFocus.IsVisible())
showPreviewForID = pitem.id;
// Show preview
if (pitem.id == showPreviewForID && Event.current.type != EventType.Layout)
{
showPreviewForID = 0;
if (!string.IsNullOrEmpty(item.previewPath))
{
Texture2D preview = PackageImport.GetPreview(item.previewPath);
Rect buttonRect = rowRect;
buttonRect.width = EditorGUIUtility.currentViewWidth;
PopupWindowWithoutFocus.Show(buttonRect, new PreviewPopup(preview), new[] { PopupLocation.Right, PopupLocation.Left, PopupLocation.Below });
}
}
}
}
void DoIconAndText(TreeViewItem item, Rect contentRect, bool selected, bool focused)
{
EditorGUIUtility.SetIconSize(new Vector2(k_IconWidth, k_IconWidth)); // If not set we see icons scaling down if text is being cropped
lineStyle = Styles.lineStyle;
lineStyle.padding.left = 0; // padding could have been set by other tree views
contentRect.height += 5; // with the default row height, underscore and lower parts of characters like g, p, etc. were not visible
if (Event.current.type == EventType.Repaint)
lineStyle.Draw(contentRect, GUIContent.Temp(item.displayName, GetIconForItem(item)), false, false, selected, focused);
EditorGUIUtility.SetIconSize(Vector2.zero);
}
protected override Texture GetIconForItem(TreeViewItem tvItem)
{
var ourItem = tvItem as PackageImportTreeViewItem;
var item = ourItem.item;
// Indefined items are always folders.
if (item == null || item.isFolder)
{
return Constants.folderIcon;
}
// We are using this TreeViewGUI when importing and exporting a package, so handle both situations:
// Exporting a package can use cached icons (icons we generate on import)
Texture cachedIcon = AssetDatabase.GetCachedIcon(item.destinationAssetPath);
if (cachedIcon != null)
return cachedIcon;
// Importing a package have to use icons based on file extension
return InternalEditorUtility.GetIconForFile(item.destinationAssetPath);
}
protected override void RenameEnded()
{
}
}
// Datasource
private class PackageImportTreeViewDataSource : TreeViewDataSource
{
private PackageImportTreeView m_PackageImportView;
public PackageImportTreeViewDataSource(TreeViewController treeView, PackageImportTreeView view)
: base(treeView)
{
m_PackageImportView = view;
rootIsCollapsable = false;
showRootItem = false;
}
public override bool IsRenamingItemAllowed(TreeViewItem item)
{
return false;
}
public override bool IsExpandable(TreeViewItem item)
{
if (!s_UseFoldouts)
return false;
return base.IsExpandable(item);
}
public override void FetchData()
{
int rootDepth = -1; // -1 so its children will have 0 depth
m_RootItem = new PackageImportTreeViewItem(null, "Assets".GetHashCode(), rootDepth, null, "InvisibleAssetsFolder");
bool initExpandedState = true;
if (initExpandedState)
m_TreeView.state.expandedIDs.Add(m_RootItem.id);
ImportPackageItem[] items = m_PackageImportView.packageItems;
Dictionary<string, TreeViewItem> treeViewFolders = new Dictionary<string, TreeViewItem>();
for (int i = 0; i < items.Length; i++)
{
var item = items[i];
if (PackageImport.HasInvalidCharInFilePath(item.destinationAssetPath))
continue; // Do not add invalid paths (we already warn the user with a dialog in PackageImport.cs)
string filename = Path.GetFileName(item.destinationAssetPath).ConvertSeparatorsToUnity();
string folderPath = Path.GetDirectoryName(item.destinationAssetPath).ConvertSeparatorsToUnity();
// Ensure folders. This is for when installed packages have been moved to other folders.
TreeViewItem targetFolder;
treeViewFolders.TryGetValue(folderPath, out targetFolder);
if (targetFolder == null)
{
targetFolder = EnsureFolderPath(folderPath, treeViewFolders, initExpandedState);
}
// Add file to folder
if (targetFolder != null)
{
int id = item.destinationAssetPath.GetHashCode();
var newItem = new PackageImportTreeViewItem(item, id, targetFolder.depth + 1, targetFolder, filename);
targetFolder.AddChild(newItem);
if (initExpandedState)
m_TreeView.state.expandedIDs.Add(id);
// We need to ensure that the folder is available for
// EnsureFolderPath on subsequent iterations.
if (item.isFolder)
treeViewFolders[item.destinationAssetPath] = newItem;
}
}
if (initExpandedState)
m_TreeView.state.expandedIDs.Sort();
}
TreeViewItem EnsureFolderPath(string folderPath, Dictionary<string, TreeViewItem> treeViewFolders, bool initExpandedState)
{
//We're in the root folder, so just return the root item as the parent.
if (folderPath == "")
return m_RootItem;
// Does folder path exist?
int id = folderPath.GetHashCode();
TreeViewItem item = TreeViewUtility.FindItem(id, m_RootItem);
if (item != null)
{
return item;
}
// Add folders as needed
string[] splitPath = folderPath.Split('/');
string currentPath = "";
TreeViewItem currentItem = m_RootItem;
int folderDepth = -1; // Will be incremented to the right depth in the loop.
for (int depth = 0; depth < splitPath.Length; ++depth)
{
string folder = splitPath[depth];
if (currentPath != "")
currentPath += '/';
currentPath += folder;
// Dont create a 'Assets' folder (we already have that as a hidden root)
if (depth == 0 && currentPath == "Assets")
continue;
// Only increment the folder depth if we are past the root "Assets" folder.
++folderDepth;
id = currentPath.GetHashCode();
TreeViewItem foundItem;
if (treeViewFolders.TryGetValue(currentPath, out foundItem))
{
currentItem = foundItem;
}
else
{
// If we do not have a tree view item for this folder we create one
var folderItem = new PackageImportTreeViewItem(null, id, folderDepth, currentItem, folder);
// Add to children array of the parent
currentItem.AddChild(folderItem);
currentItem = folderItem;
// Auto expand all folder items
if (initExpandedState)
m_TreeView.state.expandedIDs.Add(id);
// For faster finding of folders
treeViewFolders[currentPath] = folderItem;
}
}
return currentItem;
}
}
class PreviewPopup : PopupWindowContent
{
readonly Texture2D m_Preview;
readonly Vector2 kPreviewSize = new Vector2(128f, 128f);
public PreviewPopup(Texture2D preview)
{
m_Preview = preview;
}
public override void OnGUI(Rect rect)
{
PackageImport.DrawTexture(rect, m_Preview, false);
}
public override Vector2 GetWindowSize()
{
return kPreviewSize;
}
}
}
}