// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reactive.Subjects;
using System.Reflection;
using Avalonia.Data;
using Avalonia.Utilities;
namespace Avalonia
{
///
/// Base class for avalonia properties.
///
public abstract class AvaloniaProperty : IEquatable
{
///
/// Represents an unset property value.
///
public static readonly object UnsetValue = new UnsetValueType();
private static int s_nextId;
private readonly Subject _initialized;
private readonly Subject _changed;
private readonly PropertyMetadata _defaultMetadata;
private readonly Dictionary _metadata;
private readonly Dictionary _metadataCache = new Dictionary();
private bool _hasMetadataOverrides;
///
/// Initializes a new instance of the class.
///
/// The name of the property.
/// The type of the property's value.
/// The type of the class that registers the property.
/// The property metadata.
/// A callback.
protected AvaloniaProperty(
string name,
Type valueType,
Type ownerType,
PropertyMetadata metadata,
Action notifying = null)
{
Contract.Requires(name != null);
Contract.Requires(valueType != null);
Contract.Requires(ownerType != null);
Contract.Requires(metadata != null);
if (name.Contains("."))
{
throw new ArgumentException("'name' may not contain periods.");
}
_initialized = new Subject();
_changed = new Subject();
_metadata = new Dictionary();
Name = name;
PropertyType = valueType;
OwnerType = ownerType;
Notifying = notifying;
Id = s_nextId++;
_metadata.Add(ownerType, metadata);
_defaultMetadata = metadata;
}
///
/// Initializes a new instance of the class.
///
/// The direct property to copy.
/// The new owner type.
/// Optional overridden metadata.
protected AvaloniaProperty(
AvaloniaProperty source,
Type ownerType,
PropertyMetadata metadata)
{
Contract.Requires(source != null);
Contract.Requires(ownerType != null);
_initialized = source._initialized;
_changed = source._changed;
_metadata = new Dictionary();
Name = source.Name;
PropertyType = source.PropertyType;
OwnerType = ownerType;
Notifying = source.Notifying;
Id = source.Id;
_defaultMetadata = source._defaultMetadata;
// Properties that have different owner can't use fast path for metadata.
_hasMetadataOverrides = true;
if (metadata != null)
{
_metadata.Add(ownerType, metadata);
}
}
///
/// Gets the name of the property.
///
public string Name { get; }
///
/// Gets the type of the property's value.
///
public Type PropertyType { get; }
///
/// Gets the type of the class that registered the property.
///
public Type OwnerType { get; }
///
/// Gets a value indicating whether the property inherits its value.
///
public virtual bool Inherits => false;
///
/// Gets a value indicating whether this is an attached property.
///
public virtual bool IsAttached => false;
///
/// Gets a value indicating whether this is a direct property.
///
public virtual bool IsDirect => false;
///
/// Gets a value indicating whether this is a readonly property.
///
public virtual bool IsReadOnly => false;
///
/// Gets an observable that is fired when this property is initialized on a
/// new instance.
///
///
/// This observable is fired each time a new is constructed
/// for all properties registered on the object's type. The default value of the property
/// for the object is passed in the args' NewValue (OldValue will always be
/// .
///
///
/// An observable that is fired when this property is initialized on a new
/// instance.
///
public IObservable Initialized => _initialized;
///
/// Gets an observable that is fired when this property changes on any
/// instance.
///
///
/// An observable that is fired when this property changes on any
/// instance.
///
public IObservable Changed => _changed;
///
/// Gets a method that gets called before and after the property starts being notified on an
/// object.
///
///
/// When a property changes, change notifications are sent to all property subscribers;
/// for example via the observable and and the
/// event. If this callback is set for a property,
/// then it will be called before and after these notifications take place. The bool argument
/// will be true before the property change notifications are sent and false afterwards. This
/// callback is intended to support Control.IsDataContextChanging.
///
public Action Notifying { get; }
///
/// Gets the integer ID that represents this property.
///
internal int Id { get; }
internal bool HasChangedSubscriptions => _changed?.HasObservers ?? false;
///
/// Provides access to a property's binding via the
/// indexer.
///
/// The property.
/// A describing the binding.
public static IndexerDescriptor operator !(AvaloniaProperty property)
{
return new IndexerDescriptor
{
Priority = BindingPriority.LocalValue,
Property = property,
};
}
///
/// Provides access to a property's template binding via the
/// indexer.
///
/// The property.
/// A describing the binding.
public static IndexerDescriptor operator ~(AvaloniaProperty property)
{
return new IndexerDescriptor
{
Priority = BindingPriority.TemplatedParent,
Property = property,
};
}
///
/// Tests two s for equality.
///
/// The first property.
/// The second property.
/// True if the properties are equal, otherwise false.
public static bool operator ==(AvaloniaProperty a, AvaloniaProperty b)
{
if (object.ReferenceEquals(a, b))
{
return true;
}
else if (((object)a == null) || ((object)b == null))
{
return false;
}
else
{
return a.Equals(b);
}
}
///
/// Tests two s for inequality.
///
/// The first property.
/// The second property.
/// True if the properties are equal, otherwise false.
public static bool operator !=(AvaloniaProperty a, AvaloniaProperty b)
{
return !(a == b);
}
///
/// Registers a .
///
/// The type of the class that is registering the property.
/// The type of the property's value.
/// The name of the property.
/// The default value of the property.
/// Whether the property inherits its value.
/// The default binding mode for the property.
///
/// A method that gets called before and after the property starts being notified on an
/// object; the bool argument will be true before and false afterwards. This callback is
/// intended to support IsDataContextChanging.
///
/// A
public static StyledProperty Register(
string name,
TValue defaultValue = default(TValue),
bool inherits = false,
BindingMode defaultBindingMode = BindingMode.OneWay,
Action notifying = null)
where TOwner : IAvaloniaObject
{
Contract.Requires(name != null);
var metadata = new StyledPropertyMetadata(
defaultValue,
defaultBindingMode: defaultBindingMode);
var result = new StyledProperty(
name,
typeof(TOwner),
metadata,
inherits,
notifying);
AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
return result;
}
///
/// Registers an attached .
///
/// The type of the class that is registering the property.
/// The type of the class that the property is to be registered on.
/// The type of the property's value.
/// The name of the property.
/// The default value of the property.
/// Whether the property inherits its value.
/// The default binding mode for the property.
/// A
public static AttachedProperty RegisterAttached(
string name,
TValue defaultValue = default(TValue),
bool inherits = false,
BindingMode defaultBindingMode = BindingMode.OneWay,
Func validate = null)
where THost : IAvaloniaObject
{
Contract.Requires(name != null);
var metadata = new StyledPropertyMetadata(
defaultValue,
defaultBindingMode: defaultBindingMode);
var result = new AttachedProperty(name, typeof(TOwner), metadata, inherits);
var registry = AvaloniaPropertyRegistry.Instance;
registry.Register(typeof(TOwner), result);
registry.RegisterAttached(typeof(THost), result);
return result;
}
///
/// Registers an attached .
///
/// The type of the class that the property is to be registered on.
/// The type of the property's value.
/// The name of the property.
/// The type of the class that is registering the property.
/// The default value of the property.
/// Whether the property inherits its value.
/// The default binding mode for the property.
/// A
public static AttachedProperty RegisterAttached(
string name,
Type ownerType,
TValue defaultValue = default(TValue),
bool inherits = false,
BindingMode defaultBindingMode = BindingMode.OneWay,
Func validate = null)
where THost : IAvaloniaObject
{
Contract.Requires(name != null);
var metadata = new StyledPropertyMetadata(
defaultValue,
defaultBindingMode: defaultBindingMode);
var result = new AttachedProperty(name, ownerType, metadata, inherits);
var registry = AvaloniaPropertyRegistry.Instance;
registry.Register(ownerType, result);
registry.RegisterAttached(typeof(THost), result);
return result;
}
///
/// Registers a direct .
///
/// The type of the class that is registering the property.
/// The type of the property's value.
/// The name of the property.
/// Gets the current value of the property.
/// Sets the value of the property.
/// The value to use when the property is cleared.
/// The default binding mode for the property.
///
/// Whether the property is interested in data validation.
///
/// A
public static DirectProperty RegisterDirect(
string name,
Func getter,
Action setter = null,
TValue unsetValue = default(TValue),
BindingMode defaultBindingMode = BindingMode.OneWay,
bool enableDataValidation = false)
where TOwner : IAvaloniaObject
{
Contract.Requires(name != null);
Contract.Requires(getter != null);
var metadata = new DirectPropertyMetadata(
unsetValue: unsetValue,
defaultBindingMode: defaultBindingMode);
var result = new DirectProperty(
name,
getter,
setter,
metadata,
enableDataValidation);
AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
return result;
}
///
/// Returns a binding accessor that can be passed to 's []
/// operator to initiate a binding.
///
/// A .
///
/// The ! and ~ operators are short forms of this.
///
public IndexerDescriptor Bind()
{
return new IndexerDescriptor
{
Property = this,
};
}
///
public override bool Equals(object obj)
{
var p = obj as AvaloniaProperty;
return p != null && Equals(p);
}
///
public bool Equals(AvaloniaProperty other)
{
return other != null && Id == other.Id;
}
///
public override int GetHashCode()
{
return Id;
}
///
/// Gets the property metadata for the specified type.
///
/// The type.
///
/// The property metadata.
///
public PropertyMetadata GetMetadata() where T : IAvaloniaObject
{
return GetMetadata(typeof(T));
}
///
/// Gets the property metadata for the specified type.
///
/// The type.
///
/// The property metadata.
///
///
public PropertyMetadata GetMetadata(Type type)
{
if (!_hasMetadataOverrides)
{
return _defaultMetadata;
}
return GetMetadataWithOverrides(type);
}
///
/// Checks whether the is valid for the property.
///
/// The value.
/// True if the value is valid, otherwise false.
public bool IsValidValue(object value)
{
return TypeUtilities.TryConvertImplicit(PropertyType, value, out value);
}
///
/// Gets the string representation of the property.
///
/// The property's string representation.
public override string ToString()
{
return Name;
}
///
/// True if has any observers.
///
internal bool HasNotifyInitializedObservers => _initialized.HasObservers;
///
/// Notifies the observable.
///
/// The object being initialized.
internal abstract void NotifyInitialized(IAvaloniaObject o);
///
/// Notifies the observable.
///
/// The observable arguments.
internal void NotifyInitialized(AvaloniaPropertyChangedEventArgs e)
{
_initialized.OnNext(e);
}
///
/// Notifies the observable.
///
/// The observable arguments.
internal void NotifyChanged(AvaloniaPropertyChangedEventArgs e)
{
_changed.OnNext(e);
}
///
/// Routes an untyped ClearValue call to a typed call.
///
/// The object instance.
internal abstract void RouteClearValue(IAvaloniaObject o);
///
/// Routes an untyped GetValue call to a typed call.
///
/// The object instance.
internal abstract object RouteGetValue(IAvaloniaObject o);
///
/// Routes an untyped SetValue call to a typed call.
///
/// The object instance.
/// The value.
/// The priority.
internal abstract void RouteSetValue(
IAvaloniaObject o,
object value,
BindingPriority priority);
///
/// Routes an untyped Bind call to a typed call.
///
/// The object instance.
/// The binding source.
/// The priority.
internal abstract IDisposable RouteBind(
IAvaloniaObject o,
IObservable> source,
BindingPriority priority);
internal abstract void RouteInheritanceParentChanged(AvaloniaObject o, IAvaloniaObject oldParent);
///
/// Overrides the metadata for the property on the specified type.
///
/// The type.
/// The metadata.
protected void OverrideMetadata(Type type, PropertyMetadata metadata)
{
Contract.Requires(type != null);
Contract.Requires(metadata != null);
if (_metadata.ContainsKey(type))
{
throw new InvalidOperationException(
$"Metadata is already set for {Name} on {type}.");
}
var baseMetadata = GetMetadata(type);
metadata.Merge(baseMetadata, this);
_metadata.Add(type, metadata);
_metadataCache.Clear();
_hasMetadataOverrides = true;
}
private PropertyMetadata GetMetadataWithOverrides(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (_metadataCache.TryGetValue(type, out PropertyMetadata result))
{
return result;
}
Type currentType = type;
while (currentType != null)
{
if (_metadata.TryGetValue(currentType, out result))
{
_metadataCache[type] = result;
return result;
}
currentType = currentType.GetTypeInfo().BaseType;
}
_metadataCache[type] = _defaultMetadata;
return _defaultMetadata;
}
}
///
/// Class representing the .
///
public sealed class UnsetValueType
{
internal UnsetValueType() { }
///
/// Returns the string representation of the .
///
/// The string "(unset)".
public override string ToString() => "(unset)";
}
}