Data bindings - Updated to new paths API

Data bindings - Fixed profile editor behavior
This commit is contained in:
SpoinkyNL committed 2020-10-10 20:24:25 +02:00
1 parent 69ae42c039
commit 7610aeae4b
9 files changed
+264 -394

No files matched your search

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using Artemis.Storage.Entities.Profile.DataBindings;
namespace Artemis.Core
@@ -7,8 +6,6 @@ namespace Artemis.Core
/// <inheritdoc />
public class DataBinding<TLayerProperty, TProperty> : IDataBinding
{
private readonly List<DataBindingModifier<TLayerProperty, TProperty>> _modifiers = new List<DataBindingModifier<TLayerProperty, TProperty>>();
private TProperty _currentValue;
private bool _disposed;
private TimeSpan _easingProgress;
@@ -63,51 +60,9 @@ namespace Artemis.Core
/// Gets ors ets the easing function of the data binding
/// </summary>
public Easings.Functions EasingFunction { get; set; }
internal DataBindingEntity Entity { get; }
/// <summary>
/// Updates the smoothing progress of the data binding
/// </summary>
/// <param name="deltaTime">The time in seconds that passed since the last update</param>
public void Update(double deltaTime)
{
if (_disposed)
throw new ObjectDisposedException("DataBinding");
// Data bindings cannot go back in time like brushes
deltaTime = Math.Max(0, deltaTime);
_easingProgress = _easingProgress.Add(TimeSpan.FromSeconds(deltaTime));
if (_easingProgress > EasingTime)
_easingProgress = EasingTime;
}
/// <inheritdoc />
public void Apply()
{
if (_disposed)
throw new ObjectDisposedException("DataBinding");
if (Converter == null)
return;
TProperty converterValue = Converter.GetValue();
TProperty value = GetValue(converterValue);
Converter.ApplyValue(value);
}
/// <inheritdoc />
public void Dispose()
{
_disposed = true;
Registration.DataBinding = null;
DataBindingMode?.Dispose();
}
/// <summary>
/// Gets the current value of the data binding
/// </summary>
@@ -179,6 +134,46 @@ namespace Artemis.Core
return Converter.Interpolate(_previousValue, _currentValue, Easings.Interpolate(easingAmount, EasingFunction));
}
/// <summary>
/// Updates the smoothing progress of the data binding
/// </summary>
/// <param name="deltaTime">The time in seconds that passed since the last update</param>
public void Update(double deltaTime)
{
if (_disposed)
throw new ObjectDisposedException("DataBinding");
// Data bindings cannot go back in time like brushes
deltaTime = Math.Max(0, deltaTime);
_easingProgress = _easingProgress.Add(TimeSpan.FromSeconds(deltaTime));
if (_easingProgress > EasingTime)
_easingProgress = EasingTime;
}
/// <inheritdoc />
public void Apply()
{
if (_disposed)
throw new ObjectDisposedException("DataBinding");
if (Converter == null)
return;
TProperty converterValue = Converter.GetValue();
TProperty value = GetValue(converterValue);
Converter.ApplyValue(value);
}
/// <inheritdoc />
public void Dispose()
{
_disposed = true;
Registration.DataBinding = null;
DataBindingMode?.Dispose();
}
#region Mode management
/// <summary>
@@ -82,7 +82,7 @@ namespace Artemis.Core
/// <summary>
/// Converts the provided object to a type of <typeparamref name="TProperty" />
/// </summary>
public virtual TProperty ConvertFromObject(object source)
public virtual TProperty ConvertFromObject(object? source)
{
return (TProperty) Convert.ChangeType(source, typeof(TProperty));
}
@@ -1,6 +1,4 @@
using System;
using System.Linq.Expressions;
using Artemis.Core.DataModelExpansions;
using Artemis.Storage.Entities.Profile.DataBindings;
using Newtonsoft.Json;
@@ -50,14 +48,9 @@ namespace Artemis.Core
public int Order { get; set; }
/// <summary>
/// Gets the currently used instance of the parameter data model
/// Gets the path of the parameter property
/// </summary>
public DataModel ParameterDataModel { get; private set; }
/// <summary>
/// Gets the path of the parameter property in the <see cref="ParameterDataModel" />
/// </summary>
public string ParameterPropertyPath { get; private set; }
public DataModelPath? ParameterPath { get; set; }
/// <summary>
/// Gets the parameter static value, only used it <see cref="ParameterType" /> is
@@ -65,13 +58,144 @@ namespace Artemis.Core
/// </summary>
public object ParameterStaticValue { get; private set; }
/// <summary>
/// A compiled expression tree that when given a matching data model returns the value of the modifiers parameter
/// </summary>
public Func<DataModel, object> CompiledParameterAccessor { get; set; }
internal DataBindingModifierEntity Entity { get; set; }
/// <summary>
/// Applies the modifier to the provided value
/// </summary>
/// <param name="currentValue">The value to apply the modifier to, should be of the same type as the data binding target</param>
/// <returns>The modified value</returns>
public object Apply(object? currentValue)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
if (ModifierType == null)
return currentValue;
if (!ModifierType.SupportsParameter)
return ModifierType.Apply(currentValue, null);
if (ParameterType == ProfileRightSideType.Dynamic && ParameterPath != null && ParameterPath.IsValid)
{
object? value = ParameterPath.GetValue();
return ModifierType.Apply(currentValue, value);
}
if (ParameterType == ProfileRightSideType.Static)
return ModifierType.Apply(currentValue, ParameterStaticValue);
return currentValue;
}
/// <summary>
/// Updates the modifier type of the modifier and re-compiles the expression
/// </summary>
/// <param name="modifierType"></param>
public void UpdateModifierType(DataBindingModifierType modifierType)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
// Calling CreateExpression will clear compiled expressions
if (modifierType == null)
{
ModifierType = null;
return;
}
Type targetType = DirectDataBinding.DataBinding.GetTargetType();
if (!modifierType.SupportsType(targetType))
throw new ArtemisCoreException($"Cannot apply modifier type {modifierType.GetType().Name} to this modifier because " +
$"it does not support this data binding's type {targetType.Name}");
ModifierType = modifierType;
}
/// <summary>
/// Updates the parameter of the modifier and makes the modifier dynamic
/// </summary>
/// <param name="path">The path pointing to the parameter</param>
public void UpdateParameterDynamic(DataModelPath? path)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
if (path != null && !path.IsValid)
throw new ArtemisCoreException("Cannot update parameter of data binding modifier to an invalid path");
ParameterPath?.Dispose();
ParameterPath = path != null ? new DataModelPath(path) : null;
ParameterType = ProfileRightSideType.Dynamic;
}
/// <summary>
/// Updates the parameter of the modifier, makes the modifier static and re-compiles the expression
/// </summary>
/// <param name="staticValue">The static value to use as a parameter</param>
public void UpdateParameterStatic(object staticValue)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
ParameterType = ProfileRightSideType.Static;
ParameterPath?.Dispose();
ParameterPath = null;
Type parameterType = ModifierType?.ParameterType ?? DirectDataBinding.DataBinding.GetTargetType();
// If not null ensure the types match and if not, convert it
if (staticValue != null && staticValue.GetType() == parameterType)
ParameterStaticValue = staticValue;
else if (staticValue != null)
ParameterStaticValue = Convert.ChangeType(staticValue, parameterType);
// If null create a default instance for value types or simply make it null for reference types
else if (parameterType.IsValueType)
ParameterStaticValue = Activator.CreateInstance(parameterType);
else
ParameterStaticValue = null;
}
private void Initialize()
{
DataBindingModifierTypeStore.DataBindingModifierAdded += DataBindingModifierTypeStoreOnDataBindingModifierAdded;
DataBindingModifierTypeStore.DataBindingModifierRemoved += DataBindingModifierTypeStoreOnDataBindingModifierRemoved;
// Modifier type
if (Entity.ModifierTypePluginGuid != null && ModifierType == null)
{
DataBindingModifierType modifierType = DataBindingModifierTypeStore.Get(Entity.ModifierTypePluginGuid.Value, Entity.ModifierType)?.DataBindingModifierType;
if (modifierType != null)
UpdateModifierType(modifierType);
}
// Dynamic parameter
if (ParameterType == ProfileRightSideType.Dynamic && Entity.ParameterPath != null)
{
ParameterPath = new DataModelPath(null, Entity.ParameterPath);
}
// Static parameter
else if (ParameterType == ProfileRightSideType.Static && Entity.ParameterStaticValue != null && ParameterStaticValue == null)
{
// Use the target type so JSON.NET has a better idea what to do
Type parameterType = ModifierType?.ParameterType ?? DirectDataBinding.DataBinding.GetTargetType();
object staticValue;
try
{
staticValue = JsonConvert.DeserializeObject(Entity.ParameterStaticValue, parameterType);
}
// If deserialization fails, use the type's default
catch (JsonSerializationException e)
{
DeserializationLogger.LogModifierDeserializationFailure(GetType().Name, e);
staticValue = Activator.CreateInstance(parameterType);
}
UpdateParameterStatic(staticValue);
}
}
/// <inheritdoc />
public void Save()
@@ -79,6 +203,10 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
// Don't save an invalid state
if (ParameterPath != null && !ParameterPath.IsValid)
return;
if (!DirectDataBinding.Entity.Modifiers.Contains(Entity))
DirectDataBinding.Entity.Modifiers.Add(Entity);
@@ -94,11 +222,8 @@ namespace Artemis.Core
Entity.ParameterType = (int) ParameterType;
// Parameter
if (ParameterDataModel != null)
{
Entity.ParameterDataModelGuid = ParameterDataModel.PluginInfo.Guid;
Entity.ParameterPropertyPath = ParameterPropertyPath;
}
ParameterPath?.Save();
Entity.ParameterPath = ParameterPath?.Entity;
Entity.ParameterStaticValue = JsonConvert.SerializeObject(ParameterStaticValue);
}
@@ -125,186 +250,8 @@ namespace Artemis.Core
DataBindingModifierTypeStore.DataBindingModifierAdded -= DataBindingModifierTypeStoreOnDataBindingModifierAdded;
DataBindingModifierTypeStore.DataBindingModifierRemoved -= DataBindingModifierTypeStoreOnDataBindingModifierRemoved;
DataModelStore.DataModelAdded -= DataModelStoreOnDataModelAdded;
DataModelStore.DataModelRemoved -= DataModelStoreOnDataModelRemoved;
}
/// <summary>
/// Applies the modifier to the provided value
/// </summary>
/// <param name="currentValue">The value to apply the modifier to, should be of the same type as the data binding target</param>
/// <returns>The modified value</returns>
public object Apply(object currentValue)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
if (ModifierType == null)
return currentValue;
if (!ModifierType.SupportsParameter)
return ModifierType.Apply(currentValue, null);
if (ParameterType == ProfileRightSideType.Dynamic && CompiledParameterAccessor != null)
{
object value = CompiledParameterAccessor(ParameterDataModel);
return ModifierType.Apply(currentValue, value);
}
if (ParameterType == ProfileRightSideType.Static)
return ModifierType.Apply(currentValue, ParameterStaticValue);
return currentValue;
}
/// <summary>
/// Updates the modifier type of the modifier and re-compiles the expression
/// </summary>
/// <param name="modifierType"></param>
public void UpdateModifierType(DataBindingModifierType modifierType)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
// Calling CreateExpression will clear compiled expressions
if (modifierType == null)
{
ModifierType = null;
CreateExpression();
return;
}
Type targetType = DirectDataBinding.DataBinding.GetTargetType();
if (!modifierType.SupportsType(targetType))
{
throw new ArtemisCoreException($"Cannot apply modifier type {modifierType.GetType().Name} to this modifier because " +
$"it does not support this data binding's type {targetType.Name}");
}
ModifierType = modifierType;
CreateExpression();
}
/// <summary>
/// Updates the parameter of the modifier, makes the modifier dynamic and re-compiles the expression
/// </summary>
/// <param name="dataModel">The data model of the parameter</param>
/// <param name="path">The path pointing to the parameter inside the data model</param>
public void UpdateParameter(DataModel? dataModel, string? path)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
if (dataModel != null && path == null)
throw new ArtemisCoreException("If a data model is provided, a path is also required");
if (dataModel == null && path != null)
throw new ArtemisCoreException("If path is provided, a data model is also required");
if (dataModel != null)
{
if (!dataModel.ContainsPath(path))
throw new ArtemisCoreException($"Data model of type {dataModel.GetType().Name} does not contain a property at path '{path}'");
}
ParameterType = ProfileRightSideType.Dynamic;
ParameterDataModel = dataModel;
ParameterPropertyPath = path;
CreateExpression();
}
/// <summary>
/// Updates the parameter of the modifier, makes the modifier static and re-compiles the expression
/// </summary>
/// <param name="staticValue">The static value to use as a parameter</param>
public void UpdateParameter(object staticValue)
{
if (_disposed)
throw new ObjectDisposedException("DataBindingModifier");
ParameterType = ProfileRightSideType.Static;
ParameterDataModel = null;
ParameterPropertyPath = null;
Type parameterType = ModifierType?.ParameterType ?? DirectDataBinding.DataBinding.GetTargetType();
// If not null ensure the types match and if not, convert it
if (staticValue != null && staticValue.GetType() == parameterType)
ParameterStaticValue = staticValue;
else if (staticValue != null)
ParameterStaticValue = Convert.ChangeType(staticValue, parameterType);
// If null create a default instance for value types or simply make it null for reference types
else if (parameterType.IsValueType)
ParameterStaticValue = Activator.CreateInstance(parameterType);
else
ParameterStaticValue = null;
CreateExpression();
}
private void Initialize()
{
DataBindingModifierTypeStore.DataBindingModifierAdded += DataBindingModifierTypeStoreOnDataBindingModifierAdded;
DataBindingModifierTypeStore.DataBindingModifierRemoved += DataBindingModifierTypeStoreOnDataBindingModifierRemoved;
DataModelStore.DataModelAdded += DataModelStoreOnDataModelAdded;
DataModelStore.DataModelRemoved += DataModelStoreOnDataModelRemoved;
// Modifier type
if (Entity.ModifierTypePluginGuid != null && ModifierType == null)
{
DataBindingModifierType modifierType = DataBindingModifierTypeStore.Get(Entity.ModifierTypePluginGuid.Value, Entity.ModifierType)?.DataBindingModifierType;
if (modifierType != null)
UpdateModifierType(modifierType);
}
// Dynamic parameter
if (ParameterType == ProfileRightSideType.Dynamic && Entity.ParameterDataModelGuid != null && ParameterDataModel == null)
{
DataModel dataModel = DataModelStore.Get(Entity.ParameterDataModelGuid.Value)?.DataModel;
if (dataModel != null && dataModel.ContainsPath(Entity.ParameterPropertyPath))
UpdateParameter(dataModel, Entity.ParameterPropertyPath);
}
// Static parameter
else if (ParameterType == ProfileRightSideType.Static && Entity.ParameterStaticValue != null && ParameterStaticValue == null)
{
// Use the target type so JSON.NET has a better idea what to do
Type parameterType = ModifierType?.ParameterType ?? DirectDataBinding.DataBinding.GetTargetType();
object staticValue;
try
{
staticValue = JsonConvert.DeserializeObject(Entity.ParameterStaticValue, parameterType);
}
// If deserialization fails, use the type's default
catch (JsonSerializationException e)
{
DeserializationLogger.LogModifierDeserializationFailure(GetType().Name, e);
staticValue = Activator.CreateInstance(parameterType);
}
UpdateParameter(staticValue);
}
}
private void CreateExpression()
{
CompiledParameterAccessor = null;
if (ModifierType == null)
return;
if (ParameterType == ProfileRightSideType.Dynamic && ModifierType.SupportsParameter)
{
if (ParameterDataModel == null)
return;
// If the right side value is null, the constant type cannot be inferred and must be provided based on the data binding target
Expression parameterAccessor = ExpressionUtilities.CreateDataModelAccessor(
ParameterDataModel, ParameterPropertyPath, "parameter", out ParameterExpression rightSideParameter
);
Expression<Func<DataModel, object>> lambda = Expression.Lambda<Func<DataModel, object>>(Expression.Convert(parameterAccessor, typeof(object)), rightSideParameter);
CompiledParameterAccessor = lambda.Compile();
}
ParameterPath?.Dispose();
}
#region Event handlers
@@ -325,21 +272,6 @@ namespace Artemis.Core
UpdateModifierType(null);
}
private void DataModelStoreOnDataModelAdded(object sender, DataModelStoreEvent e)
{
DataModel dataModel = e.Registration.DataModel;
if (dataModel.PluginInfo.Guid == Entity.ParameterDataModelGuid && dataModel.ContainsPath(Entity.ParameterPropertyPath))
UpdateParameter(dataModel, Entity.ParameterPropertyPath);
}
private void DataModelStoreOnDataModelRemoved(object sender, DataModelStoreEvent e)
{
if (e.Registration.DataModel != ParameterDataModel)
return;
ParameterDataModel = null;
CompiledParameterAccessor = null;
}
#endregion
}
}
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Artemis.Core.DataModelExpansions;
using Artemis.Storage.Entities.Profile.DataBindings;
namespace Artemis.Core
@@ -20,31 +17,20 @@ namespace Artemis.Core
DataBinding = dataBinding;
Entity = entity;
Initialize();
Load();
}
internal DirectDataBindingEntity Entity { get; }
/// <summary>
/// Gets the currently used instance of the data model that contains the source of the data binding
/// Gets the path of the source property
/// </summary>
public DataModel SourceDataModel { get; private set; }
/// <summary>
/// Gets the path of the source property in the <see cref="SourceDataModel" />
/// </summary>
public string SourcePropertyPath { get; private set; }
public DataModelPath? SourcePath { get; private set; }
/// <summary>
/// Gets a list of modifiers applied to this data binding
/// </summary>
public IReadOnlyList<DataBindingModifier<TLayerProperty, TProperty>> Modifiers => _modifiers.AsReadOnly();
/// <summary>
/// Gets the compiled function that gets the current value of the data binding target
/// </summary>
public Func<DataModel, object> CompiledTargetAccessor { get; private set; }
internal DirectDataBindingEntity Entity { get; }
/// <inheritdoc />
public DataBinding<TLayerProperty, TProperty> DataBinding { get; }
@@ -55,10 +41,10 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("DirectDataBinding");
if (CompiledTargetAccessor == null)
if (SourcePath == null || !SourcePath.IsValid)
return baseValue;
object dataBindingValue = CompiledTargetAccessor(SourceDataModel);
object? dataBindingValue = SourcePath.GetValue();
foreach (DataBindingModifier<TLayerProperty, TProperty> dataBindingModifier in Modifiers)
dataBindingValue = dataBindingModifier.Apply(dataBindingValue);
@@ -72,11 +58,10 @@ namespace Artemis.Core
{
_disposed = true;
DataModelStore.DataModelAdded -= DataModelStoreOnDataModelAdded;
DataModelStore.DataModelRemoved -= DataModelStoreOnDataModelRemoved;
foreach (DataBindingModifier<TLayerProperty, TProperty> dataBindingModifier in Modifiers)
dataBindingModifier.Dispose();
SourcePath?.Dispose();
}
#endregion
@@ -86,7 +71,9 @@ namespace Artemis.Core
/// <inheritdoc />
public void Load()
{
// Data model is done during Initialize
// Source
if (Entity.SourcePath != null)
SourcePath = new DataModelPath(null, Entity.SourcePath);
// Modifiers
foreach (DataBindingModifierEntity dataBindingModifierEntity in Entity.Modifiers)
@@ -98,12 +85,12 @@ namespace Artemis.Core
/// <inheritdoc />
public void Save()
{
// Data model
if (SourceDataModel != null)
{
Entity.SourceDataModelGuid = SourceDataModel.PluginInfo.Guid;
Entity.SourcePropertyPath = SourcePropertyPath;
}
// Don't save an invalid state
if (SourcePath != null && !SourcePath.IsValid)
return;
SourcePath?.Save();
Entity.SourcePath = SourcePath?.Entity;
// Modifiers
Entity.Modifiers.Clear();
@@ -113,76 +100,30 @@ namespace Artemis.Core
#endregion
#region Initialization
private void Initialize()
{
DataModelStore.DataModelAdded += DataModelStoreOnDataModelAdded;
DataModelStore.DataModelRemoved += DataModelStoreOnDataModelRemoved;
// Source
if (Entity.SourceDataModelGuid != null && SourceDataModel == null)
{
DataModel dataModel = DataModelStore.Get(Entity.SourceDataModelGuid.Value)?.DataModel;
if (dataModel != null && dataModel.ContainsPath(Entity.SourcePropertyPath))
UpdateSource(dataModel, Entity.SourcePropertyPath);
}
}
private void CreateExpression()
{
Type listType = SourceDataModel.GetListTypeInPath(SourcePropertyPath);
if (listType != null)
throw new ArtemisCoreException($"Cannot create a regular accessor at path {SourcePropertyPath} because the path contains a list");
ParameterExpression parameter = Expression.Parameter(typeof(DataModel), "targetDataModel");
Expression accessor = SourcePropertyPath.Split('.').Aggregate<string, Expression>(
Expression.Convert(parameter, SourceDataModel.GetType()), // Cast to the appropriate type
Expression.Property
);
UnaryExpression returnValue = Expression.Convert(accessor, typeof(object));
Expression<Func<DataModel, object>> lambda = Expression.Lambda<Func<DataModel, object>>(returnValue, parameter);
CompiledTargetAccessor = lambda.Compile();
}
#endregion
#region Source
/// <summary>
/// Returns the type of the source property of this data binding
/// </summary>
public Type GetSourceType()
public Type? GetSourceType()
{
return SourceDataModel?.GetTypeAtPath(SourcePropertyPath);
return SourcePath?.GetPropertyType();
}
/// <summary>
/// Updates the source of the data binding and re-compiles the expression
/// Updates the source of the data binding
/// </summary>
/// <param name="dataModel">The data model of the source</param>
/// <param name="path">The path pointing to the source inside the data model</param>
public void UpdateSource(DataModel dataModel, string path)
/// <param name="path">The path pointing to the source</param>
public void UpdateSource(DataModelPath? path)
{
if (_disposed)
throw new ObjectDisposedException("DirectDataBinding");
if (dataModel != null && path == null)
throw new ArtemisCoreException("If a data model is provided, a path is also required");
if (dataModel == null && path != null)
throw new ArtemisCoreException("If path is provided, a data model is also required");
if (path != null && !path.IsValid)
throw new ArtemisCoreException("Cannot update source of data binding to an invalid path");
if (dataModel != null)
{
if (!dataModel.ContainsPath(path))
throw new ArtemisCoreException($"Data model of type {dataModel.GetType().Name} does not contain a property at path '{path}'");
}
SourceDataModel = dataModel;
SourcePropertyPath = path;
CreateExpression();
SourcePath?.Dispose();
SourcePath = path != null ? new DataModelPath(path) : null;
}
#endregion
@@ -239,31 +180,12 @@ namespace Artemis.Core
#endregion
#region Event handlers
private void DataModelStoreOnDataModelAdded(object sender, DataModelStoreEvent e)
{
DataModel dataModel = e.Registration.DataModel;
if (dataModel.PluginInfo.Guid == Entity.SourceDataModelGuid && dataModel.ContainsPath(Entity.SourcePropertyPath))
UpdateSource(dataModel, Entity.SourcePropertyPath);
}
private void DataModelStoreOnDataModelRemoved(object sender, DataModelStoreEvent e)
{
if (SourceDataModel != e.Registration.DataModel)
return;
SourceDataModel = null;
CompiledTargetAccessor = null;
}
#endregion
#region Events
/// <summary>
/// Occurs when a modifier is added or removed
/// </summary>
public event EventHandler ModifiersUpdated;
public event EventHandler? ModifiersUpdated;
protected virtual void OnModifiersUpdated()
{