/
BindingExtensions.cs
2270 lines (1924 loc) · 82 KB
/
BindingExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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 Unity.Profiling;
using UnityEngine;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;
namespace UnityEditor.UIElements.Bindings
{
internal class SerializedObjectBindingContext
{
public UInt64 lastRevision {get; private set; }
public SerializedObject serializedObject {get; private set; }
private bool wasUpdated {get; set; }
private bool m_DelayBind = false;
private long m_BindingOperationStartTimeMs;
private const int k_MaxBindingTimeMs = 50;
public SerializedObjectBindingContext(SerializedObject so)
{
this.serializedObject = so;
this.lastRevision = so.objectVersion;
}
public void Bind(VisualElement element)
{
element.SetProperty(FindContextPropertyKey, this);
ContinueBinding(element, null);
}
internal void ContinueBinding(VisualElement element, SerializedProperty parentProperty)
{
try
{
m_BindingOperationStartTimeMs = Panel.TimeSinceStartupMs();
m_DelayBind = false;
BindTree(element, parentProperty);
}
finally
{
m_DelayBind = false;
}
}
private bool ShouldDelayBind()
{
if (!m_DelayBind && !VisualTreeBindingsUpdater.disableBindingsThrottling)
{
m_DelayBind = (Panel.TimeSinceStartupMs() - m_BindingOperationStartTimeMs) > k_MaxBindingTimeMs;
}
return m_DelayBind;
}
public void Unbind(VisualElement element)
{
var existingContext = element.GetProperty(FindContextPropertyKey);
if (existingContext != null)
{
if (existingContext != this)
{
return;
}
element.SetProperty(FindContextPropertyKey, null);
}
RemoveBinding(element as IBindable, false);
var childCount = element.hierarchy.childCount;
for (int i = 0; i < childCount; ++i)
{
Unbind(element.hierarchy[i]);
}
}
#region Bind Tree
private static bool SendBindingEvent<TEventType>(TEventType evt, VisualElement target)
where TEventType : EventBase<TEventType>, new()
{
evt.elementTarget = target;
EventDispatchUtilities.HandleEventAtTargetAndDefaultPhase(evt, target.elementPanel, target);
return evt.isPropagationStopped;
}
internal void BindTree(VisualElement element, SerializedProperty parentProperty)
{
if (element.HasSelfEventInterests(SerializedObjectBindEvent.EventCategory))
{
using (var evt = SerializedObjectBindEvent.GetPooled(serializedObject))
{
if (SendBindingEvent(evt, element))
{
return;
}
}
}
if (ShouldDelayBind())
{
// too much time spent on binding, we`ll do the rest on the next frame
var request = DefaultSerializedObjectBindingImplementation.BindingRequest.CreateDelayBinding(this, parentProperty);
VisualTreeBindingsUpdater.AddBindingRequest(element, request);
return;
}
if (element is IBindable field)
{
if (!string.IsNullOrEmpty(field.bindingPath))
{
var foundProperty = BindPropertyRelative(field, parentProperty);
if (foundProperty != null)
{
parentProperty = foundProperty;
}
}
}
var childCount = element.hierarchy.childCount;
for (var i = 0; i < childCount; ++i)
{
BindTree(element.hierarchy[i], parentProperty);
}
}
private static readonly string k_EnabledOverrideSet = "EnabledSetByBindings";
static void SyncEditableState(VisualElement fieldElement, bool shouldBeEditable)
{
if (fieldElement.enabledSelf != shouldBeEditable)
{
if (shouldBeEditable)
{
if (fieldElement.GetProperty(k_EnabledOverrideSet) != null)
{
fieldElement.SetEnabled(true);
}
else
{
// the field was disabled by user code, we don't want to re-enable it.
}
}
else
{
fieldElement.SetProperty(k_EnabledOverrideSet, fieldElement.enabledSelf);
fieldElement.SetEnabled(false);
}
}
}
internal SerializedProperty BindPropertyRelative(IBindable field, SerializedProperty parentProperty)
{
var unsafeMode = parentProperty?.unsafeMode ?? false;
// We switch to unsafe mode because we don't care if the parentProperty is valid or not (using
// [SerializeReference], you can end up with a property that doesn't exist anymore, which would throw in
// "safe mode")
if (null != parentProperty)
parentProperty.unsafeMode = true;
var property = parentProperty?.FindPropertyRelative(field.bindingPath);
if (null != parentProperty)
parentProperty.unsafeMode = unsafeMode;
if (property == null)
property = serializedObject?.FindProperty(field.bindingPath);
if (property == null || field is not VisualElement fieldElement)
{
// Object is null or property was not found, we have nothing to do here
return property;
}
// Set enabled state before sending the event because element like PropertyField may stop the event
SyncEditableState(fieldElement, property.editable);
if (fieldElement.HasSelfEventInterests(SerializedPropertyBindEvent.EventCategory))
{
using (var evt = SerializedPropertyBindEvent.GetPooled(property))
{
if (SendBindingEvent(evt, fieldElement))
{
return property;
}
}
}
// If we intend on binding, we first remove any binding that were already present
RemoveBinding(field, true);
CreateBindingObjectForProperty(fieldElement, property);
return property;
}
private void CreateBindingObjectForProperty(VisualElement element, SerializedProperty prop)
{
// A bound Foldout (a PropertyField with child properties) is special.
if (element is Foldout foldout)
{
// We bind to the given propertyPath but we only bind to its 'isExpanded' state, not its value.
SerializedObjectBinding<bool>.CreateBind(
foldout, this, prop,
p => p.isExpanded,
(p, v) => p.isExpanded = v,
SerializedPropertyHelper.ValueEquals<bool>);
return;
}
else if (element is Label label && label.GetProperty(PropertyField.foldoutTitleBoundLabelProperty) != null)
{
// We bind to the given propertyPath but we only bind to its 'localizedDisplayName' state, not its value.
// This is a feature from IMGUI where the title of a Foldout will change if one of the child
// properties is named "Name" and its value changes.
SerializedObjectBinding<string>.CreateBind(
label, this, prop,
p => p.localizedDisplayName,
(p, v) => {},
SerializedPropertyHelper.ValueEquals<string>);
return;
}
if (element is ListView listView)
{
BindListView(listView, prop);
if (listView.headerFoldout != null)
{
// The foldout will be bound as hierarchy binding continues.
listView.headerFoldout.bindingPath = prop.propertyPath;
}
return;
}
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
if (prop.type == "long" || prop.type == "ulong")
{
if (element is INotifyValueChanged<long> || element is INotifyValueChanged<string>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetLongPropertyValue, SerializedPropertyHelper.SetLongPropertyValue, SerializedPropertyHelper.ValueEquals);
}
else if (element is INotifyValueChanged<ulong>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetULongPropertyValue, SerializedPropertyHelper.SetULongPropertyValue, SerializedPropertyHelper.ValueEquals);
}
else if (element is INotifyValueChanged<int>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetIntPropertyValue, SerializedPropertyHelper.SetIntPropertyValue, SerializedPropertyHelper.ValueEquals);
}
else if (element is INotifyValueChanged<float>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetLongPropertyValueAsFloat, SerializedPropertyHelper.SetFloatPropertyValue, SerializedPropertyHelper.ValueEquals);
}
}
else // prop.type == "int"
{
if (element is INotifyValueChanged<int> || element is INotifyValueChanged<string>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetIntPropertyValue, SerializedPropertyHelper.SetIntPropertyValue, SerializedPropertyHelper.ValueEquals);
}
else if (element is INotifyValueChanged<uint>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetUIntPropertyValue, SerializedPropertyHelper.SetUIntPropertyValue, SerializedPropertyHelper.ValueEquals);
}
else if (element is INotifyValueChanged<long>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetLongPropertyValue, SerializedPropertyHelper.SetLongPropertyValue, SerializedPropertyHelper.ValueEquals);
}
else if (element is INotifyValueChanged<float>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetIntPropertyValueAsFloat, SerializedPropertyHelper.SetFloatPropertyValue, SerializedPropertyHelper.ValueEquals);
}
}
break;
case SerializedPropertyType.Boolean:
DefaultBind(element, prop, SerializedPropertyHelper.GetBoolPropertyValue, SerializedPropertyHelper.SetBoolPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Float:
if (prop.type == "float")
{
if (element is INotifyValueChanged<double>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetFloatPropertyValueAsDouble, SerializedPropertyHelper.SetFloatPropertyValueFromDouble, SerializedPropertyHelper.ValueEquals);
}
else
{
DefaultBind(element, prop, SerializedPropertyHelper.GetFloatPropertyValue, SerializedPropertyHelper.SetFloatPropertyValue, SerializedPropertyHelper.ValueEquals);
}
}
else // prop.type == "double"
{
if (element is INotifyValueChanged<float>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetDoublePropertyValueAsFloat, SerializedPropertyHelper.SetDoublePropertyValueFromFloat, SerializedPropertyHelper.ValueEquals);
}
else
{
DefaultBind(element, prop, SerializedPropertyHelper.GetDoublePropertyValue, SerializedPropertyHelper.SetDoublePropertyValue, SerializedPropertyHelper.ValueEquals);
}
}
break;
case SerializedPropertyType.String:
DefaultBind(element, prop, SerializedPropertyHelper.GetStringPropertyValue, SerializedPropertyHelper.SetStringPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Color:
DefaultBind(element, prop, SerializedPropertyHelper.GetColorPropertyValue, SerializedPropertyHelper.SetColorPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.ObjectReference:
DefaultBind(element, prop, SerializedPropertyHelper.GetObjectRefPropertyValue, SerializedPropertyHelper.SetObjectRefPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.LayerMask:
DefaultBind(element, prop, SerializedPropertyHelper.GetLayerMaskPropertyValue, SerializedPropertyHelper.SetLayerMaskPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Enum:
CreateEnumBindingObject(element, prop);
break;
case SerializedPropertyType.Vector2:
DefaultBind(element, prop, SerializedPropertyHelper.GetVector2PropertyValue, SerializedPropertyHelper.SetVector2PropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Vector3:
DefaultBind(element, prop, SerializedPropertyHelper.GetVector3PropertyValue, SerializedPropertyHelper.SetVector3PropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Vector4:
DefaultBind(element, prop, SerializedPropertyHelper.GetVector4PropertyValue, SerializedPropertyHelper.SetVector4PropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Rect:
DefaultBind(element, prop, SerializedPropertyHelper.GetRectPropertyValue, SerializedPropertyHelper.SetRectPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.ArraySize:
DefaultBind(element, prop, SerializedPropertyHelper.GetIntPropertyValue, SerializedPropertyHelper.SetIntPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.AnimationCurve:
DefaultBind(element, prop, SerializedPropertyHelper.GetAnimationCurvePropertyValue, SerializedPropertyHelper.SetAnimationCurvePropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Bounds:
DefaultBind(element, prop, SerializedPropertyHelper.GetBoundsPropertyValue, SerializedPropertyHelper.SetBoundsPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Gradient:
DefaultBind(element, prop, SerializedPropertyHelper.GetGradientPropertyValue, SerializedPropertyHelper.SetGradientPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Quaternion:
DefaultBind(element, prop, SerializedPropertyHelper.GetQuaternionPropertyValue, SerializedPropertyHelper.SetQuaternionPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.FixedBufferSize:
DefaultBind(element, prop, SerializedPropertyHelper.GetIntPropertyValue, SerializedPropertyHelper.SetIntPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Vector2Int:
DefaultBind(element, prop, SerializedPropertyHelper.GetVector2IntPropertyValue, SerializedPropertyHelper.SetVector2IntPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Vector3Int:
DefaultBind(element, prop, SerializedPropertyHelper.GetVector3IntPropertyValue, SerializedPropertyHelper.SetVector3IntPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.RectInt:
DefaultBind(element, prop, SerializedPropertyHelper.GetRectIntPropertyValue, SerializedPropertyHelper.SetRectIntPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.BoundsInt:
DefaultBind(element, prop, SerializedPropertyHelper.GetBoundsIntPropertyValue, SerializedPropertyHelper.SetBoundsIntPropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.Character:
if (element is INotifyValueChanged<string>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetCharacterPropertyValueAsString, SerializedPropertyHelper.SetCharacterPropertyValueFromString, SerializedPropertyHelper.ValueEquals);
}
else
{
DefaultBind(element, prop, SerializedPropertyHelper.GetCharacterPropertyValue, SerializedPropertyHelper.SetCharacterPropertyValue, SerializedPropertyHelper.ValueEquals);
}
break;
case SerializedPropertyType.Hash128:
DefaultBind(element, prop, SerializedPropertyHelper.GetHash128PropertyValue, SerializedPropertyHelper.SetHash128PropertyValue, SerializedPropertyHelper.ValueEquals);
break;
case SerializedPropertyType.ExposedReference:
case SerializedPropertyType.Generic:
// nothing to bind here
break;
default:
Debug.LogWarning(string.Format("Binding is not supported for {0} properties \"{1}\"", prop.type,
prop.propertyPath));
break;
}
}
private void DefaultBind<TValue>(VisualElement element, SerializedProperty prop,
Func<SerializedProperty, TValue> propertyReadFunc, Action<SerializedProperty, TValue> propertyWriteFunc,
Func<TValue, SerializedProperty, Func<SerializedProperty, TValue>, bool> valueComparerFunc)
{
var field = element as INotifyValueChanged<TValue>;
if (element is INotifyValueChanged<string> && typeof(TValue) != typeof(string))
{
//One Way Binding here with string conversions
SerializedObjectStringConversionBinding<TValue>.CreateBind(element as INotifyValueChanged<string>, this, prop, propertyReadFunc,
propertyWriteFunc, valueComparerFunc);
}
else if (field != null)
{
SerializedObjectBinding<TValue>.CreateBind(field, this, prop, propertyReadFunc,
propertyWriteFunc, valueComparerFunc);
}
else
{
Debug.LogWarning(string.Format("Field type {0} is not compatible with {2} property \"{1}\"",
element.GetType().FullName, prop.propertyPath, prop.type));
}
}
private void CreateEnumBindingObject(VisualElement element, SerializedProperty prop)
{
if (element is PopupField<string>)
{
SerializedDefaultEnumBinding.CreateBind((PopupField<string>)element, this, prop);
}
else if (element is EnumFlagsField || element is EnumField)
{
SerializedManagedEnumBinding.CreateBind((BaseField<Enum>)element, this, prop);
}
else if (element is INotifyValueChanged<int>)
{
DefaultBind(element, prop, SerializedPropertyHelper.GetIntPropertyValue, SerializedPropertyHelper.SetIntPropertyValue, SerializedPropertyHelper.ValueEquals);
}
else
{
DefaultBind(element, prop, SerializedPropertyHelper.GetEnumPropertyValueAsString, SerializedPropertyHelper.SetEnumPropertyValueFromString, SerializedPropertyHelper.SlowEnumValueEquals);
}
}
private bool BindListView(ListView listView, SerializedProperty prop)
{
// This should be done elsewhere. That's what the SerializedPropertyBindEvent are for.
// Problem is, ListView is in the engine assembly and can't have knowledge of SerializedObjects
if (prop.propertyType == SerializedPropertyType.Generic)
{
var sizeProperty = prop.FindPropertyRelative("Array.size");
if (sizeProperty == null)
{
Debug.LogWarning(string.Format("Binding ListView failed: can't find array size for property \"{0}\"",
prop.propertyPath));
return false;
}
ListViewSerializedObjectBinding.CreateBind(listView, this, prop);
return true;
}
else
{
Debug.LogWarning(string.Format("Binding ListView is not supported for {0} properties \"{1}\"", prop.type,
prop.propertyPath));
}
return false;
}
private void RemoveBinding(IBindable bindable, bool forceRemove)
{
if (bindable == null || !bindable.IsBound())
{
return;
}
if (bindable.binding is SerializedObjectBindingBase bindingBase)
{
if (forceRemove || bindingBase.bindingContext == this)
{
bindable.binding?.Release();
bindable.binding = null;
}
}
}
private static readonly PropertyName FindContextPropertyKey = "__UnityBindingContext";
internal static SerializedObjectBindingContext GetBindingContextFromElement(VisualElement element)
{
if (element is IBindable bindable)
{
if (bindable.binding is SerializedObjectBindingBase bindingBase)
{
return bindingBase.bindingContext;
}
}
if (element.GetProperty(FindContextPropertyKey) is SerializedObjectBindingContext context)
{
return context;
}
return null;
}
internal static SerializedObjectBindingContext FindBindingContext(VisualElement element, SerializedObject obj)
{
while (element != null)
{
var context = GetBindingContextFromElement(element);
if (context != null && context.serializedObject == obj)
return context;
element = element.hierarchy.parent;
}
return null;
}
#endregion
#region SerializedObject Version Update
internal void UpdateRevision()
{
var previousRevision = lastRevision;
if (IsValid())
{
lastRevision = serializedObject.objectVersion;
if (previousRevision != lastRevision)
{
OnSerializedObjectChanged();
}
}
}
internal bool IsValid()
{
if (serializedObject == null || serializedObject.m_NativeObjectPtr == IntPtr.Zero)
return false;
return serializedObject.isValid;
}
internal void UpdateIfNecessary()
{
if (!wasUpdated)
{
if (IsValid())
{
serializedObject.UpdateIfRequiredOrScript();
UpdateRevision();
}
wasUpdated = true;
}
}
internal void ResetUpdate()
{
if (wasUpdated)
{
wasUpdated = false;
UpdateRevision(); //If somebody called Update() on our serializedObject, we need to revalidate properties
}
}
void OnSerializedObjectChanged()
{
UpdateTrackedProperties();
}
#endregion
#region Property Value Tracking
class TrackedValue
{
public uint contentHash;
public Action<object, SerializedProperty> onChangeCallback;
public Action<object, SerializedProperty> onUpdateCallback;
public object cookie;
public SerializedPropertyType originalPropType;
public int propertyHash;
public TrackedValue(SerializedProperty property, Action<object, SerializedProperty> changeCB, Action<object, SerializedProperty> updateCB)
{
contentHash = property.contentHash;
originalPropType = property.propertyType;
propertyHash = property.hashCodeForPropertyPath;
onChangeCallback = changeCB;
onUpdateCallback = updateCB;
}
public bool Update(SerializedObjectBindingContext context, SerializedProperty currentProp)
{
if (currentProp.propertyType != originalPropType)
{
return false;
}
onUpdateCallback?.Invoke(cookie, currentProp);
var newContentHash = currentProp.contentHash;
if (contentHash != newContentHash)
{
contentHash = newContentHash;
onChangeCallback(cookie, currentProp);
}
return true;
}
}
class TrackedValues
{
// MultiValueDictionary?
private Dictionary<int, List<TrackedValue> > m_TrackedValues = new Dictionary<int, List<TrackedValue>>();
public TrackedValues()
{
}
public void Add(SerializedProperty prop, object cookie, Action<object, SerializedProperty> onChangeCallback, Action<object, SerializedProperty> onUpdateCallback)
{
var hash = prop.hashCodeForPropertyPath;
if (!m_TrackedValues.TryGetValue(hash, out var values))
{
values = new List<TrackedValue>();
m_TrackedValues.Add(hash, values);
}
var t = new TrackedValue(prop, onChangeCallback, onUpdateCallback);
t.cookie = cookie;
values.Add(t);
}
public void Remove(SerializedProperty prop, object cookie)
{
var hash = prop.hashCodeForPropertyPath;
Remove(hash, cookie);
}
public void Remove(int propertyPathHash, object cookie)
{
if (m_TrackedValues.TryGetValue(propertyPathHash, out var values))
{
for (int i = values.Count - 1; i >= 0; i--)
{
var t = values[i];
if (ReferenceEquals(t.cookie, cookie))
{
values.RemoveAt(i);
}
}
if (values.Count == 0)
{
m_TrackedValues.Remove(propertyPathHash);
}
}
}
public void Update(SerializedObjectBindingContext context, SerializedProperty currentProperty)
{
var hash = currentProperty.hashCodeForPropertyPath;
if (m_TrackedValues.TryGetValue(hash, out var values))
{
for (int i = 0; i < values.Count; ++i)
{
values[i].Update(context, currentProperty);
}
}
}
}
/// <summary>
/// Map of value trackers per serialized property type. WARNING: tracker may be null for some types.
/// Check <see cref="GetOrCreateTrackedValues"/> for reference.
/// </summary>
private TrackedValues m_ValueTracker = new TrackedValues();
public bool RegisterSerializedPropertyChangeCallback(object cookie, SerializedProperty property,
Action<object, SerializedProperty> valueChangedCallback)
{
m_ValueTracker.Add(property, cookie, valueChangedCallback, null);
return true;
}
public void UnregisterSerializedPropertyChangeCallback(object cookie, SerializedProperty property)
{
m_ValueTracker.Remove(property, cookie);
}
public SerializedObjectBindingContextUpdater AddBindingUpdater(VisualElement element)
{
var b = VisualTreeBindingsUpdater.GetAdditionalBinding(element);
var contextUpdater = b as SerializedObjectBindingContextUpdater;
if (b == null)
{
contextUpdater = SerializedObjectBindingContextUpdater.Create(element, this);
VisualTreeBindingsUpdater.SetAdditionalBinding(element, contextUpdater);
}
else
{
if (contextUpdater == null || contextUpdater.bindingContext != this)
{
throw new NotSupportedException("An element can track properties on only one serializedObject at a time");
}
}
return contextUpdater;
}
#endregion
private HashSet<SerializedObjectBindingBase> m_RegisteredBindings = new HashSet<SerializedObjectBindingBase>();
private static void DefaultOnPropertyChange(object cookie, SerializedProperty changedProp)
{
if (cookie is SerializedObjectBindingBase binding)
{
binding.OnPropertyValueChanged(changedProp);
}
}
private static void OnPropertyUpdate(object cookie, SerializedProperty changedProp)
{
if (cookie is SerializedObjectBindingBase binding)
{
binding.SyncObjectVersion();
}
}
internal void RegisterBindingObject(SerializedObjectBindingBase b)
{
if (!m_RegisteredBindings.Contains(b))
{
m_RegisteredBindings.Add(b);
if (b.ResolveProperty())
{
m_ValueTracker.Add(b.boundProperty, b, (o, p) => DefaultOnPropertyChange(o,p), (o, p) => OnPropertyUpdate(o,p));
}
}
}
internal void UnregisterBindingObject(SerializedObjectBindingBase b)
{
if (b.boundPropertyHash != 0)
{
m_ValueTracker.Remove(b.boundPropertyHash, b);
}
m_RegisteredBindings.Remove(b);
}
HashSet<long> visited = new HashSet<long>();
void UpdateTrackedProperties()
{
// Iterating over the entire object, as gathering valid property names hashes is faster than querying
// each saved SerializedProperty.isValid
var iterator = serializedObject.GetIterator();
iterator.unsafeMode = true;
visited.Clear();
{
bool visitChild = true;
while (iterator.Next(visitChild))
{
visitChild = true;
switch (iterator.propertyType)
{
case SerializedPropertyType.ManagedReference:
{
// Managed reference objects can form a cyclical graph, so need to track visited objects
long refId = iterator.managedReferenceId;
if (!visited.Add(refId))
{
visitChild = false;
}
break;
}
case SerializedPropertyType.String:
visitChild = false;
break;
default:
break;
}
m_ValueTracker.Update(this, iterator);
}
}
visited.Clear();
}
}
internal class DefaultSerializedObjectBindingImplementation : ISerializedObjectBindingImplementation
{
public void Bind(VisualElement element, SerializedObject obj)
{
element.SetProperty(BindingExtensions.s_DataSourceProperty, obj);
if (element.panel != null || element is EditorElement || element is InspectorElement)
{
var context = FindOrCreateBindingContext(element, obj);
context.Bind(element);
return;
}
//wait later
CreateBindingRequest(element, obj);
}
public void Unbind(VisualElement element)
{
element?.SetProperty(BindingExtensions.s_DataSourceProperty, null);
UnbindTree(element);
}
private void UnbindTree(VisualElement element)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
var context = SerializedObjectBindingContext.GetBindingContextFromElement(element);
RemoveBindingRequest(element);
VisualTreeBindingsUpdater.ClearAdditionalBinding(element);
if (context != null)
{
context.Unbind(element);
}
else
{
var childCount = element.hierarchy.childCount;
for (int i = 0; i < childCount; ++i)
{
UnbindTree(element.hierarchy[i]);
}
}
}
static Dictionary<object, object> GetTemporaryCache(VisualElement element)
{
var updater = element.elementPanel?.GetUpdater(VisualTreeUpdatePhase.Bindings) as VisualTreeBindingsUpdater;
return updater?.temporaryObjectCache;
}
static SerializedObjectBindingContext FindOrCreateBindingContext(VisualElement element, SerializedObject obj)
{
var context = SerializedObjectBindingContext.FindBindingContext(element, obj);
if (context == null || context.serializedObject != obj)
{
//we couldn't find the context, let's try to find it elsewhere
var cookie = GetTemporaryCache(element);
if (cookie != null && obj != null)
{
if (cookie.TryGetValue(obj, out var c))
{
context = c as SerializedObjectBindingContext;
}
}
if (context == null)
{
context = new SerializedObjectBindingContext(obj);
if (obj != null)
{
cookie?.Add(obj, context);
}
}
}
return context;
}
public SerializedProperty BindProperty(IBindable field, SerializedObject obj)
{
var property = obj?.FindProperty(field.bindingPath);
if (property != null)
{
var element = field as VisualElement;
if (element != null)
{
if (element.panel == null)
{
// wait until element is attached
CreateBindingRequest(element, property.serializedObject);
}
else
{
var context = FindOrCreateBindingContext(element, obj);
context.Bind(element);
}
}
}
return property;
}
public void BindProperty(IBindable field, SerializedProperty property)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
field.bindingPath = property.propertyPath;
var element = field as VisualElement;
if (element != null)
{
if (element.panel == null)
{
// wait until element is attached
CreateBindingRequest(element, property.serializedObject);
}
else
{
var context = FindOrCreateBindingContext(element, property.serializedObject);
context.Bind(element);
}
}
}
public void TrackPropertyValue(VisualElement element, SerializedProperty property, Action<SerializedProperty> callback)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
if (element != null)
{
var request = BindingRequest.Create(BindingRequest.RequestType.TrackProperty, property.serializedObject);
request.parentProperty = property.Copy();
request.obj = property.serializedObject;
if (callback != null)
{
request.callback = (e, p) => callback(p);
}
else
{
request.callback = SendPropertyChangeCallback;
}
if (element.panel == null)
{
// wait until element is attached
VisualTreeBindingsUpdater.AddBindingRequest(element, request);
}
else
{
request.Bind(element);
request.Release();
}
}
}
private static void SendPropertyChangeCallback(object cookie, SerializedProperty prop)
{
if (cookie is VisualElement element)
{
using (SerializedPropertyChangeEvent evt = SerializedPropertyChangeEvent.GetPooled())
{
evt.changedProperty = prop;
evt.elementTarget = element;
element.SendEvent(evt);
}
}
}
private static void SendObjectChangeCallback(object cookie, SerializedObject obj)
{
if (cookie is VisualElement element)
{
using (SerializedObjectChangeEvent evt = SerializedObjectChangeEvent.GetPooled(obj))