forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchUtils.cs
More file actions
1563 lines (1363 loc) · 64.4 KB
/
Copy pathSearchUtils.cs
File metadata and controls
1563 lines (1363 loc) · 64.4 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.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Pool;
using UnityEditor.Search.Providers;
using UnityEditor.Utils;
using UnityEngine.Search;
using UnityEditor.SceneManagement;
namespace UnityEditor.Search
{
/// <summary>
/// Utilities used by multiple components of QuickSearch.
/// </summary>
public static class SearchUtils
{
private static readonly string[] k_Dots = { ".", "..", "..." };
internal static readonly char[] KeywordsValueDelimiters = new[] { ':', '=', '<', '>', '!', '|' };
private static readonly char[] k_AdbInvalidCharacters = {'/', '?', '<', '>', '\\', ':', '*', '|', '"' };
/// <summary>
/// Separators used to split an entry into indexable tokens.
/// </summary>
public static readonly char[] entrySeparators = { '/', ' ', '_', '-', '.' };
private static readonly Stack<StringBuilder> _SbPool = new Stack<StringBuilder>();
/// <summary>
/// Extract all variations on a word.
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
public static string[] FindShiftLeftVariations(string word)
{
if (word.Length <= 1)
return new string[0];
var variations = new List<string>(word.Length) { word };
for (int i = 1, end = word.Length - 1; i < end; ++i)
{
word = word.Substring(1);
variations.Add(word);
}
return variations.ToArray();
}
public static Texture2D GetSceneObjectPreview(GameObject obj, Vector2 size, FetchPreviewOptions options, Texture2D thumbnail)
{
return Utils.GetSceneObjectPreview(null, obj, size, options, thumbnail);
}
public static Texture2D GetSceneObjectPreview(SearchContext ctx, GameObject obj, Vector2 size, FetchPreviewOptions options, Texture2D thumbnail)
{
return GetSceneObjectPreview(null, obj, size, options, thumbnail);
}
/// <summary>
/// Tokenize a string each Capital letter.
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
static readonly Regex s_CamelCaseSplit = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
public static string[] SplitCamelCase(string source)
{
return s_CamelCaseSplit.Split(source);
}
internal static string UppercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}
internal static string LowercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
// Return char and concat substring.
return char.ToLower(s[0]) + s.Substring(1);
}
internal static string ToPascalWithSpaces(string s, bool uppercaseFirstWordOnly = false)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
var tokens = Regex.Split(s, @"-+|_+|\s+|(?<!^)(?=[A-Z0-9])")
.Where(t => !string.IsNullOrWhiteSpace(t))
.Select((word, index) =>
{
if (uppercaseFirstWordOnly && index != 0)
return LowercaseFirst(word);
return UppercaseFirst(word);
});
return string.Join(" ", tokens);
}
/// <summary>
/// Split an entry according to a specified list of separators.
/// </summary>
/// <param name="entry">Entry to split.</param>
/// <param name="entrySeparators">List of separators that indicate split points.</param>
/// <returns>Returns list of tokens in lowercase</returns>
public static IEnumerable<string> SplitEntryComponents(string entry, char[] entrySeparators)
{
var nameTokens = entry.Split(entrySeparators).Distinct();
var scc = nameTokens.SelectMany(s => SplitCamelCase(s)).Where(s => s.Length > 0);
var fcc = scc.Aggregate("", (current, s) => current + s[0]);
return new[] { fcc }.Concat(scc.Where(s => s.Length > 1))
.Where(s => s.Length > 1)
.Select(s => s.ToLowerInvariant())
.Distinct();
}
/// <summary>
/// Split a file entry according to a list of separators and find all the variations on the entry name.
/// </summary>
/// <param name="path"></param>
/// <param name="entrySeparators"></param>
/// <returns>Returns list of tokens and variations in lowercase</returns>
public static IEnumerable<string> SplitFileEntryComponents(string path, in char[] entrySeparators)
{
return SplitFileEntryComponents(path, entrySeparators, 1);
}
public static IEnumerable<string> SplitFileEntryComponents(string path, in char[] entrySeparators, int minTokenLength)
{
path = Utils.RemoveInvalidCharsFromPath(path, '_');
var name = Path.GetFileNameWithoutExtension(path);
var nameTokens = name.Split(entrySeparators).Distinct().ToArray();
var scc = nameTokens.SelectMany(s => SplitCamelCase(s)).Where(s => s.Length > 0).ToArray();
var fcc = scc.Aggregate("", (current, s) => current + s[0]);
return new[] { Path.GetExtension(path).Replace(".", "") }
.Concat(scc)
.Concat(FindShiftLeftVariations(fcc))
.Concat(nameTokens)
.Concat(path.Split(entrySeparators).Reverse())
.Where(s => s.Length >= minTokenLength)
.Select(s => s.ToLowerInvariant())
.Distinct();
}
/// <summary>
/// Format the pretty name of a Transform component by appending all the parents hierarchy names.
/// </summary>
/// <param name="tform">Transform to extract name from.</param>
/// <returns>Returns a transform name using "/" as hierarchy separator.</returns>
public static string GetTransformPath(Transform tform)
{
if (tform.parent == null)
return "/" + tform.name;
return GetTransformPath(tform.parent) + "/" + tform.name;
}
/// <summary>
/// Get the path of a Unity Object. If it is a GameObject or a Component it is the <see cref="SearchUtils.GetTransformPath(Transform)"/>. Else it is the asset name.
/// </summary>
/// <param name="obj"></param>
/// <returns>Returns the path of an object.</returns>
public static string GetObjectPath(UnityEngine.Object obj)
{
if (!obj)
return string.Empty;
if (obj is Component c)
return GetTransformPath(c.gameObject.transform);
var assetPath = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(assetPath))
{
if (Utils.IsBuiltInResource(assetPath))
return GlobalObjectId.GetGlobalObjectIdSlow(obj).ToString();
return assetPath;
}
if (obj is GameObject go)
return GetTransformPath(go.transform);
return obj.name;
}
static ulong GetStableHash(in UnityEngine.Object obj, in ulong assetHash = 0)
{
var fileIdHint = Utils.GetFileIDHint(obj);
if (fileIdHint == 0)
fileIdHint = (ulong)obj.GetInstanceID();
return fileIdHint * 1181783497276652981UL + assetHash;
}
/// <summary>
/// Return a unique document key owning the object
/// </summary>
internal static ulong GetDocumentKey(in UnityEngine.Object obj)
{
if (!obj)
return ulong.MaxValue;
if (obj is GameObject go)
return GetStableHash(go, (ulong)(GetHierarchyAssetPath(go)?.GetHashCode() ?? 0));
if (obj is Component c)
return GetDocumentKey(c.gameObject);
var assetPath = AssetDatabase.GetAssetPath(obj);
if (string.IsNullOrEmpty(assetPath))
return ulong.MaxValue;
return AssetDatabase.AssetPathToGUID(assetPath).GetHashCode64();
}
/// <summary>
/// Get the hierarchy path of a GameObject possibly including the scene name.
/// </summary>
/// <param name="gameObject">GameObject to extract a path from.</param>
/// <param name="includeScene">If true, will append the scene name to the path.</param>
/// <returns>Returns the path of a GameObject.</returns>
public static string GetHierarchyPath(GameObject gameObject, bool includeScene = true)
{
if (gameObject == null)
return String.Empty;
StringBuilder sb;
if (_SbPool.Count > 0)
{
sb = _SbPool.Pop();
sb.Clear();
}
else
{
sb = new StringBuilder(200);
}
try
{
if (includeScene)
{
var sceneName = gameObject.scene.name;
if (sceneName == string.Empty)
{
var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject);
if (prefabStage != null)
sceneName = "Prefab Stage";
else
sceneName = "Unsaved Scene";
}
sb.Append("<b>" + sceneName + "</b>");
}
sb.Append(GetTransformPath(gameObject.transform));
var path = sb.ToString();
sb.Clear();
return path;
}
finally
{
_SbPool.Push(sb);
}
}
/// <summary>
/// Get the path of the scene (or prefab) containing a GameObject.
/// </summary>
/// <param name="gameObject">GameObject to find the scene path.</param>
/// <param name="prefabOnly">If true, will return a path only if the GameObject is a prefab.</param>
/// <returns>Returns the path of a scene or prefab</returns>
public static string GetHierarchyAssetPath(GameObject gameObject, bool prefabOnly = false)
{
if (gameObject == null)
return String.Empty;
bool isPrefab = PrefabUtility.GetPrefabAssetType(gameObject.gameObject) != PrefabAssetType.NotAPrefab;
if (isPrefab)
return PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameObject);
if (prefabOnly)
return null;
return gameObject.scene.path;
}
/// <summary>
/// Select and ping multiple objects in the Project Browser.
/// </summary>
/// <param name="items">Search Items to select and ping.</param>
/// <param name="focusProjectBrowser">If true, will focus the project browser before pinging the objects.</param>
/// <param name="pingSelection">If true, will ping the selected objects.</param>
public static void SelectMultipleItems(IEnumerable<SearchItem> items, bool focusProjectBrowser = false, bool pingSelection = true)
{
Selection.objects = items.Select(i => i.ToObject()).Where(o => o).ToArray();
if (Selection.objects.Length == 0)
{
var firstItem = items.FirstOrDefault();
if (firstItem != null)
EditorUtility.OpenWithDefaultApp(firstItem.id);
return;
}
EditorApplication.delayCall += () =>
{
if (focusProjectBrowser)
EditorWindow.FocusWindowIfItsOpen(Utils.GetProjectBrowserWindowType());
if (pingSelection)
EditorApplication.delayCall += () => EditorGUIUtility.PingObject(Selection.objects.LastOrDefault());
};
}
/// <summary>
/// Helper function to match a string against the SearchContext. This will try to match the search query against each tokens of content (similar to the AddComponent menu workflow)
/// </summary>
/// <param name="context">Search context containing the searchQuery that we try to match.</param>
/// <param name="content">String content that will be tokenized and use to match the search query.</param>
/// <param name="ignoreCase">Perform matching ignoring casing.</param>
/// <returns>Has a match occurred.</returns>
public static bool MatchSearchGroups(SearchContext context, string content, bool ignoreCase = false)
{
return MatchSearchGroups(context.searchQuery, context.searchWords, content, out _, out _,
ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
internal static bool MatchSearchGroups(string searchContext, string[] tokens, string content, out int startIndex, out int endIndex, StringComparison sc = StringComparison.OrdinalIgnoreCase)
{
startIndex = endIndex = -1;
if (String.IsNullOrEmpty(content))
return false;
if (string.IsNullOrEmpty(searchContext))
return false;
if (searchContext == content)
{
startIndex = 0;
endIndex = content.Length - 1;
return true;
}
return MatchSearchGroups(tokens, content, out startIndex, out endIndex, sc);
}
internal static bool MatchSearchGroups(string[] tokens, string content, out int startIndex, out int endIndex, StringComparison sc = StringComparison.OrdinalIgnoreCase)
{
startIndex = endIndex = -1;
if (String.IsNullOrEmpty(content))
return false;
// Each search group is space separated
// Search group must match in order and be complete.
var searchGroups = tokens;
var startSearchIndex = 0;
foreach (var searchGroup in searchGroups)
{
if (searchGroup.Length == 0)
continue;
startSearchIndex = content.IndexOf(searchGroup, startSearchIndex, sc);
if (startSearchIndex == -1)
{
return false;
}
startIndex = startIndex == -1 ? startSearchIndex : startIndex;
startSearchIndex = endIndex = startSearchIndex + searchGroup.Length - 1;
}
return startIndex != -1 && endIndex != -1;
}
/// <summary>
/// Utility function to fetch all the game objects in a particular scene.
/// </summary>
/// <param name="scene">Scene to get objects from.</param>
/// <returns>The array of game objects in the scene.</returns>
public static GameObject[] FetchGameObjects(Scene scene)
{
var goRoots = new List<UnityEngine.Object>();
if (!scene.IsValid() || !scene.isLoaded)
return new GameObject[0];
var sceneRootObjects = scene.GetRootGameObjects();
if (sceneRootObjects != null && sceneRootObjects.Length > 0)
goRoots.AddRange(sceneRootObjects);
return SceneModeUtility.GetObjects(goRoots.ToArray(), true);
}
/// <summary>
/// Utility function to fetch all the game objects for the current stage (i.e. scene or prefab)
/// </summary>
/// <returns>The array of game objects in the current stage.</returns>
public static IEnumerable<GameObject> FetchGameObjects()
{
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
return SceneModeUtility.GetObjects(new[] { prefabStage.prefabContentsRoot }, true);
void AddScene(Scene scene, List<Scene> outScenes)
{
if (!scene.IsValid() || !scene.isLoaded)
return;
outScenes.Add(scene);
}
using var scenesPoolHandle = ListPool<Scene>.Get(out var scenes);
var stage = StageUtility.GetCurrentStage();
if (stage is not MainStage)
{
for (int i = 0, c = stage.sceneCount; i < c; ++i)
{
var scene = stage.GetSceneAt(i);
AddScene(scene, scenes);
}
}
else
{
for (int i = 0; i < SceneManager.sceneCount; ++i)
{
var scene = SceneManager.GetSceneAt(i);
AddScene(scene, scenes);
}
if (EditorApplication.isPlaying)
AddScene(EditorSceneManager.GetDontDestroyOnLoadScene(), scenes);
}
using var gameObjectRootPoolHandle = ListPool<UnityEngine.Object>.Get(out var goRoots);
using var sceneRootGameObjectPoolHandle = ListPool<GameObject>.Get(out var sceneRootObjects);
foreach (var scene in scenes)
{
scene.GetRootGameObjects(sceneRootObjects);
if (sceneRootObjects.Count > 0)
goRoots.AddRange(sceneRootObjects);
}
return SceneModeUtility.GetObjects(goRoots.ToArray(), true)
.Where(o => (o.hideFlags & HideFlags.HideInHierarchy) != HideFlags.HideInHierarchy);
}
internal static ISet<string> GetReferences(UnityEngine.Object obj, int level = 1)
{
var refs = new HashSet<string>();
var objPath = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(objPath))
refs.UnionWith(AssetDatabase.GetDependencies(objPath));
if (obj is GameObject go)
{
foreach (var c in go.GetComponents<Component>())
{
using (var so = new SerializedObject(c))
{
var p = so.GetIterator();
var next = p.NextVisible(true);
while (next)
{
if (p.propertyType == SerializedPropertyType.ObjectReference && p.objectReferenceValue)
{
var refValue = AssetDatabase.GetAssetPath(p.objectReferenceValue);
if (!String.IsNullOrEmpty(refValue))
refs.Add(refValue);
}
next = p.NextVisible(!p.isArray && !p.isFixedBuffer);
}
}
}
}
var lvlRefs = refs;
while (level-- > 0)
{
var nestedRefs = new HashSet<string>();
foreach (var r in lvlRefs)
nestedRefs.UnionWith(AssetDatabase.GetDependencies(r, false));
lvlRefs = nestedRefs;
lvlRefs.ExceptWith(refs);
refs.UnionWith(nestedRefs);
}
refs.Remove(objPath);
return refs;
}
static readonly Dictionary<string, SearchProvider> s_GroupProviders = new Dictionary<string, SearchProvider>();
public static SearchProvider CreateGroupProvider(SearchProvider templateProvider, string groupId, int groupPriority, bool cacheProvider = false)
{
if (cacheProvider && s_GroupProviders.TryGetValue(groupId, out var groupProvider))
return groupProvider;
groupProvider = new SearchProvider($"_group_provider_{groupId}", groupId, templateProvider, groupPriority);
if (cacheProvider)
s_GroupProviders[groupId] = groupProvider;
return groupProvider;
}
public static string GetAssetPath(in SearchItem item)
{
if (item.provider.type == Providers.AssetProvider.type)
return Providers.AssetProvider.GetAssetPath(item);
if (item.provider.type == "dep")
return AssetDatabase.GUIDToAssetPath(item.id);
return null;
}
static Dictionary<Type, List<Type>> s_BaseTypes = new Dictionary<Type, List<Type>>();
internal static IEnumerable<SearchProposition> FetchTypePropositions<T>(string category = "Types", Type blockType = null, int priority = -1444) where T : UnityEngine.Object
{
if (category != null)
{
yield return new SearchProposition(category: category, label: "Prefabs", replacement: "t:prefab",
icon: GetTypeIcon(typeof(GameObject)), data: typeof(GameObject), type: blockType, priority: priority, color: QueryColors.type);
}
if (string.Equals(category, "Types", StringComparison.Ordinal))
{
yield return new SearchProposition(category: "Types", label: "Scripts", replacement: "t:script",
icon: GetTypeIcon(typeof(MonoScript)), data: typeof(MonoScript), type: blockType, priority: priority, color: QueryColors.type);
yield return new SearchProposition(category: "Types", label: "Scenes", replacement: "t:scene",
icon: GetTypeIcon(typeof(SceneAsset)), data: typeof(SceneAsset), type: blockType, priority: priority, color: QueryColors.type);
yield return new SearchProposition(category: "Types", label: "Presets", replacement: "t:preset",
icon: GetTypeIcon(typeof(Presets.Preset)), data: typeof(Presets.Preset), type: blockType, priority: priority, color: QueryColors.type);
}
if (!s_BaseTypes.TryGetValue(typeof(T), out var types))
{
var ignoredAssemblies = new[]
{
typeof(EditorApplication).Assembly,
typeof(UnityEditorInternal.InternalEditorUtility).Assembly
};
types = TypeCache.GetTypesDerivedFrom<T>()
.Where(t => !t.IsGenericType)
.Where(t => !ignoredAssemblies.Contains(t.Assembly))
.Where(t => !typeof(Editor).IsAssignableFrom(t))
.Where(t => !typeof(EditorWindow).IsAssignableFrom(t))
.Where(t => t.Assembly.GetName().Name.IndexOf("Editor", StringComparison.Ordinal) == -1).ToList();
s_BaseTypes[typeof(T)] = types;
}
foreach (var t in types)
{
yield return new SearchProposition(
priority: t.Name[0] + priority,
category: category,
label: t.Name,
replacement: $"t:{t.Name}",
data: t,
help: $"Search {t.Name}",
type: blockType,
icon: GetTypeIcon(t),
color: QueryColors.type);
}
}
internal static SearchProposition CreateKeywordProposition(in string keyword)
{
if (keyword.IndexOf('|') == -1)
return SearchProposition.invalid;
var tokens = keyword.Split('|');
if (tokens.Length < 5)
return SearchProposition.invalid;
// <0:fieldname>:|<1:display name>|<2:help text>|<3:property type>|<4: owner type string>|<5:propositionOptions>
var valueType = tokens[3];
var replacement = ParseBlockContent(valueType, tokens[0], out Type blockType);
var ownerType = FindType<UnityEngine.Object>(tokens[4]);
if (ownerType == null)
return SearchProposition.invalid;
var generationOptions = SearchPropositionGenerationOptions.None;
if (tokens.Length >= 6 && !string.IsNullOrWhiteSpace(tokens[5]))
{
if (Utils.TryParse<int>(tokens[5], out var temp))
{
generationOptions = (SearchPropositionGenerationOptions)temp;
}
}
return new SearchProposition(
category: $"Properties/{ObjectNames.NicifyVariableName(ownerType.Name)}",
label: $"{tokens[1]} ({blockType?.Name ?? valueType})",
replacement: replacement,
help: tokens[2],
priority: (ownerType.Name[0] << 4) + tokens[1][0],
moveCursor: TextCursorPlacement.MoveAutoComplete,
icon:
AssetPreview.GetMiniTypeThumbnailFromType(blockType) ??
GetTypeIcon(ownerType),
type: null,
data: null,
color: replacement.StartsWith("#", StringComparison.Ordinal) ? QueryColors.property : QueryColors.filter,
generationOptions: generationOptions
);
}
internal static IEnumerable<SearchProposition> FetchEnumPropositions<T>(string category = null, string replacementId = null, string replacementOp = null, Type blockType = null, int priority = 0, Texture2D icon = null, Color color = default) where T : Enum
{
var type = typeof(T);
return FetchEnumPropositions(type, category, replacementId, replacementOp, blockType, priority, icon, color);
}
internal static IEnumerable<SearchProposition> FetchEnumPropositions(Type enumType, string category = null, string replacementId = null, string replacementOp = null, Type blockType = null, int priority = 0, Texture2D icon = null, Color color = default)
{
if (!enumType?.IsEnum ?? true)
throw new ArgumentException("Type should of an enum.", nameof(enumType));
if (blockType == null)
blockType = typeof(QueryFilterBlock);
var replacementBase = $"{replacementId}{replacementOp}";
var enumNames = Enum.GetNames(enumType).Select(n => Utils.FastToLower(n)).ToList();
var fields = enumType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
foreach (var fieldInfo in fields)
{
if (fieldInfo.FieldType != enumType)
continue;
var enumName = fieldInfo.Name;
var label = ToPascalWithSpaces(enumName, true);
var data = Utils.FastToLower(enumName);
var replacement = label;
if (blockType == typeof(QueryFilterBlock))
{
replacement = $"{replacementBase}<$enum:{enumName},{enumType.FullName}$>";
}
else if (blockType == typeof(QueryListMarkerBlock))
{
replacement = $"{replacementBase}{GetListMarkerReplacementText(data, enumNames, Utils.GetIconSkinAgnosticName(icon), color)}";
data = replacement;
}
string help = null;
var descriptionAttribute = fieldInfo.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>();
if (descriptionAttribute != null)
help = descriptionAttribute.Description;
yield return new SearchProposition(category: category, label: label, replacement: replacement, help: help,
data: data, priority: priority, icon: icon, type: blockType, color: color);
}
}
static Dictionary<Type, Texture2D> s_TypeIcons = new Dictionary<Type, Texture2D>();
public static Texture2D GetTypeIcon(in Type type)
{
if (s_TypeIcons.TryGetValue(type, out var t) && t)
return t;
if (!type.IsAbstract && typeof(MonoBehaviour) != type && typeof(MonoBehaviour).IsAssignableFrom(type))
{
var script = EditorGUIUtility.GetScript(type.Name);
if (!script)
return s_TypeIcons[type] = AssetPreview.GetMiniTypeThumbnail(type) ?? AssetPreview.GetMiniTypeThumbnail(typeof(DefaultAsset));
var obj = EditorUtility.InstanceIDToObject(script.GetInstanceID());
var customIcon = AssetPreview.GetMiniThumbnail(obj);
return s_TypeIcons[type] = customIcon;
}
return s_TypeIcons[type] = AssetPreview.GetMiniTypeThumbnail(type) ?? AssetPreview.GetMiniTypeThumbnail(typeof(MonoScript));
}
internal static IEnumerable<SearchProposition> EnumeratePropertyPropositions(IEnumerable<UnityEngine.Object> objs, Func<SerializedObject, IEnumerable<SerializedProperty>> nonVisiblePropertyIterator = null)
{
return EnumeratePropertyKeywords(objs, nonVisiblePropertyIterator).Select(k => CreateKeywordProposition(k));
}
internal static void IterateSupportedProperties(SerializedObject so, Action<SerializedProperty> handler)
{
var p = so.GetIterator();
var next = p.NextVisible(true);
while (next)
{
var supported = SearchUtils.IsPropertyTypeSupported(p);
if (supported)
{
handler(p);
}
next = p.NextVisible(IterateSupportedProperties_EnterChildren(p));
}
}
internal static bool IterateSupportedProperties_EnterChildren(SerializedProperty p)
{
switch (p.propertyType)
{
case SerializedPropertyType.AnimationCurve:
case SerializedPropertyType.Bounds:
case SerializedPropertyType.Gradient:
case SerializedPropertyType.Vector3Int:
case SerializedPropertyType.Vector2Int:
case SerializedPropertyType.Vector2:
case SerializedPropertyType.Vector3:
case SerializedPropertyType.Vector4:
case SerializedPropertyType.Quaternion:
return false;
}
if (p.propertyType == SerializedPropertyType.Generic)
{
if (string.Equals(p.type, "map", StringComparison.Ordinal))
return false;
if (string.Equals(p.type, "Matrix4x4f", StringComparison.Ordinal))
return false;
}
return (p.propertyType == SerializedPropertyType.String || !p.isArray) && !p.isFixedBuffer && p.propertyPath.LastIndexOf('[') == -1;
}
internal static string GetPropertyNamePrefix(UnityEngine.Object obj)
{
var objType = obj.GetType();
var isComponent = typeof(Component).IsAssignableFrom(objType);
return isComponent ? objType.Name + "." : null;
}
internal static IEnumerable<string> EnumeratePropertyKeywords(IEnumerable<UnityEngine.Object> objs, Func<SerializedObject, IEnumerable<SerializedProperty>> nonVisiblePropertyIterator = null)
{
var templates = GetTemplates(objs);
foreach (var obj in templates)
{
var propertyPrefix = GetPropertyNamePrefix(obj);
using (var so = new SerializedObject(obj))
{
if (nonVisiblePropertyIterator != null)
{
foreach (var serializedProperty in nonVisiblePropertyIterator(so))
{
if (!IsPropertyTypeSupported(serializedProperty)) continue;
var propertyType = GetPropertyManagedTypeString(serializedProperty);
if (propertyType != null)
{
var keyword = CreateKeyword(serializedProperty, propertyType, propertyPrefix);
yield return keyword;
}
}
}
var p = so.GetIterator();
var next = p.NextVisible(true);
while (next)
{
var supported = SearchUtils.IsPropertyTypeSupported(p);
var propertyType = supported ? GetPropertyManagedTypeString(p) : null;
if (propertyType != null)
{
var keyword = CreateKeyword(p, propertyType, propertyPrefix);
yield return keyword;
}
next = p.NextVisible(IterateSupportedProperties_EnterChildren(p));
}
}
}
}
private static string CreateKeyword(in SerializedProperty p, in string propertyType, in string namePrefix = null)
{
var path = p.propertyPath;
if (path.IndexOf(' ') != -1)
path = p.name;
return $"#{(string.IsNullOrEmpty(namePrefix) ? "" : namePrefix)}{path.Replace(" ", "")}|{p.displayName}|{p.tooltip}|{propertyType}|{p.serializedObject?.targetObject?.GetType().AssemblyQualifiedName}";
}
internal static string GetPropertyManagedTypeString(in SerializedProperty p)
{
Type managedType;
switch (p.propertyType)
{
case SerializedPropertyType.Vector2:
case SerializedPropertyType.Vector3:
case SerializedPropertyType.Vector4:
case SerializedPropertyType.Boolean:
case SerializedPropertyType.String:
return p.propertyType.ToString();
case SerializedPropertyType.Integer:
managedType = p.GetManagedType();
if (managedType != null && !managedType.IsPrimitive)
return managedType.AssemblyQualifiedName;
return "Number";
case SerializedPropertyType.Character:
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.LayerMask:
case SerializedPropertyType.RenderingLayerMask:
case SerializedPropertyType.Float:
return "Number";
case SerializedPropertyType.Generic:
if (p.isArray)
return "Count";
return null;
case SerializedPropertyType.ObjectReference:
if (p.objectReferenceValue)
return p.objectReferenceValue.GetType().AssemblyQualifiedName;
if (p.type.StartsWith("PPtr<", StringComparison.Ordinal) && TryFindType<UnityEngine.Object>(p.type.Substring(5, p.type.Length - 6), out managedType))
return managedType.AssemblyQualifiedName;
managedType = p.GetManagedType();
if (managedType != null && !managedType.IsPrimitive)
return managedType.AssemblyQualifiedName;
return null;
}
if (p.isArray)
return "Count";
managedType = p.GetManagedType();
if (managedType != null && !managedType.IsPrimitive)
return managedType.AssemblyQualifiedName;
return p.propertyType.ToString();
}
internal static bool IsPropertyTypeSupported(SerializedProperty p)
{
var isAsset = !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(p.serializedObject.targetObject));
return IsPropertyTypeSupported(p, isAsset);
}
internal static bool IsPropertyTypeSupported(SerializedProperty p, bool isOwnerAsset)
{
var isSupported = isOwnerAsset ? ObjectIndexer.IsIndexableProperty(p.propertyType) : SearchValue.IsSearchableProperty(p.propertyType);
return isSupported && (p.propertyType == SerializedPropertyType.String || !p.isArray) && !p.isFixedBuffer && p.propertyPath.LastIndexOf('[') == -1;
}
internal static IEnumerable<UnityEngine.Object> GetTemplates(IEnumerable<UnityEngine.Object> objects)
{
var seenTypes = new HashSet<Type>();
foreach (var obj in objects)
{
if (!obj)
continue;
var ct = obj.GetType();
if (!seenTypes.Contains(ct))
{
seenTypes.Add(ct);
yield return obj;
}
if (obj is GameObject go)
{
foreach (var comp in go.GetComponents<Component>())
{
if (!comp)
continue;
ct = comp.GetType();
if (!seenTypes.Contains(ct))
{
seenTypes.Add(ct);
yield return comp;
}
}
}
var path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path))
{
var importer = AssetImporter.GetAtPath(path);
if (importer)
{
var it = importer.GetType();
if (it != typeof(AssetImporter) && !seenTypes.Contains(it))
{
seenTypes.Add(it);
yield return importer;
}
}
}
}
}
internal static string ParseSearchText(string searchText, IEnumerable<SearchProvider> providers, out SearchProvider filteredProvider)
{
filteredProvider = null;
var searchQuery = searchText.TrimStart();
if (string.IsNullOrEmpty(searchQuery))
return searchQuery;
foreach (var p in providers)
{
if (searchQuery.StartsWith(p.filterId, StringComparison.OrdinalIgnoreCase))
{
filteredProvider = p;
searchQuery = searchQuery.Remove(0, p.filterId.Length).TrimStart();
break;
}
}
return searchQuery;
}
static string ParseBlockContent(string type, in string content, out Type valueType)
{
var replacement = content;
var del = content.LastIndexOf(':');
if (del != -1)
replacement = content.Substring(0, del);
valueType = Type.GetType(type);
type = valueType?.Name ?? type;
if (QueryListBlockAttribute.TryGetReplacement(replacement.ToLower(), type, ref valueType, out var replacementText))
return replacementText;
switch (type)
{
case "Enum":
return $"{replacement}=0";
case "String":
return $"{replacement}:\"\"";
case "Boolean":
return $"{replacement}=true";
case "Array":
case "Count":
return $"{replacement}>=1";
case "Integer":
case "Float":
case "Number":
return $"{replacement}>0";
case "Color":
return $"{replacement}=#00ff00";
case "Vector2":
return $"{replacement}=(,)";
case "Vector3":
case "Quaternion":
return $"{replacement}=(,,)";
case "Vector4":
return $"{replacement}=(,,,)";
default:
if (valueType != null)
{
if (typeof(UnityEngine.Object).IsAssignableFrom(valueType))
return $"{replacement}=<$object:none,{valueType.FullName}$>";
if (valueType.IsEnum)
{
var enums = valueType.GetEnumValues();
if (enums.Length > 0)
return $"{replacement}=<$enum:{enums.GetValue(0)},{valueType.FullName}$>";
}
}
break;
}
return replacement;
}
internal static bool TryFindType<T>(in string typeString, out Type type)
{
type = FindType<T>(typeString);
return type != null;
}
static Dictionary<string, Type> s_CachedTypes = new Dictionary<string, Type>();
internal static Type FindType<T>(in string typeString)
{
if (s_CachedTypes.TryGetValue(typeString, out var foundType))
return foundType;
var selfType = typeof(T);
if (string.Equals(selfType.Name, typeString, StringComparison.OrdinalIgnoreCase) ||
string.Equals(selfType.FullName, typeString, StringComparison.Ordinal))
return s_CachedTypes[typeString] = selfType;
var type = Type.GetType(typeString);
if (type != null)
return s_CachedTypes[typeString] = type;
foreach (var t in TypeCache.GetTypesDerivedFrom<T>())
{
if (!t.IsVisible)
continue;
if (t.GetAttribute<ObsoleteAttribute>() != null)
continue;
if (string.Equals(t.Name, typeString, StringComparison.OrdinalIgnoreCase) ||
string.Equals(t.FullName, typeString, StringComparison.Ordinal))
{
return s_CachedTypes[typeString] = t;
}
}
return s_CachedTypes[typeString] = null;
}
internal static IEnumerable<Type> FindTypes<T>(string typeString)
{