forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUQuery.cs
More file actions
1242 lines (1070 loc) · 46.8 KB
/
Copy pathUQuery.cs
File metadata and controls
1242 lines (1070 loc) · 46.8 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;
using System.Collections.Generic;
using System.Threading;
using UnityEngine.UIElements.StyleSheets;
using UnityEngine.UIElements;
namespace UnityEngine.UIElements
{
internal struct RuleMatcher
{
public StyleSheet sheet;
public StyleComplexSelector complexSelector;
public RuleMatcher(StyleSheet sheet, StyleComplexSelector complexSelector, int styleSheetIndexInStack)
{
this.sheet = sheet;
this.complexSelector = complexSelector;
}
public override string ToString()
{
return complexSelector.ToString();
}
}
/// <summary>
/// UQuery is a set of extension methods allowing you to select individual or collection of visualElements inside a complex hierarchy.
/// </summary>
public static class UQuery
{
//This scheme saves us 20 bytes instead of saving a Func<object, bool> directly (12 vs 32 bytes)
internal interface IVisualPredicateWrapper
{
bool Predicate(object e);
}
internal class IsOfType<T> : IVisualPredicateWrapper where T : VisualElement
{
public static IsOfType<T> s_Instance = new IsOfType<T>();
public bool Predicate(object e)
{
return e is T;
}
}
internal class PredicateWrapper<T> : IVisualPredicateWrapper where T : VisualElement
{
private Func<T, bool> predicate;
public PredicateWrapper(Func<T, bool> p)
{
predicate = p;
}
public bool Predicate(object e)
{
T element = e as T;
if (element != null)
{
return predicate(element);
}
return false;
}
}
internal abstract class UQueryMatcher : HierarchyTraversal
{
internal List<RuleMatcher> m_Matchers;
protected UQueryMatcher()
{
}
public override void Traverse(VisualElement element)
{
base.Traverse(element);
}
protected virtual bool OnRuleMatchedElement(RuleMatcher matcher, VisualElement element)
{
return false;
}
static void NoProcessResult(VisualElement e, MatchResultInfo i) {}
public override void TraverseRecursive(VisualElement element, int depth)
{
int originalCount = m_Matchers.Count;
int count = m_Matchers.Count; // changes while we iterate so save
for (int j = 0; j < count; j++)
{
RuleMatcher matcher = m_Matchers[j];
if (StyleSelectorHelper.MatchRightToLeft(element, matcher.complexSelector, (e, i) => NoProcessResult(e, i)))
{
// use by uQuery to determine if we need to stop
if (OnRuleMatchedElement(matcher, element))
{
return;
}
}
}
Recurse(element, depth);
// Remove all matchers that we could possibly have added at this level of recursion
if (m_Matchers.Count > originalCount)
{
m_Matchers.RemoveRange(originalCount, m_Matchers.Count - originalCount);
}
}
public virtual void Run(VisualElement root, List<RuleMatcher> matchers)
{
m_Matchers = matchers;
Traverse(root);
}
}
internal abstract class SingleQueryMatcher : UQueryMatcher
{
public VisualElement match { get; set; }
public override void Run(VisualElement root, List<RuleMatcher> matchers)
{
match = null;
base.Run(root, matchers);
m_Matchers = null;
}
public bool IsInUse()
{
return m_Matchers != null;
}
public abstract SingleQueryMatcher CreateNew();
}
internal class FirstQueryMatcher : SingleQueryMatcher
{
public static readonly FirstQueryMatcher Instance = new FirstQueryMatcher();
protected override bool OnRuleMatchedElement(RuleMatcher matcher, VisualElement element)
{
if (match == null)
match = element;
return true;
}
public override SingleQueryMatcher CreateNew() => new FirstQueryMatcher();
}
internal class LastQueryMatcher : SingleQueryMatcher
{
public static readonly LastQueryMatcher Instance = new LastQueryMatcher();
protected override bool OnRuleMatchedElement(RuleMatcher matcher, VisualElement element)
{
match = element;
return false;
}
public override SingleQueryMatcher CreateNew() => new LastQueryMatcher();
}
internal class IndexQueryMatcher : SingleQueryMatcher
{
public static readonly IndexQueryMatcher Instance = new IndexQueryMatcher();
private int matchCount = -1;
private int _matchIndex;
public int matchIndex
{
get { return _matchIndex; }
set
{
matchCount = -1;
_matchIndex = value;
}
}
public override void Run(VisualElement root, List<RuleMatcher> matchers)
{
matchCount = -1;
base.Run(root, matchers);
}
protected override bool OnRuleMatchedElement(RuleMatcher matcher, VisualElement element)
{
++matchCount;
if (matchCount == _matchIndex)
{
match = element;
}
return matchCount >= _matchIndex;
}
public override SingleQueryMatcher CreateNew() => new IndexQueryMatcher();
}
}
/// <summary>
/// Query object containing all the selection rules. The object can be saved and rerun later without re-allocating memory.
/// </summary>
public struct UQueryState<T> : IEnumerable<T>, IEquatable<UQueryState<T>> where T : VisualElement
{
//this makes it non-thread safe. But saves on allocations...
private static ActionQueryMatcher s_Action = new ActionQueryMatcher();
private readonly VisualElement m_Element;
internal readonly List<RuleMatcher> m_Matchers;
internal UQueryState(VisualElement element, List<RuleMatcher> matchers)
{
m_Element = element;
m_Matchers = matchers;
}
/// <summary>
/// Creates a new QueryState with the same selection rules, applied on another VisualElement.
/// </summary>
/// <param name="element">The element on which to apply the selection rules.</param>
/// <returns>A new QueryState with the same selection rules, applied on this element.</returns>
public UQueryState<T> RebuildOn(VisualElement element)
{
return new UQueryState<T>(element, m_Matchers);
}
private T Single(UQuery.SingleQueryMatcher matcher)
{
if (matcher.IsInUse()) //Prevent reentrance issues
{
matcher = matcher.CreateNew();
}
matcher.Run(m_Element, m_Matchers);
var match = matcher.match as T;
// We need to make sure we don't leak a ref to the VisualElement.
matcher.match = null;
return match;
}
/// <summary>
/// The first element matching all the criteria, or null if none was found.
/// </summary>
/// <returns>The first element matching all the criteria, or null if none was found.</returns>
public T First() => Single(UQuery.FirstQueryMatcher.Instance);
/// <summary>
/// The last element matching all the criteria, or null if none was found.
/// </summary>
/// <returns>The last element matching all the criteria, or null if none was found.</returns>
public T Last() => Single(UQuery.LastQueryMatcher.Instance);
private class ListQueryMatcher<TElement> : UQuery.UQueryMatcher where TElement : VisualElement
{
public List<TElement> matches { get; set; }
protected override bool OnRuleMatchedElement(RuleMatcher matcher, VisualElement element)
{
matches.Add(element as TElement);
return false;
}
public void Reset()
{
matches = null;
}
}
private static readonly ListQueryMatcher<T> s_List = new ListQueryMatcher<T>();
/// <summary>
/// Adds all elements satisfying selection rules to the list.
/// </summary>
/// <param name="results">Adds all elements satisfying selection rules to the list.</param>
public void ToList(List<T> results)
{
s_List.matches = results;
s_List.Run(m_Element, m_Matchers);
s_List.Reset();
}
/// <summary>
/// Returns a list containing elements satisfying selection rules.
/// </summary>
/// <returns>A list containing elements satisfying selection rules.</returns>
public List<T> ToList()
{
List<T> result = new List<T>();
ToList(result);
return result;
}
/// <summary>
/// Selects the nth element matching all the criteria, or null if not enough elements were found.
/// </summary>
/// <param name="index">The index of the matched element.</param>
/// <returns>The match element at the specified index.</returns>
public T AtIndex(int index)
{
var indexMatcher = UQuery.IndexQueryMatcher.Instance;
indexMatcher.matchIndex = index;
return Single(indexMatcher);
}
//Convoluted trick so save on allocating memory for delegates or lambdas
private class ActionQueryMatcher : UQuery.UQueryMatcher
{
internal Action<T> callBack { get; set; }
protected override bool OnRuleMatchedElement(RuleMatcher matcher, VisualElement element)
{
if (element is T castedElement)
{
callBack(castedElement);
}
return false;
}
}
/// <summary>
/// Invokes function on all elements matching the query.
/// </summary>
/// <param name="funcCall">The action to be invoked with each matching element.</param>
public void ForEach(Action<T> funcCall)
{
var act = s_Action;
if (act.callBack != null)
{
//we're inside a ForEach callback already. we need to allocate :(
act = new ActionQueryMatcher();
}
try
{
act.callBack = funcCall;
act.Run(m_Element, m_Matchers);
}
finally
{
act.callBack = null;
}
}
private class DelegateQueryMatcher<TReturnType> : UQuery.UQueryMatcher
{
public Func<T, TReturnType> callBack { get; set; }
public List<TReturnType> result { get; set; }
public static DelegateQueryMatcher<TReturnType> s_Instance = new DelegateQueryMatcher<TReturnType>();
protected override bool OnRuleMatchedElement(RuleMatcher matcher, VisualElement element)
{
if (element is T castedElement)
{
result.Add(callBack(castedElement));
}
return false;
}
}
/// <summary>
/// Invokes function on all elements matching the query.
/// </summary>
/// <param name="result">Each return value will be added to this list.</param>
/// <param name="funcCall">The function to be invoked with each matching element.</param>
public void ForEach<T2>(List<T2> result, Func<T, T2> funcCall)
{
var matcher = DelegateQueryMatcher<T2>.s_Instance;
if (matcher.callBack != null)
{
//we're inside a call to ForEach already!, we need to allocate :(
matcher = new DelegateQueryMatcher<T2>();
}
try
{
matcher.callBack = funcCall;
matcher.result = result;
matcher.Run(m_Element, m_Matchers);
}
finally
{
matcher.callBack = null;
matcher.result = null;
}
}
/// <summary>
/// Invokes function on all elements matching the query.
/// </summary>
/// <param name="funcCall">The action to be invoked with each matching element.</param>
public List<T2> ForEach<T2>(Func<T, T2> funcCall)
{
List<T2> result = new List<T2>();
ForEach(result, funcCall);
return result;
}
/// <summary>
/// Allows traversing the results of the query with `foreach` without creating GC allocations.
/// </summary>
/// <returns>A <see cref="UQueryState{T}.Enumerator"/> instance configured to traverse the results.</returns>
public Enumerator GetEnumerator() => new Enumerator(this);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private static readonly ListQueryMatcher<VisualElement> s_EnumerationList = new ListQueryMatcher<VisualElement>();
/// <undoc/>
public struct Enumerator : IEnumerator<T>
{
private List<VisualElement> iterationList;
private int currentIndex;
internal Enumerator(UQueryState<T> queryState)
{
iterationList = VisualElementListPool.Get();
s_EnumerationList.matches = iterationList;
s_EnumerationList.Run(queryState.m_Element, queryState.m_Matchers);
s_EnumerationList.Reset();
currentIndex = -1;
}
/// <undoc/>
public T Current => (T)iterationList[currentIndex];
/// <undoc/>
object IEnumerator.Current => Current;
/// <undoc/>
public bool MoveNext()
{
return (++currentIndex < iterationList.Count); // increment current position and check if reached end of buffer
}
/// <undoc/>
public void Reset()
{
currentIndex = -1;
}
/// <undoc/>
public void Dispose()
{
VisualElementListPool.Release(iterationList);
iterationList = null;
}
}
/// <undoc/>
public bool Equals(UQueryState<T> other)
{
return ReferenceEquals(m_Element, other.m_Element) &&
EqualityComparer<List<RuleMatcher>>.Default.Equals(m_Matchers, other.m_Matchers);
}
/// <undoc/>
public override bool Equals(object obj)
{
if (!(obj is UQueryState<T>))
{
return false;
}
return Equals((UQueryState<T>)obj);
}
public override int GetHashCode()
{
var hashCode = 488160421;
hashCode = hashCode * -1521134295 + EqualityComparer<VisualElement>.Default.GetHashCode(m_Element);
hashCode = hashCode * -1521134295 + EqualityComparer<List<RuleMatcher>>.Default.GetHashCode(m_Matchers);
return hashCode;
}
/// <undoc/>
public static bool operator==(UQueryState<T> state1, UQueryState<T> state2)
{
return state1.Equals(state2);
}
/// <undoc/>
public static bool operator!=(UQueryState<T> state1, UQueryState<T> state2)
{
return !(state1 == state2);
}
}
/// <summary>
/// Utility Object that contructs a set of selection rules to be ran on a root visual element.
/// </summary>
public struct UQueryBuilder<T> : IEquatable<UQueryBuilder<T>> where T : VisualElement
{
private List<StyleSelector> m_StyleSelectors;
private List<StyleSelector> styleSelectors { get { return m_StyleSelectors ?? (m_StyleSelectors = new List<StyleSelector>()); } }
private List<StyleSelectorPart> m_Parts;
private List<StyleSelectorPart> parts { get { return m_Parts ?? (m_Parts = new List<StyleSelectorPart>()); } }
private VisualElement m_Element;
private List<RuleMatcher> m_Matchers;
private StyleSelectorRelationship m_Relationship;
private int pseudoStatesMask;
private int negatedPseudoStatesMask;
/// <summary>
/// Initializes a QueryBuilder.
/// </summary>
/// <param name="visualElement">The root element on which to condfuct the search query.</param>
public UQueryBuilder(VisualElement visualElement)
: this()
{
m_Element = visualElement;
m_Parts = null;
m_StyleSelectors = null;
m_Relationship = StyleSelectorRelationship.None;
m_Matchers = new List<RuleMatcher>();
pseudoStatesMask = negatedPseudoStatesMask = 0;
}
/// <summary>
/// Selects all elements with the specified class in the class list, as specified with the `class` attribute in a UXML file or added with <see cref="VisualElement.AddToClassList(string)"/> method.
/// </summary>
/// <param name="classname">The class to use in the query.</param>
/// <remarks>
/// This method can be called multiple times in order to select elements with multiple classes.
/// To select elements by their C# type, use <see cref="OfType{T2}(string,string[])"/>.
/// </remarks>
public UQueryBuilder<T> Class(string classname)
{
AddClass(classname);
return this;
}
/// <summary>
/// Selects element with this name.
/// </summary>
public UQueryBuilder<T> Name(string id)
{
AddName(id);
return this;
}
/// <summary>
/// Selects all elements that are descendants of currently matching ancestors.
/// </summary>
public UQueryBuilder<T2> Descendents<T2>(string name = null, params string[] classNames) where T2 : VisualElement
{
FinishCurrentSelector();
AddType<T2>();
AddName(name);
AddClasses(classNames);
return AddRelationship<T2>(StyleSelectorRelationship.Descendent);
}
/// <summary>
/// Selects all elements that are descendants of currently matching ancestors.
/// </summary>
public UQueryBuilder<T2> Descendents<T2>(string name = null, string classname = null) where T2 : VisualElement
{
FinishCurrentSelector();
AddType<T2>();
AddName(name);
AddClass(classname);
return AddRelationship<T2>(StyleSelectorRelationship.Descendent);
}
/// <summary>
/// Selects all direct child elements of elements matching the previous rules.
/// </summary>
public UQueryBuilder<T2> Children<T2>(string name = null, params string[] classes) where T2 : VisualElement
{
FinishCurrentSelector();
AddType<T2>();
AddName(name);
AddClasses(classes);
return AddRelationship<T2>(StyleSelectorRelationship.Child);
}
/// <summary>
/// Selects all direct child elements of elements matching the previous rules.
/// </summary>
public UQueryBuilder<T2> Children<T2>(string name = null, string className = null) where T2 : VisualElement
{
FinishCurrentSelector();
AddType<T2>();
AddName(name);
AddClass(className);
return AddRelationship<T2>(StyleSelectorRelationship.Child);
}
/// <summary>
/// Selects all elements of the specified Type (eg: Label, Button, ScrollView, etc).
/// </summary>
/// <param name="name">If specified, will select elements with this name.</param>
/// <param name="classes">If specified, will select elements with the given class (not to be confused with Type).</param>
/// <returns>QueryBuilder configured with the associated selection rules.</returns>
public UQueryBuilder<T2> OfType<T2>(string name = null, params string[] classes) where T2 : VisualElement
{
AddType<T2>();
AddName(name);
AddClasses(classes);
return AddRelationship<T2>(StyleSelectorRelationship.None);
}
/// <summary>
/// Selects all elements of the specified Type (eg: Label, Button, ScrollView, etc).
/// </summary>
/// <param name="name">If specified, will select elements with this name.</param>
/// <param name="className">If specified, will select elements with the given class (not to be confused with Type).</param>
/// <returns>QueryBuilder configured with the associated selection rules.</returns>
public UQueryBuilder<T2> OfType<T2>(string name = null, string className = null) where T2 : VisualElement
{
AddType<T2>();
AddName(name);
AddClass(className);
return AddRelationship<T2>(StyleSelectorRelationship.None);
}
//Only used to avoid allocations in Q<>() Don't use this unless you know what you're doing
internal UQueryBuilder<T> SingleBaseType()
{
parts.Add(StyleSelectorPart.CreatePredicate(UQuery.IsOfType<T>.s_Instance));
return this;
}
/// <summary>
/// Selects all elements satifying the predicate.
/// </summary>
/// <param name="selectorPredicate">Predicate that must return true for selected elements.</param>
/// <returns>QueryBuilder configured with the associated selection rules.</returns>
public UQueryBuilder<T> Where(Func<T, bool> selectorPredicate)
{
//we can't use a static instance as in the QueryState<T>.ForEach below since the query might be long lived
parts.Add(StyleSelectorPart.CreatePredicate(new UQuery.PredicateWrapper<T>(selectorPredicate)));
return this;
}
private void AddClass(string c)
{
if (c != null)
parts.Add(StyleSelectorPart.CreateClass(c));
}
private void AddClasses(params string[] classes)
{
if (classes != null)
{
for (int i = 0; i < classes.Length; i++)
AddClass(classes[i]);
}
}
private void AddName(string id)
{
if (id != null)
parts.Add(StyleSelectorPart.CreateId(id));
}
private void AddType<T2>() where T2 : VisualElement
{
if (typeof(T2) != typeof(VisualElement))
parts.Add(StyleSelectorPart.CreatePredicate(UQuery.IsOfType<T2>.s_Instance));
}
private UQueryBuilder<T> AddPseudoState(PseudoStates s)
{
pseudoStatesMask = pseudoStatesMask | (int)s;
return this;
}
private UQueryBuilder<T> AddNegativePseudoState(PseudoStates s)
{
negatedPseudoStatesMask = negatedPseudoStatesMask | (int)s;
return this;
}
/// <summary>
/// Selects all elements that are active.
/// </summary>
/// <returns>A QueryBuilder with the selection rules.</returns>
public UQueryBuilder<T> Active()
{
return AddPseudoState(PseudoStates.Active);
}
/// <summary>
/// Selects all elements that are not active.
/// </summary>
public UQueryBuilder<T> NotActive()
{
return AddNegativePseudoState(PseudoStates.Active);
}
/// <summary>
/// Selects all elements that are not visible.
/// </summary>
public UQueryBuilder<T> Visible()
{
return Where(e => e.visible);
}
/// <summary>
/// Selects all elements that are not visible.
/// </summary>
public UQueryBuilder<T> NotVisible()
{
return Where(e => !e.visible);
}
/// <summary>
/// Selects all elements that are hovered.
/// </summary>
public UQueryBuilder<T> Hovered()
{
return AddPseudoState(PseudoStates.Hover);
}
/// <summary>
/// Selects all elements that are not hovered.
/// </summary>
public UQueryBuilder<T> NotHovered()
{
return AddNegativePseudoState(PseudoStates.Hover);
}
/// <summary>
/// Selects all elements that are checked.
/// </summary>
public UQueryBuilder<T> Checked()
{
return AddPseudoState(PseudoStates.Checked);
}
/// <summary>
/// Selects all elements that npot checked.
/// </summary>
public UQueryBuilder<T> NotChecked()
{
return AddNegativePseudoState(PseudoStates.Checked);
}
/// <summary>
/// Selects all elements that are not selected.
/// </summary>
[Obsolete("Use Checked() instead")]
public UQueryBuilder<T> Selected()
{
return AddPseudoState(PseudoStates.Checked);
}
/// <summary>
/// Selects all elements that are not selected.
/// </summary>
[Obsolete("Use NotChecked() instead")]
public UQueryBuilder<T> NotSelected()
{
return AddNegativePseudoState(PseudoStates.Checked);
}
/// <summary>
/// Selects all elements that are enabled.
/// </summary>
public UQueryBuilder<T> Enabled()
{
return AddNegativePseudoState(PseudoStates.Disabled);
}
/// <summary>
/// Selects all elements that are not enabled.
/// </summary>
public UQueryBuilder<T> NotEnabled()
{
return AddPseudoState(PseudoStates.Disabled);
}
/// <summary>
/// Selects all elements that are enabled.
/// </summary>
public UQueryBuilder<T> Focused()
{
return AddPseudoState(PseudoStates.Focus);
}
/// <summary>
/// Selects all elements that don't currently own the focus.
/// </summary>
public UQueryBuilder<T> NotFocused()
{
return AddNegativePseudoState(PseudoStates.Focus);
}
private UQueryBuilder<T2> AddRelationship<T2>(StyleSelectorRelationship relationship) where T2 : VisualElement
{
return new UQueryBuilder<T2>(m_Element)
{
m_Matchers = m_Matchers,
m_Parts = m_Parts,
m_StyleSelectors = m_StyleSelectors,
m_Relationship = relationship == StyleSelectorRelationship.None ? m_Relationship : relationship,
pseudoStatesMask = pseudoStatesMask,
negatedPseudoStatesMask = negatedPseudoStatesMask
};
}
void AddPseudoStatesRuleIfNecessasy()
{
if (pseudoStatesMask != 0 ||
negatedPseudoStatesMask != 0)
{
parts.Add(new StyleSelectorPart() {type = StyleSelectorType.PseudoClass});
}
}
private void FinishSelector()
{
FinishCurrentSelector();
if (styleSelectors.Count > 0)
{
var selector = new StyleComplexSelector();
selector.selectors = styleSelectors.ToArray();
styleSelectors.Clear();
m_Matchers.Add(new RuleMatcher { complexSelector = selector });
}
}
private bool CurrentSelectorEmpty()
{
return parts.Count == 0 &&
m_Relationship == StyleSelectorRelationship.None &&
pseudoStatesMask == 0 &&
negatedPseudoStatesMask == 0;
}
private void FinishCurrentSelector()
{
if (!CurrentSelectorEmpty())
{
StyleSelector sel = new StyleSelector();
sel.previousRelationship = m_Relationship;
AddPseudoStatesRuleIfNecessasy();
sel.parts = m_Parts.ToArray();
sel.pseudoStateMask = pseudoStatesMask;
sel.negatedPseudoStateMask = negatedPseudoStatesMask;
styleSelectors.Add(sel);
m_Parts.Clear();
pseudoStatesMask = negatedPseudoStatesMask = 0;
}
}
/// <summary>
/// Compiles the selection rules into a QueryState object.
/// </summary>
public UQueryState<T> Build()
{
FinishSelector();
if (m_Matchers.Count == 0)
{
// an empty query should match everything
parts.Add(new StyleSelectorPart() {type = StyleSelectorType.Wildcard});
FinishSelector();
}
return new UQueryState<T>(m_Element, m_Matchers);
}
// Quick One-liners accessors
/// <undoc/>
public static implicit operator T(UQueryBuilder<T> s)
{
return s.First();
}
/// <undoc/>
public static bool operator==(UQueryBuilder<T> builder1, UQueryBuilder<T> builder2)
{
return builder1.Equals(builder2);
}
/// <undoc/>
public static bool operator!=(UQueryBuilder<T> builder1, UQueryBuilder<T> builder2)
{
return !(builder1 == builder2);
}
/// <summary>
/// Convenience overload, shorthand for Build().First().
/// </summary>
/// <returns>The first element matching all the criteria, or null if none was found.</returns>
/// <seealso cref="UQueryState{T}.First"/>
public T First()
{
return Build().First();
}
/// <summary>
/// Convenience overload, shorthand for Build().Last().
/// </summary>
/// <returns>The last element matching all the criteria, or null if none was found.</returns>
public T Last()
{
return Build().Last();
}
/// <summary>
/// Convenience method. shorthand for Build().ToList.
/// </summary>
/// <returns>A list containing elements satisfying selection rules.</returns>
public List<T> ToList()
{
return Build().ToList();
}
/// <summary>
/// Convenience method. Shorthand gor Build().ToList().
/// </summary>
/// <param name="results">Adds all elements satisfying selection rules to the list.</param>
public void ToList(List<T> results)
{
Build().ToList(results);
}
/// <summary>
/// Convenience overload, shorthand for Build().AtIndex().
/// </summary>
/// <seealso cref="UQueryState{T}.AtIndex"/>
public T AtIndex(int index)
{
return Build().AtIndex(index);
}
/// <summary>
/// Convenience overload, shorthand for Build().ForEach().
/// </summary>
/// <param name="result">Each return value will be added to this list.</param>
/// <param name="funcCall">The function to be invoked with each matching element.</param>
public void ForEach<T2>(List<T2> result, Func<T, T2> funcCall)
{
Build().ForEach(result, funcCall);
}
/// <summary>
/// Convenience overload, shorthand for Build().ForEach().
/// </summary>
/// <param name="funcCall">The function to be invoked with each matching element.</param>
public List<T2> ForEach<T2>(Func<T, T2> funcCall)
{
return Build().ForEach(funcCall);
}
/// <summary>
/// Convenience overload, shorthand for Build().ForEach().
/// </summary>
/// <param name="funcCall">The function to be invoked with each matching element.</param>
public void ForEach(Action<T> funcCall)
{
Build().ForEach(funcCall);
}
/// <undoc/>
public bool Equals(UQueryBuilder<T> other)
{
return EqualityComparer<List<StyleSelector>>.Default.Equals(m_StyleSelectors, other.m_StyleSelectors) &&
EqualityComparer<List<StyleSelector>>.Default.Equals(styleSelectors, other.styleSelectors) &&
EqualityComparer<List<StyleSelectorPart>>.Default.Equals(m_Parts, other.m_Parts) &&
EqualityComparer<List<StyleSelectorPart>>.Default.Equals(parts, other.parts) && ReferenceEquals(m_Element, other.m_Element) &&
EqualityComparer<List<RuleMatcher>>.Default.Equals(m_Matchers, other.m_Matchers) &&
m_Relationship == other.m_Relationship &&
pseudoStatesMask == other.pseudoStatesMask &&
negatedPseudoStatesMask == other.negatedPseudoStatesMask;
}
/// <undoc/>
public override bool Equals(object obj)
{
if (!(obj is UQueryBuilder<T>))
{
return false;
}
return Equals((UQueryBuilder<T>)obj);