This repository has been archived by the owner on Aug 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
/
PropertyContainer.cs
669 lines (579 loc) · 24.1 KB
/
PropertyContainer.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
// Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
// This file is distributed under GPL v3. See LICENSE.md for details.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using SiliconStudio.Core.Reflection;
using SiliconStudio.Core.Serialization;
using SiliconStudio.Core.Serialization.Serializers;
namespace SiliconStudio.Core
{
/// <summary>
/// Represents a container that can hold properties, lightweight to embed (lazy initialized).
/// </summary>
/// <remarks>
/// Tag properties system purpose is to allow binding of properties that aren't logically supposed to be
/// in a general class (probably because the property exists only in a higher level part of the engine).
/// A typical example includes source mesh, collision data and various bouding volumes for a Geometry object:
/// including them directly in the low-level Geometry class would be a terrible design decision !
/// And the other well known solution, which consist of maintaining a Dictionary of object to properties
/// isn't really nice either (especially with non-deterministic object destruction, it's hard to clean it up, would require lot of events).
/// As a result, a specific system has been implemented.
/// A class that could hold such tag properties should have an instance of <see cref="PropertyContainer"/> as a mutable field member.
/// An cool feature of this system is that if a property doesn't exist, it could be generated during first access from a delegate or come from a default value.
/// </remarks>
[DataContract]
//[DataSerializer(typeof(PropertyContainer.Serializer))]
[DataSerializer(typeof(DictionaryAllSerializer<PropertyContainer, PropertyKey, object>))]
[DataSerializerGlobal(null, typeof(Dictionary<PropertyKey, object>))]
public partial struct PropertyContainer : IDictionary<PropertyKey, object>
{
private static readonly Dictionary<Type, List<PropertyKey>> accessorProperties = new Dictionary<Type, List<PropertyKey>>();
private Dictionary<PropertyKey, object> properties;
private object owner;
private static ReadOnlyCollection<PropertyKey> emptyKeys = new ReadOnlyCollection<PropertyKey>(new List<PropertyKey>());
private static ReadOnlyCollection<object> emptyValues = new ReadOnlyCollection<object>(new List<object>());
/// <summary>
/// Property changed delegate.
/// </summary>
/// <param name="container">The property container.</param>
/// <param name="key">The property key.</param>
/// <param name="newValue">The property new value.</param>
/// <param name="oldValue">The property old value.</param>
public delegate void PropertyUpdatedDelegate(ref PropertyContainer propertyContainer, PropertyKey propertyKey, object newValue, object oldValue);
/// <summary>
/// Occurs when a property is modified.
/// </summary>
public event PropertyUpdatedDelegate PropertyUpdated;
public PropertyContainer(object owner)
{
properties = null;
PropertyUpdated = null;
this.owner = owner;
}
[DataMemberIgnore]
public object Owner
{
get
{
return owner;
}
private set
{
owner = value;
}
}
/// <summary>
/// Gets the key-properties value pairs in this instance.
/// </summary>
public IEnumerator<KeyValuePair<PropertyKey, object>> GetEnumerator()
{
if (properties != null)
{
foreach (var property in properties)
{
yield return new KeyValuePair<PropertyKey, object>(property.Key, property.Value);
}
}
if (Owner != null)
{
var currentType = Owner.GetType();
while (currentType != null)
{
List<PropertyKey> typeAccessorProperties;
if (accessorProperties.TryGetValue(currentType, out typeAccessorProperties))
{
foreach (var accessorProperty in typeAccessorProperties)
{
yield return new KeyValuePair<PropertyKey, object>(accessorProperty, accessorProperty.AccessorMetadata.GetValue(ref this));
}
}
currentType = currentType.GetTypeInfo().BaseType;
}
}
}
public void Clear()
{
if (properties != null) properties.Clear();
}
/// <summary>
/// Gets the number of properties stored in this container.
/// </summary>
/// <value>The count of properties.</value>
public int Count
{
get
{
// TODO: improve this.
int count = 0;
using (var enumerator = GetEnumerator())
{
while (enumerator.MoveNext())
++count;
}
return count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Adds the specified key-value pair.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void Add<T>(PropertyKey<T> key, T value)
{
SetObject(key, value, true);
}
/// <summary>
/// Determines whether the specified instance contains this key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified instance contains this key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(PropertyKey key)
{
// If it's a key with AccessorMetadata, check if it has been registered to this type
// Not very efficient... hopefully it should be rarely used. If not, it should be quite easy to optimize.
if (key.AccessorMetadata != null && Owner != null)
{
var currentType = Owner.GetType();
while (currentType != null)
{
List<PropertyKey> typeAccessorProperties;
if (accessorProperties.TryGetValue(currentType, out typeAccessorProperties))
{
foreach (var accessorProperty in typeAccessorProperties)
{
if (accessorProperty == key)
return true;
}
}
currentType = currentType.GetTypeInfo().BaseType;
}
return false;
}
return properties != null && properties.ContainsKey(key);
}
public void Add(PropertyKey key, object value)
{
SetObject(key, value, true);
}
public bool Remove(PropertyKey propertyKey)
{
bool removed = false;
if (PropertyUpdated != null || propertyKey.PropertyUpdateCallback != null)
{
object previousValue = Get(propertyKey);
if (properties != null)
removed = properties.Remove(propertyKey);
var tagValue = Get(propertyKey);
if (!ArePropertyValuesEqual(propertyKey, tagValue, previousValue))
{
if (propertyKey.PropertyUpdateCallback != null)
propertyKey.PropertyUpdateCallback(ref this, propertyKey, tagValue, previousValue);
if (PropertyUpdated != null)
PropertyUpdated(ref this, propertyKey, tagValue, previousValue);
}
}
else
{
if (properties != null)
removed = properties.Remove(propertyKey);
}
return removed;
}
public object this[PropertyKey key]
{
get
{
return Get(key);
}
set
{
SetObject(key, value);
}
}
public ICollection<PropertyKey> Keys
{
get
{
return this.Select(x => x.Key).ToList();
}
}
public ICollection<object> Values
{
get
{
return this.Select(x => x.Value).ToList();
}
}
/// <summary>
/// Copies properties from this instance to a container.
/// </summary>
/// <param name="destination">The destination.</param>
public void CopyTo(ref PropertyContainer destination)
{
foreach (var keyValuePair in this)
destination.SetObject(keyValuePair.Key, keyValuePair.Value);
}
/// <summary>
/// Gets the specified tag value.
/// </summary>
/// <param name="propertyKey">The tag property.</param>
/// <returns>Value of the tag property</returns>
public object Get(PropertyKey propertyKey)
{
return Get(propertyKey, false);
}
private object Get(PropertyKey propertyKey, bool forceNotToKeep)
{
// First, check if there is an accessor
if (propertyKey.AccessorMetadata != null)
{
return propertyKey.AccessorMetadata.GetValue(ref this);
}
object value;
// Get bound value, if any.
if (properties != null && properties.TryGetValue(propertyKey, out value))
{
if (propertyKey.IsValueType)
value = ((ValueHolder)value).ObjectValue;
return value;
}
if (propertyKey.DefaultValueMetadata != null)
{
// Get default value.
object defaultValue = propertyKey.DefaultValueMetadata.GetDefaultValue(ref this);
// Check if value should be kept.
if (propertyKey.DefaultValueMetadata.KeepValue && !forceNotToKeep)
{
// Register it.
SetObject(propertyKey, defaultValue);
}
return defaultValue;
}
return null;
}
/// <summary>
/// Gets the value of a property key or throw an error if the value was not found
/// </summary>
/// <typeparam name="T">Type of the property key</typeparam>
/// <param name="propertyKey">The property key.</param>
/// <returns>The value associated with this property key.</returns>
/// <exception cref="System.ArgumentNullException">propertyKey</exception>
/// <exception cref="System.ArgumentException">Unable to retrieve value for [{0}].ToFormat(propertyKey)</exception>
public T GetSafe<T>(PropertyKey<T> propertyKey)
{
if (propertyKey == null) throw new ArgumentNullException("propertyKey");
if (propertyKey.IsValueType)
{
return Get(propertyKey);
}
var result = Get((PropertyKey)propertyKey, false);
if (result == null)
{
throw new ArgumentException("Unable to retrieve value for [{0}]".ToFormat(propertyKey));
}
return (T)result;
}
/// <summary>
/// Gets the specified tag value.
/// </summary>
/// <typeparam name="T">Type of the tag value</typeparam>
/// <param name="propertyKey">The tag property.</param>
/// <returns>Typed value of the tag property</returns>
public T Get<T>(PropertyKey<T> propertyKey)
{
if (propertyKey == null) throw new ArgumentNullException("propertyKey");
if (propertyKey.IsValueType)
{
// Fast path for value type
// First, check if there is an accessor
if (propertyKey.AccessorMetadata != null)
{
// TODO: Not optimal, but not used so far
return (T)propertyKey.AccessorMetadata.GetValue(ref this);
}
object value;
// Get bound value, if any.
if (properties != null && properties.TryGetValue(propertyKey, out value))
return ((ValueHolder<T>)value).Value;
if (propertyKey.DefaultValueMetadata != null)
{
// Get default value.
T defaultValue = ((DefaultValueMetadata<T>)propertyKey.DefaultValueMetadata).GetDefaultValueT(ref this);
// Check if value should be kept.
if (propertyKey.DefaultValueMetadata.KeepValue)
{
// Register it.
Set(propertyKey, defaultValue);
}
return defaultValue;
}
return default(T);
}
var result = Get((PropertyKey)propertyKey, false);
return result != null ? (T)result : default(T);
}
/// <summary>
/// Tries to get a tag value.
/// </summary>
/// <typeparam name="T">Type of the tag value</typeparam>
/// <param name="propertyKey">The tag property.</param>
/// <param name="value">The value or default vaue if not found</param>
/// <returns>Returns <c>true</c> if the was found; <c>false</c> otherwise</returns>
public bool TryGetValue(PropertyKey propertyKey, out object value)
{
// Implem to avoid boxing/unboxing when using object as output value
if (ContainsKey(propertyKey))
{
var result = Get(propertyKey);
value = result;
return true;
}
value = null;
return false;
}
/// <summary>
/// Tries to get a tag value.
/// </summary>
/// <typeparam name="T">Type of the tag value</typeparam>
/// <param name="propertyKey">The tag property.</param>
/// <param name="value">The value or default vaue if not found</param>
/// <returns>Returns <c>true</c> if the was found; <c>false</c> otherwise</returns>
public bool TryGetValue<T>(PropertyKey<T> propertyKey, out T value)
{
if (ContainsKey(propertyKey))
{
value = Get<T>(propertyKey);
return true;
}
value = default(T);
return false;
}
/// <summary>
/// Sets the specified tag value.
/// </summary>
/// <typeparam name="T">Type of the tag value</typeparam>
/// <param name="propertyKey">The tag property.</param>
/// <param name="tagValue">The tag value.</param>
public void Set<T>(PropertyKey<T> propertyKey, T tagValue)
{
if (propertyKey.IsValueType)
{
ValueHolder<T> valueHolder = null;
T oldValue;
// Fast path for value types
// Fast path for value type
// First, check if there is an accessor
if (propertyKey.AccessorMetadata != null)
{
// TODO: Not optimal, but not used so far
oldValue = (T)propertyKey.AccessorMetadata.GetValue(ref this);
}
else
{
object value;
// Get bound value, if any.
if (properties != null && properties.TryGetValue(propertyKey, out value))
{
valueHolder = (ValueHolder<T>)value;
oldValue = valueHolder.Value;
}
else if (propertyKey.DefaultValueMetadata != null)
{
// Get default value.
oldValue = propertyKey.DefaultValueMetadataT.GetDefaultValueT(ref this);
}
else
{
oldValue = default(T);
}
}
// Allow to validate the metadata before storing it.
if (propertyKey.ValidateValueMetadata != null)
{
// TODO: Use typed validate?
propertyKey.ValidateValueMetadataT.ValidateValueCallback(ref tagValue);
}
// First, check if there is an accessor
if (propertyKey.AccessorMetadata != null)
{
// TODO: Not optimal, but not used so far
propertyKey.AccessorMetadata.SetValue(ref this, tagValue);
return;
}
if (properties == null)
properties = new Dictionary<PropertyKey, object>();
if (valueHolder != null)
valueHolder.Value = tagValue;
else
valueHolder = new ValueHolder<T>(tagValue);
if (PropertyUpdated != null || propertyKey.PropertyUpdateCallback != null)
{
object previousValue = GetNonRecursive(propertyKey);
properties[propertyKey] = valueHolder;
if (!ArePropertyValuesEqual(propertyKey, tagValue, previousValue))
{
if (PropertyUpdated != null)
PropertyUpdated(ref this, propertyKey, tagValue, previousValue);
if (propertyKey.PropertyUpdateCallback != null)
propertyKey.PropertyUpdateCallback(ref this, propertyKey, tagValue, previousValue);
}
}
else
{
properties[propertyKey] = valueHolder;
}
if (propertyKey.ObjectInvalidationMetadata != null)
{
propertyKey.ObjectInvalidationMetadataT.Invalidate(Owner, propertyKey, ref oldValue);
}
return;
}
SetObject((PropertyKey)propertyKey, tagValue, false);
}
/// <summary>
/// Sets the specified tag value.
/// </summary>
/// <param name="propertyKey">The tag property.</param>
/// <param name="tagValue">The tag value.</param>
public void SetObject(PropertyKey propertyKey, object tagValue)
{
SetObject(propertyKey, tagValue, false);
}
private void SetObject(PropertyKey propertyKey, object tagValue, bool tryToAdd = false)
{
var oldValue = Get(propertyKey, true);
// Allow to validate the metadata before storing it.
if (propertyKey.ValidateValueMetadata != null)
{
propertyKey.ValidateValueMetadata.Validate(ref tagValue);
}
// First, check if there is an accessor
if (propertyKey.AccessorMetadata != null)
{
propertyKey.AccessorMetadata.SetValue(ref this, tagValue);
return;
}
if (properties == null)
properties = new Dictionary<PropertyKey, object>();
var valueToSet = propertyKey.IsValueType ? propertyKey.CreateValueHolder(tagValue) : tagValue;
if (PropertyUpdated != null || propertyKey.PropertyUpdateCallback != null)
{
object previousValue = GetNonRecursive(propertyKey);
if (tryToAdd)
properties.Add(propertyKey, valueToSet);
else
properties[propertyKey] = valueToSet;
if (!ArePropertyValuesEqual(propertyKey, tagValue, previousValue))
{
if (PropertyUpdated != null)
PropertyUpdated(ref this, propertyKey, tagValue, previousValue);
if (propertyKey.PropertyUpdateCallback != null)
propertyKey.PropertyUpdateCallback(ref this, propertyKey, tagValue, previousValue);
}
}
else
{
if (tryToAdd)
properties.Add(propertyKey, valueToSet);
else
properties[propertyKey] = valueToSet;
}
if (propertyKey.ObjectInvalidationMetadata != null)
{
propertyKey.ObjectInvalidationMetadata.Invalidate(Owner, propertyKey, oldValue);
}
}
public static void AddAccessorProperty(Type type, PropertyKey propertyKey)
{
if (!type.GetTypeInfo().IsClass)
throw new ArgumentException("Class type is expected.", "type");
if (propertyKey.AccessorMetadata == null)
throw new ArgumentException("Given PropertyKey doesn't have accessor metadata.", "propertyKey");
List<PropertyKey> typeAccessorProperties;
if (!accessorProperties.TryGetValue(type, out typeAccessorProperties))
accessorProperties.Add(type, typeAccessorProperties = new List<PropertyKey>());
typeAccessorProperties.Add(propertyKey);
}
internal void RaisePropertyContainerUpdated(PropertyKey propertyKey, object newValue, object oldValue)
{
if (PropertyUpdated != null)
PropertyUpdated(ref this, propertyKey, newValue, oldValue);
}
private object GetNonRecursive(PropertyKey propertyKey)
{
object value;
// Get bound value, if any.
if (properties != null && properties.TryGetValue(propertyKey, out value))
{
if (propertyKey.IsValueType)
return ((ValueHolder)value).ObjectValue;
return value;
}
if (propertyKey.DefaultValueMetadata != null)
{
// Get default value.
return propertyKey.DefaultValueMetadata.GetDefaultValue(ref this);
}
return null;
}
private static bool ArePropertyValuesEqual(PropertyKey propertyKey, object propertyValue1, object propertyValue2)
{
var propertyType = propertyKey.PropertyType;
if (!propertyType.GetTypeInfo().IsValueType && propertyType != typeof(string))
{
return object.ReferenceEquals(propertyValue1, propertyValue2);
}
return object.Equals(propertyValue1, propertyValue2);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void ICollection<KeyValuePair<PropertyKey, object>>.Add(KeyValuePair<PropertyKey, object> item)
{
Add(item.Key, item.Value);
}
bool ICollection<KeyValuePair<PropertyKey, object>>.Contains(KeyValuePair<PropertyKey, object> item)
{
return properties.ContainsValue(item);
}
void ICollection<KeyValuePair<PropertyKey, object>>.CopyTo(KeyValuePair<PropertyKey, object>[] array, int arrayIndex)
{
((IDictionary<PropertyKey, object>)properties).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<PropertyKey, object>>.Remove(KeyValuePair<PropertyKey, object> item)
{
return ((IDictionary<PropertyKey, object>)properties).Remove(item);
}
internal abstract class ValueHolder
{
public abstract object ObjectValue { get; }
}
internal class ValueHolder<T> : ValueHolder
{
public T Value;
public ValueHolder(T value)
{
Value = value;
}
public override object ObjectValue
{
get { return Value; }
}
}
}
}