forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisualElement.cs
More file actions
1408 lines (1205 loc) · 49.2 KB
/
Copy pathVisualElement.cs
File metadata and controls
1408 lines (1205 loc) · 49.2 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
//#define ENABLE_CAPTURE_DEBUG
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine.Yoga;
using UnityEngine.Experimental.UIElements.StyleEnums;
using UnityEngine.Experimental.UIElements.StyleSheets;
namespace UnityEngine.Experimental.UIElements
{
internal delegate void OnStylesResolved(ICustomStyle styles);
// pseudo states are used for common states of a widget
// they are addressable from CSS via the pseudo state syntax ":selected" for example
// while css class list can solve the same problem, pseudo states are a fast commonly agreed upon path for common cases.
[Flags]
internal enum PseudoStates
{
Active = 1 << 0, // control is currently pressed in the case of a button
Hover = 1 << 1, // mouse is over control, set and removed from dispatcher automatically
Checked = 1 << 3, // usually associated with toggles of some kind to change visible style
Selected = 1 << 4, // selected, used to denote the current selected state and associate a visual style from CSS
Disabled = 1 << 5, // control will not respond to user input
Focus = 1 << 6, // control has the keyboard focus. This is activated deactivated by the dispatcher automatically
}
public enum PickingMode
{
Position, // todo better name
Ignore
}
internal class VisualElementListPool
{
static ObjectPool<List<VisualElement>> pool = new ObjectPool<List<VisualElement>>(20);
public static List<VisualElement> Copy(List<VisualElement> elements)
{
var result = pool.Get();
result.AddRange(elements);
return result;
}
public static List<VisualElement> Get(int initialCapacity = 0)
{
List<VisualElement> result = pool.Get();
if (initialCapacity > 0 && result.Capacity < initialCapacity)
{
result.Capacity = initialCapacity;
}
return result;
}
public static void Release(List<VisualElement> elements)
{
elements.Clear();
pool.Release(elements);
}
}
public partial class VisualElement : Focusable, ITransform
{
public class VisualElementFactory : UxmlFactory<VisualElement, VisualElementUxmlTraits> {}
public class VisualElementUxmlTraits : UxmlTraits
{
UxmlStringAttributeDescription m_Name;
UxmlEnumAttributeDescription<PickingMode> m_PickingMode;
protected UxmlIntAttributeDescription m_FocusIndex;
public VisualElementUxmlTraits()
{
m_Name = new UxmlStringAttributeDescription { name = "name" };
m_PickingMode = new UxmlEnumAttributeDescription<PickingMode> { name = "pickingMode" };
m_FocusIndex = new UxmlIntAttributeDescription { name = "focusIndex", defaultValue = VisualElement.defaultFocusIndex };
}
public override IEnumerable<UxmlAttributeDescription> uxmlAttributesDescription
{
get
{
foreach (var attr in base.uxmlAttributesDescription)
{
yield return attr;
}
yield return m_Name;
yield return m_PickingMode;
yield return m_FocusIndex;
}
}
public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
{
get { yield return new UxmlChildElementDescription(typeof(VisualElement)); }
}
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
ve.name = m_Name.GetValueFromBag(bag);
ve.pickingMode = m_PickingMode.GetValueFromBag(bag);
ve.focusIndex = m_FocusIndex.GetValueFromBag(bag);
}
}
public static readonly int defaultFocusIndex = -1;
private static uint s_NextId;
string m_Name;
HashSet<string> m_ClassList;
string m_TypeName;
string m_FullTypeName;
// Used for view data persistence, like expanded states.
private string m_PersistenceKey;
public string persistenceKey
{
get { return m_PersistenceKey; }
set
{
if (m_PersistenceKey != value)
{
m_PersistenceKey = value;
if (!string.IsNullOrEmpty(value))
Dirty(ChangeType.PersistentData);
}
}
}
// It seems worse to have unwanted/unpredictable persistence
// than to expect it and not have it. This internal check, set
// by Panel.ValidatePersistentDataOnSubTree() controls whether
// persistency is enabled or not. Persistence will be disabled
// on any VisualElement that does not have a persistenceKey, but
// it will also be disabled if any of its parents does not have
// a persistenceKey.
internal bool enablePersistence { get; private set; }
public object userData { get; set; }
public override bool canGrabFocus { get { return visible && enabledInHierarchy && base.canGrabFocus; } }
public override FocusController focusController
{
get { return panel == null ? null : panel.focusController; }
}
private RenderData m_RenderData;
internal RenderData renderData
{
get { return m_RenderData ?? (m_RenderData = new RenderData()); }
}
Vector3 m_Position = Vector3.zero;
Quaternion m_Rotation = Quaternion.identity;
Vector3 m_Scale = Vector3.one;
public ITransform transform
{
get { return this; }
}
Vector3 ITransform.position
{
get
{
return m_Position;
}
set
{
if (m_Position == value)
return;
m_Position = value;
Dirty(ChangeType.Transform);
}
}
Quaternion ITransform.rotation
{
get
{
return m_Rotation;
}
set
{
if (m_Rotation == value)
return;
m_Rotation = value;
Dirty(ChangeType.Transform);
}
}
Vector3 ITransform.scale
{
get
{
return m_Scale;
}
set
{
if (m_Scale == value)
return;
m_Scale = value;
Dirty(ChangeType.Transform);
}
}
Matrix4x4 ITransform.matrix
{
get { return Matrix4x4.TRS(m_Position, m_Rotation, m_Scale); }
}
Rect m_Layout;
// This will replace the Rect position
// origin and size relative to parent
public Rect layout
{
get
{
var result = m_Layout;
if (yogaNode != null && style.positionType.value != PositionType.Manual)
{
result.x = yogaNode.LayoutX;
result.y = yogaNode.LayoutY;
result.width = yogaNode.LayoutWidth;
result.height = yogaNode.LayoutHeight;
}
return result;
}
set
{
if (yogaNode == null)
{
yogaNode = new YogaNode();
}
// Same position value while type is already manual should not trigger any layout change, return early
if (style.positionType.value == PositionType.Manual && m_Layout == value)
return;
// set results so we can read straight back in get without waiting for a pass
m_Layout = value;
// mark as inline so that they do not get overridden if needed.
IStyle styleAccess = this;
styleAccess.positionType = PositionType.Manual;
styleAccess.marginLeft = 0.0f;
styleAccess.marginRight = 0.0f;
styleAccess.marginBottom = 0.0f;
styleAccess.marginTop = 0.0f;
styleAccess.positionLeft = value.x;
styleAccess.positionTop = value.y;
styleAccess.positionRight = float.NaN;
styleAccess.positionBottom = float.NaN;
styleAccess.width = value.width;
styleAccess.height = value.height;
Dirty(ChangeType.Transform);
}
}
public Rect contentRect
{
get
{
var spacing = new Spacing(m_Style.paddingLeft,
m_Style.paddingTop,
m_Style.paddingRight,
m_Style.paddingBottom);
return paddingRect - spacing;
}
}
protected Rect paddingRect
{
get
{
var spacing = new Spacing(style.borderLeftWidth,
style.borderTopWidth,
style.borderRightWidth,
style.borderBottomWidth);
return rect - spacing;
}
}
/// <summary>
/// AABB after applying the world transform to <c>rect</c>.
/// </summary>
public Rect worldBound
{
get
{
var g = worldTransform;
var min = GUIUtility.Internal_MultiplyPoint(new Vector3(rect.min.x, rect.min.y, 1), g);
var max = GUIUtility.Internal_MultiplyPoint(new Vector3(rect.max.x, rect.max.y, 1), g);
// We assume that the transform performs translation/scaling without rotation.
return Rect.MinMaxRect(Math.Min(min.x, max.x), Math.Min(min.y, max.y), Math.Max(min.x, max.x), Math.Max(min.y, max.y));
}
}
/// <summary>
/// AABB after applying the transform to the rect, but before applying the layout translation.
/// </summary>
public Rect localBound
{
get
{
var g = transform.matrix;
var min = GUIUtility.Internal_MultiplyPoint(layout.min, g);
var max = GUIUtility.Internal_MultiplyPoint(layout.max, g);
// We assume that the transform performs translation/scaling without rotation.
return Rect.MinMaxRect(Math.Min(min.x, max.x), Math.Min(min.y, max.y), Math.Max(min.x, max.x), Math.Max(min.y, max.y));
}
}
internal Rect rect
{
get
{
return new Rect(0.0f, 0.0f, layout.width, layout.height);
}
}
internal bool isWorldTransformDirty { get; set; } = true;
/// <summary>
/// Returns a matrix that cumulates the following operations (in order):
/// -Local Scaling
/// -Local Rotation
/// -Local Translation
/// -Layout Translation
/// -Parent <c>worldTransform</c> (recursive definition - consider identity when there is no parent)
/// </summary>
/// <remarks>
/// Multiplying the <c>layout</c> rect by this matrix is incorrect because it already contains the translation.
/// </remarks>
public Matrix4x4 worldTransform
{
get
{
if (IsDirty(ChangeType.Transform))
{
var offset = Matrix4x4.Translate(new Vector3(layout.x, layout.y, 0));
if (shadow.parent != null)
{
renderData.worldTransForm = shadow.parent.worldTransform * offset * transform.matrix;
}
else
{
renderData.worldTransForm = offset * transform.matrix;
}
ClearDirty(ChangeType.Transform);
}
return renderData.worldTransForm;
}
}
// which pseudo states would change the current VE styles if added
internal PseudoStates triggerPseudoMask;
// which pseudo states would change the current VE styles if removed
internal PseudoStates dependencyPseudoMask;
private PseudoStates m_PseudoStates;
internal PseudoStates pseudoStates
{
get { return m_PseudoStates; }
set
{
if (m_PseudoStates != value)
{
m_PseudoStates = value;
if ((triggerPseudoMask & m_PseudoStates) != 0
|| (dependencyPseudoMask & ~m_PseudoStates) != 0)
{
Dirty(ChangeType.Styles);
}
}
}
}
public PickingMode pickingMode { get; set; }
// does not guarantee uniqueness
public string name
{
get { return m_Name; }
set
{
if (m_Name == value)
return;
m_Name = value;
Dirty(ChangeType.Styles);
}
}
internal string fullTypeName
{
get
{
if (string.IsNullOrEmpty(m_FullTypeName))
m_FullTypeName = GetType().FullName;
return m_FullTypeName;
}
}
internal string typeName
{
get
{
if (string.IsNullOrEmpty(m_TypeName))
{
var type = GetType();
bool isGeneric = false;
isGeneric = type.IsGenericType;
m_TypeName = isGeneric ? type.Name.Remove(type.Name.IndexOf('`')) : type.Name;
}
return m_TypeName;
}
}
// Set and pass in values to be used for layout
internal YogaNode yogaNode { get; private set; }
// shared style object, cannot be changed by the user
internal VisualElementStylesData m_SharedStyle = VisualElementStylesData.none;
// user-defined style object, if not set, is the same reference as m_SharedStyles
internal VisualElementStylesData m_Style = VisualElementStylesData.none;
protected virtual void OnStyleResolved(ICustomStyle style)
{
// push all non inlined layout things up
FinalizeLayout();
}
internal VisualElementStylesData sharedStyle
{
get
{
return m_SharedStyle;
}
}
internal VisualElementStylesData effectiveStyle
{
get
{
return m_Style;
}
}
internal bool hasInlineStyle
{
get
{
return m_Style != m_SharedStyle;
}
}
VisualElementStylesData inlineStyle
{
get
{
if (!hasInlineStyle)
{
var inline = new VisualElementStylesData(false);
inline.Apply(m_SharedStyle, StylePropertyApplyMode.Copy);
m_Style = inline;
}
return m_Style;
}
}
// Opacity is not fully supported so it's hidden from public API for now
internal float opacity
{
get
{
return style.opacity.value;
}
set
{
style.opacity = value;
}
}
internal readonly uint controlid;
public VisualElement()
{
controlid = ++s_NextId;
shadow = new Hierarchy(this);
m_ClassList = new HashSet<string>();
m_FullTypeName = string.Empty;
m_TypeName = string.Empty;
SetEnabled(true);
// Make element non focusable by default.
focusIndex = defaultFocusIndex;
name = string.Empty;
yogaNode = new YogaNode();
changesNeeded = ChangeType.All;
clippingOptions = ClippingOptions.ClipContents;
}
protected internal override void ExecuteDefaultAction(EventBase evt)
{
base.ExecuteDefaultAction(evt);
if (evt.GetEventTypeId() == MouseOverEvent.TypeId() || evt.GetEventTypeId() == MouseOutEvent.TypeId())
{
UpdateCursorStyle(evt.GetEventTypeId());
}
else if (evt.GetEventTypeId() == MouseEnterEvent.TypeId())
{
pseudoStates |= PseudoStates.Hover;
}
else if (evt.GetEventTypeId() == MouseLeaveEvent.TypeId())
{
pseudoStates &= ~PseudoStates.Hover;
}
else if (evt.GetEventTypeId() == BlurEvent.TypeId())
{
pseudoStates = pseudoStates & ~PseudoStates.Focus;
}
else if (evt.GetEventTypeId() == FocusEvent.TypeId())
{
pseudoStates = pseudoStates | PseudoStates.Focus;
}
}
public sealed override void Focus()
{
if (!canGrabFocus && shadow.parent != null)
{
shadow.parent.Focus();
}
else
{
base.Focus();
}
}
internal void SetPanel(BaseVisualElementPanel p)
{
if (panel == p)
return;
//We now gather all Elements in order to dispatch events in an efficient manner
List<VisualElement> elements = VisualElementListPool.Get();
try
{
elements.Add(this);
GatherAllChildren(elements);
foreach (var e in elements)
{
e.ChangePanel(p);
}
}
finally
{
VisualElementListPool.Release(elements);
}
}
// This should never be called directly
// This needs to be virtual for GraphView.cs
// We could avoid this by having a single PanelChangeEvent
// containing both the previous and the new panel values.
internal virtual void ChangePanel(BaseVisualElementPanel p)
{
if (panel != null)
{
using (var e = DetachFromPanelEvent.GetPooled())
{
e.target = this;
UIElementsUtility.eventDispatcher.DispatchEvent(e, panel);
}
}
elementPanel = p;
if (panel != null)
{
using (var e = AttachToPanelEvent.GetPooled())
{
e.target = this;
UIElementsUtility.eventDispatcher.DispatchEvent(e, panel);
}
}
Dirty(ChangeType.Styles);
}
// in the case of a Topology change the target is the parent of the removed or added element
// TODO write test suite for this method. in particular, any change type should implicitly
private ChangeType changesNeeded;
// helper when change impact are known and we need to propagate down into children
private void PropagateToChildren(ChangeType type)
{
// when touching we grass fire in the tree but stop when we are already touched.
// this is a key point of the on demand dirty that keeps it from exploding.
if ((type & changesNeeded) == type)
return;
changesNeeded |= type;
// only those propagate to children
type = type & (ChangeType.Styles | ChangeType.Transform);
if (type == 0)
return;
// propagate to children
if (m_Children != null)
{
foreach (var child in m_Children)
{
// recurse down
child.PropagateToChildren(type);
}
}
}
private void PropagateChangesToParents()
{
ChangeType parentChanges = 0;
if (changesNeeded != 0)
{
// if we have any change at all, propagate the repaint flag
// this is somehow an implementation detail but this is the only flag that is checked in the app tick
// this means that styles, layout, transform, etc. will be processed just before painting a panel
// a small downside is that we might repaint more often that necessary
// another solution would be to process all flags sequentially in the tick to check if a repaint is needed
parentChanges |= ChangeType.Repaint;
if ((changesNeeded & ChangeType.Styles) > 0)
{
// if this visual element needs its styles recomputed, propagate this specific flags for its parents
// it is less expensive than a full styles re-pass
parentChanges |= ChangeType.StylesPath;
}
if ((changesNeeded & (ChangeType.PersistentData | ChangeType.PersistentDataPath)) > 0)
{
// Parents do not need their OnPersistentDataReady() called but they need to call still
// propagate it to their children so it gets back to us.
parentChanges |= ChangeType.PersistentDataPath;
}
}
var current = shadow.parent;
while (current != null)
{
if ((current.changesNeeded & parentChanges) == parentChanges)
break;
current.changesNeeded |= parentChanges;
current = current.shadow.parent;
}
}
public void Dirty(ChangeType type)
{
// when touching we grass fire in the tree but stop when we are already touched.
// this is a key point of the on demand dirty that keeps it from exploding.
if ((type & changesNeeded) == type)
return;
if ((type & ChangeType.Layout) == ChangeType.Layout)
{
if (yogaNode != null && yogaNode.IsMeasureDefined)
{
yogaNode.MarkDirty();
}
type |= ChangeType.Repaint;
}
if (((type & ChangeType.Transform) == ChangeType.Transform) && (elementPanel != null))
{
elementPanel.hasDirtyTransform = true;
}
PropagateToChildren(type);
PropagateChangesToParents();
}
internal bool AnyDirty()
{
return changesNeeded != 0;
}
public bool IsDirty(ChangeType type)
{
return (changesNeeded & type) == type;
}
public bool AnyDirty(ChangeType type)
{
return (changesNeeded & type) > 0;
}
public void ClearDirty(ChangeType type)
{
changesNeeded &= ~type;
}
[Obsolete("enabled is deprecated. Use SetEnabled as setter, and enabledSelf/enabledInHierarchy as getters.", true)]
public virtual bool enabled
{
get { return enabledInHierarchy; }
set { SetEnabled(value); }
}
private bool m_Enabled;
//TODO: Make private once VisualContainer is merged with VisualElement
protected internal bool SetEnabledFromHierarchy(bool state)
{
//returns false if state hasn't changed
if (state == ((pseudoStates & PseudoStates.Disabled) != PseudoStates.Disabled))
return false;
if (state && m_Enabled && (parent == null || parent.enabledInHierarchy))
pseudoStates &= ~PseudoStates.Disabled;
else
pseudoStates |= PseudoStates.Disabled;
return true;
}
//Returns true if 'this' can be enabled relative to the enabled state of its panel
public bool enabledInHierarchy
{
get { return (pseudoStates & PseudoStates.Disabled) != PseudoStates.Disabled; }
}
//Returns the local enabled state
public bool enabledSelf
{
get { return m_Enabled; }
}
public void SetEnabled(bool value)
{
if (m_Enabled != value)
{
m_Enabled = value;
PropagateEnabledToChildren(value);
}
}
void PropagateEnabledToChildren(bool value)
{
if (SetEnabledFromHierarchy(value))
{
for (int i = 0; i < shadow.childCount; ++i)
{
shadow[i].PropagateEnabledToChildren(value);
}
}
}
public bool visible
{
get
{
return style.visibility.GetSpecifiedValueOrDefault(Visibility.Visible) == Visibility.Visible;
}
set
{
// Note: this could causes an allocation because styles are copy-on-write
// we might want to remove this setter altogether
// so everything goes through style.visibility (and then it's documented in a single place)
style.visibility = value ? Visibility.Visible : Visibility.Hidden;
}
}
public virtual void DoRepaint()
{
var painter = elementPanel.stylePainter;
painter.DrawBackground(this);
painter.DrawBorder(this);
}
internal virtual void DoRepaint(IStylePainter painter)
{
if (visible == false)
{
return;
}
DoRepaint();
}
private void GetFullHierarchicalPersistenceKey(StringBuilder key)
{
const string keySeparator = "__";
if (parent != null)
parent.GetFullHierarchicalPersistenceKey(key);
if (!string.IsNullOrEmpty(persistenceKey))
{
key.Append(keySeparator);
key.Append(persistenceKey);
}
}
public string GetFullHierarchicalPersistenceKey()
{
StringBuilder key = new StringBuilder();
GetFullHierarchicalPersistenceKey(key);
return key.ToString();
}
public T GetOrCreatePersistentData<T>(object existing, string key) where T : class, new()
{
Debug.Assert(elementPanel != null, "VisualElement.elementPanel is null! Cannot load persistent data.");
var persistentData = elementPanel == null || elementPanel.getViewDataDictionary == null ? null : elementPanel.getViewDataDictionary();
// If persistency is disable (no data, no key, no key one of the parents), just return the
// existing data or create a local one if none exists.
if (persistentData == null || string.IsNullOrEmpty(persistenceKey) || enablePersistence == false)
{
if (existing != null)
return existing as T;
return new T();
}
string keyWithType = key + "__" + typeof(T).ToString();
if (!persistentData.ContainsKey(keyWithType))
persistentData.Set(keyWithType, new T());
return persistentData.Get<T>(keyWithType);
}
public T GetOrCreatePersistentData<T>(ScriptableObject existing, string key) where T : ScriptableObject
{
Debug.Assert(elementPanel != null, "VisualElement.elementPanel is null! Cannot load persistent data.");
var persistentData = elementPanel == null || elementPanel.getViewDataDictionary == null ? null : elementPanel.getViewDataDictionary();
// If persistency is disable (no data, no key, no key one of the parents), just return the
// existing data or create a local one if none exists.
if (persistentData == null || string.IsNullOrEmpty(persistenceKey) || enablePersistence == false)
{
if (existing != null)
return existing as T;
return ScriptableObject.CreateInstance<T>();
}
string keyWithType = key + "__" + typeof(T).ToString();
if (!persistentData.ContainsKey(keyWithType))
persistentData.Set(keyWithType, ScriptableObject.CreateInstance<T>());
return persistentData.GetScriptable<T>(keyWithType);
}
public void OverwriteFromPersistedData(object obj, string key)
{
Debug.Assert(elementPanel != null, "VisualElement.elementPanel is null! Cannot load persistent data.");
var persistentData = elementPanel == null || elementPanel.getViewDataDictionary == null ? null : elementPanel.getViewDataDictionary();
// If persistency is disable (no data, no key, no key one of the parents), just return the
// existing data or create a local one if none exists.
if (persistentData == null || string.IsNullOrEmpty(persistenceKey) || enablePersistence == false)
{
return;
}
string keyWithType = key + "__" + obj.GetType();
if (!persistentData.ContainsKey(keyWithType))
{
persistentData.Set(keyWithType, obj);
return;
}
persistentData.Overwrite(obj, keyWithType);
}
public void SavePersistentData()
{
if (elementPanel != null && elementPanel.savePersistentViewData != null && !string.IsNullOrEmpty(persistenceKey))
elementPanel.savePersistentViewData();
}
internal bool IsPersitenceSupportedOnChildren()
{
// We relax here the requirement that ALL parents of a VisualElement
// need to have a persistenceKey for persistence to work. Plain
// VisualElements are likely to be used just for layouting and
// grouping and requiring a key on each element is a bit tedious.
if (this.GetType() == typeof(VisualElement))
return true;
if (string.IsNullOrEmpty(persistenceKey))
return false;
return true;
}
internal void OnPersistentDataReady(bool enablePersistence)
{
this.enablePersistence = enablePersistence;
OnPersistentDataReady();
}
public virtual void OnPersistentDataReady() {}
// position should be in local space
// override to customize intersection between point and shape
public virtual bool ContainsPoint(Vector2 localPoint)
{
return rect.Contains(localPoint);
}
public virtual bool Overlaps(Rect rectangle)
{
return rect.Overlaps(rectangle, true);
}
public enum MeasureMode
{
Undefined = YogaMeasureMode.Undefined,
Exactly = YogaMeasureMode.Exactly,
AtMost = YogaMeasureMode.AtMost
}
private bool m_RequireMeasureFunction = false;
internal bool requireMeasureFunction
{
get { return m_RequireMeasureFunction; }
set
{
m_RequireMeasureFunction = value;
if (m_RequireMeasureFunction && !yogaNode.IsMeasureDefined)
{
yogaNode.SetMeasureFunction(Measure);
}
else if (!m_RequireMeasureFunction && yogaNode.IsMeasureDefined)
{
yogaNode.SetMeasureFunction(null);
}
}
}
protected internal virtual Vector2 DoMeasure(float width, MeasureMode widthMode, float height, MeasureMode heightMode)
{
return new Vector2(float.NaN, float.NaN);
}
internal YogaSize Measure(YogaNode node, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode)
{
Debug.Assert(node == yogaNode, "YogaNode instance mismatch");
Vector2 size = DoMeasure(width, (MeasureMode)widthMode, height, (MeasureMode)heightMode);
return MeasureOutput.Make(Mathf.RoundToInt(size.x), Mathf.RoundToInt(size.y));
}
public void SetSize(Vector2 size)
{
var pos = layout;
pos.width = size.x;
pos.height = size.y;
layout = pos;
}
internal const Align DefaultAlignContent = Align.FlexStart;
internal const Align DefaultAlignItems = Align.Stretch;