1
0
mirror of https://github.com/Artemis-RGB/Artemis synced 2025-12-13 05:48:35 +00:00

Darthified code

This commit is contained in:
SpoinkyNL 2020-10-05 22:50:29 +02:00
parent 5b80c1e4fe
commit ae64db8a13
198 changed files with 1339 additions and 1305 deletions

View File

@ -12,8 +12,8 @@ namespace Artemis.Core.DefaultTypes
public override bool Evaluate(object a, object b)
{
var aString = (string) a;
var bString = (string) b;
string aString = (string) a;
string bString = (string) b;
return bString != null && aString != null && aString.Contains(bString, StringComparison.InvariantCultureIgnoreCase);
}

View File

@ -12,8 +12,8 @@ namespace Artemis.Core.DefaultTypes
public override bool Evaluate(object a, object b)
{
var aString = (string) a;
var bString = (string) b;
string aString = (string) a;
string bString = (string) b;
return bString != null && aString != null && aString.EndsWith(bString, StringComparison.InvariantCultureIgnoreCase);
}

View File

@ -12,8 +12,8 @@ namespace Artemis.Core.DefaultTypes
public override bool Evaluate(object a, object b)
{
var aString = (string) a;
var bString = (string) b;
string aString = (string) a;
string bString = (string) b;
return string.Equals(aString, bString, StringComparison.InvariantCultureIgnoreCase);
}

View File

@ -12,8 +12,8 @@ namespace Artemis.Core.DefaultTypes
public override bool Evaluate(object a, object b)
{
var aString = (string) a;
var bString = (string) b;
string aString = (string) a;
string bString = (string) b;
return bString != null && aString != null && !aString.Contains(bString, StringComparison.InvariantCultureIgnoreCase);
}

View File

@ -12,8 +12,8 @@ namespace Artemis.Core.DefaultTypes
public override bool Evaluate(object a, object b)
{
var aString = (string) a;
var bString = (string) b;
string aString = (string) a;
string bString = (string) b;
return !string.Equals(aString, bString, StringComparison.InvariantCultureIgnoreCase);
}

View File

@ -12,8 +12,8 @@ namespace Artemis.Core.DefaultTypes
public override bool Evaluate(object a, object b)
{
var aString = (string) a;
var bString = (string) b;
string aString = (string) a;
string bString = (string) b;
return bString != null && aString != null && aString.StartsWith(bString, StringComparison.InvariantCultureIgnoreCase);
}

View File

@ -29,7 +29,7 @@ namespace Artemis.Core.DefaultTypes
/// <inheritdoc />
public override float Interpolate(float a, float b, double progress)
{
var diff = b - a;
float diff = b - a;
return (float) (a + diff * progress);
}

View File

@ -34,7 +34,7 @@ namespace Artemis.Core.DefaultTypes
/// <inheritdoc />
public override int Interpolate(int a, int b, double progress)
{
var diff = b - a;
int diff = b - a;
return (int) Math.Round(a + diff * progress, InterpolationRoundingMode);
}
}

View File

@ -15,7 +15,7 @@ namespace Artemis.Core.DefaultTypes
public override object Apply(object currentValue, object parameterValue)
{
((SKColor) currentValue).ToHsl(out var h, out var s, out var l);
((SKColor) currentValue).ToHsl(out float h, out float s, out float l);
l *= (Convert.ToSingle(parameterValue) + 100f) / 100f;
return SKColor.FromHsl(h, s, l);

View File

@ -15,7 +15,7 @@ namespace Artemis.Core.DefaultTypes
public override object Apply(object currentValue, object parameterValue)
{
((SKColor) currentValue).ToHsl(out var h, out var s, out var l);
((SKColor) currentValue).ToHsl(out float h, out float s, out float l);
l *= (Convert.ToSingle(parameterValue) * -1 + 100f) / 100f;
return SKColor.FromHsl(h, s, l);
}

View File

@ -13,7 +13,7 @@ namespace Artemis.Core.DefaultTypes
public override object Apply(object currentValue, object parameterValue)
{
var parameter = Convert.ToSingle(parameterValue);
float parameter = Convert.ToSingle(parameterValue);
// Ye ye none of that
if (parameter == 0)
return 0;

View File

@ -14,7 +14,7 @@ namespace Artemis.Core.DefaultTypes
public override object Apply(object currentValue, object parameterValue)
{
var parameter = Convert.ToSingle(parameterValue);
float parameter = Convert.ToSingle(parameterValue);
// Ye ye none of that
if (parameter == 0f)
return 100f;

View File

@ -15,7 +15,7 @@ namespace Artemis.Core.DefaultTypes
public override object Apply(object currentValue, object parameterValue)
{
var floatValue = Convert.ToSingle(currentValue);
float floatValue = Convert.ToSingle(currentValue);
return Math.Ceiling(floatValue);
}
}

View File

@ -15,7 +15,7 @@ namespace Artemis.Core.DefaultTypes
public override object Apply(object currentValue, object parameterValue)
{
var floatValue = Convert.ToSingle(currentValue);
float floatValue = Convert.ToSingle(currentValue);
return Math.Floor(floatValue);
}
}

View File

@ -15,7 +15,7 @@ namespace Artemis.Core.DefaultTypes
public override object Apply(object currentValue, object parameterValue)
{
var floatValue = Convert.ToSingle(currentValue);
float floatValue = Convert.ToSingle(currentValue);
return Math.Round(floatValue, MidpointRounding.AwayFromZero);
}
}

View File

@ -27,7 +27,7 @@
/// <inheritdoc />
protected override void UpdateCurrentValue(float keyframeProgress, float keyframeProgressEased)
{
var diff = NextKeyframe.Value - CurrentKeyframe.Value;
float diff = NextKeyframe.Value - CurrentKeyframe.Value;
CurrentValue = CurrentKeyframe.Value + diff * keyframeProgressEased;
}
}

View File

@ -37,7 +37,7 @@ namespace Artemis.Core.DefaultTypes
/// <inheritdoc />
protected override void UpdateCurrentValue(float keyframeProgress, float keyframeProgressEased)
{
var diff = NextKeyframe.Value - CurrentKeyframe.Value;
int diff = NextKeyframe.Value - CurrentKeyframe.Value;
CurrentValue = (int) Math.Round(CurrentKeyframe.Value + diff * keyframeProgressEased, MidpointRounding.AwayFromZero);
}
}

View File

@ -22,8 +22,8 @@ namespace Artemis.Core.DefaultTypes
/// <inheritdoc />
protected override void UpdateCurrentValue(float keyframeProgress, float keyframeProgressEased)
{
var xDiff = NextKeyframe.Value.X - CurrentKeyframe.Value.X;
var yDiff = NextKeyframe.Value.Y - CurrentKeyframe.Value.Y;
float xDiff = NextKeyframe.Value.X - CurrentKeyframe.Value.X;
float yDiff = NextKeyframe.Value.Y - CurrentKeyframe.Value.Y;
CurrentValue = new SKPoint(CurrentKeyframe.Value.X + xDiff * keyframeProgressEased, CurrentKeyframe.Value.Y + yDiff * keyframeProgressEased);
}
}

View File

@ -22,8 +22,8 @@ namespace Artemis.Core.DefaultTypes
/// <inheritdoc />
protected override void UpdateCurrentValue(float keyframeProgress, float keyframeProgressEased)
{
var widthDiff = NextKeyframe.Value.Width - CurrentKeyframe.Value.Width;
var heightDiff = NextKeyframe.Value.Height - CurrentKeyframe.Value.Height;
float widthDiff = NextKeyframe.Value.Width - CurrentKeyframe.Value.Width;
float heightDiff = NextKeyframe.Value.Height - CurrentKeyframe.Value.Height;
CurrentValue = new SKSize(CurrentKeyframe.Value.Width + widthDiff * keyframeProgressEased, CurrentKeyframe.Value.Height + heightDiff * keyframeProgressEased);
}
}

View File

@ -6,9 +6,9 @@ namespace Artemis.Core
{
public static void CopyFilesRecursively(this DirectoryInfo source, DirectoryInfo target)
{
foreach (var dir in source.GetDirectories())
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (var file in source.GetFiles())
foreach (FileInfo file in source.GetFiles())
file.CopyTo(Path.Combine(target.FullName, file.Name));
}
@ -17,10 +17,10 @@ namespace Artemis.Core
if (!baseDir.Exists)
return;
foreach (var dir in baseDir.EnumerateDirectories())
foreach (DirectoryInfo dir in baseDir.EnumerateDirectories())
DeleteRecursively(dir);
var files = baseDir.GetFiles();
foreach (var file in files)
FileInfo[] files = baseDir.GetFiles();
foreach (FileInfo file in files)
{
file.IsReadOnly = false;
file.Delete();

View File

@ -80,8 +80,8 @@ namespace Artemis.Core
IEnumerable<TSource> _()
{
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
yield return element;

View File

@ -9,9 +9,9 @@ namespace Artemis.Core
{
public static string GetProcessFilename(this Process p)
{
var capacity = 2000;
var builder = new StringBuilder(capacity);
var ptr = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, p.Id);
int capacity = 2000;
StringBuilder builder = new StringBuilder(capacity);
IntPtr ptr = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, p.Id);
if (!QueryFullProcessImageName(ptr, 0, builder, ref capacity)) return string.Empty;
return builder.ToString();

View File

@ -7,7 +7,7 @@ namespace Artemis.Core
{
public static string GetDeviceIdentifier(this IRGBDevice rgbDevice)
{
var builder = new StringBuilder();
StringBuilder builder = new StringBuilder();
builder.Append(rgbDevice.DeviceInfo.DeviceName);
builder.Append('-');
builder.Append(rgbDevice.DeviceInfo.Manufacturer);

View File

@ -14,10 +14,10 @@ namespace Artemis.Core
public static SKColor Interpolate(this SKColor from, SKColor to, float progress)
{
var redDiff = to.Red - from.Red;
var greenDiff = to.Green - from.Green;
var blueDiff = to.Blue - from.Blue;
var alphaDiff = to.Alpha - from.Alpha;
int redDiff = to.Red - from.Red;
int greenDiff = to.Green - from.Green;
int blueDiff = to.Blue - from.Blue;
int alphaDiff = to.Alpha - from.Alpha;
return new SKColor(
ClampToByte(from.Red + redDiff * progress),

View File

@ -78,7 +78,7 @@ namespace Artemis.Core
return true;
if (PrimitiveTypeConversions.ContainsKey(to) && PrimitiveTypeConversions[to].Contains(from))
return true;
var castable = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
bool castable = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Any(
m => m.ReturnType == to &&
(m.Name == "op_Implicit" ||

View File

@ -37,10 +37,10 @@ namespace Artemis.Core
if (timesToRepeat == 0)
return Stops.OrderBy(c => c.Position).Select(c => c.Color).ToArray();
var colors = Stops.OrderBy(c => c.Position).Select(c => c.Color).ToList();
var result = new List<SKColor>();
List<SKColor> colors = Stops.OrderBy(c => c.Position).Select(c => c.Color).ToList();
List<SKColor> result = new List<SKColor>();
for (var i = 0; i <= timesToRepeat; i++)
for (int i = 0; i <= timesToRepeat; i++)
result.AddRange(colors);
return result.ToArray();
@ -60,13 +60,13 @@ namespace Artemis.Core
return Stops.OrderBy(c => c.Position).Select(c => c.Position).ToArray();
// Create stops and a list of divided stops
var stops = Stops.OrderBy(c => c.Position).Select(c => c.Position / (timesToRepeat + 1)).ToList();
var result = new List<float>();
List<float> stops = Stops.OrderBy(c => c.Position).Select(c => c.Position / (timesToRepeat + 1)).ToList();
List<float> result = new List<float>();
// For each repeat cycle, add the base stops to the end result
for (var i = 0; i <= timesToRepeat; i++)
for (int i = 0; i <= timesToRepeat; i++)
{
var localStops = stops.Select(s => s + result.LastOrDefault()).ToList();
List<float> localStops = stops.Select(s => s + result.LastOrDefault()).ToList();
result.AddRange(localStops);
}
@ -90,11 +90,11 @@ namespace Artemis.Core
if (!Stops.Any())
return SKColor.Empty;
var stops = Stops.OrderBy(x => x.Position).ToArray();
ColorGradientStop[] stops = Stops.OrderBy(x => x.Position).ToArray();
if (position <= 0) return stops[0].Color;
if (position >= 1) return stops[^1].Color;
ColorGradientStop left = stops[0], right = null;
foreach (var stop in stops)
foreach (ColorGradientStop stop in stops)
{
if (stop.Position >= position)
{
@ -109,10 +109,10 @@ namespace Artemis.Core
return left.Color;
position = (float) Math.Round((position - left.Position) / (right.Position - left.Position), 2);
var a = (byte) ((right.Color.Alpha - left.Color.Alpha) * position + left.Color.Alpha);
var r = (byte) ((right.Color.Red - left.Color.Red) * position + left.Color.Red);
var g = (byte) ((right.Color.Green - left.Color.Green) * position + left.Color.Green);
var b = (byte) ((right.Color.Blue - left.Color.Blue) * position + left.Color.Blue);
byte a = (byte) ((right.Color.Alpha - left.Color.Alpha) * position + left.Color.Alpha);
byte r = (byte) ((right.Color.Red - left.Color.Red) * position + left.Color.Red);
byte g = (byte) ((right.Color.Green - left.Color.Green) * position + left.Color.Green);
byte b = (byte) ((right.Color.Blue - left.Color.Blue) * position + left.Color.Blue);
return new SKColor(r, g, b, a);
}
@ -122,10 +122,10 @@ namespace Artemis.Core
/// <returns></returns>
public static ColorGradient GetUnicornBarf()
{
var gradient = new ColorGradient();
for (var i = 0; i < 9; i++)
ColorGradient gradient = new ColorGradient();
for (int i = 0; i < 9; i++)
{
var color = i != 8 ? SKColor.FromHsv(i * 32, 100, 100) : SKColor.FromHsv(0, 100, 100);
SKColor color = i != 8 ? SKColor.FromHsv(i * 32, 100, 100) : SKColor.FromHsv(0, 100, 100);
gradient.Stops.Add(new ColorGradientStop(color, 0.125f * i));
}

View File

@ -34,7 +34,7 @@ namespace Artemis.Core
Entity = entity;
BooleanOperator = (BooleanOperator) Entity.BooleanOperator;
foreach (var childEntity in Entity.Children)
foreach (DataModelConditionPartEntity childEntity in Entity.Children)
{
if (childEntity is DataModelConditionGroupEntity groupEntity)
AddChild(new DataModelConditionGroup(this, groupEntity));
@ -88,7 +88,7 @@ namespace Artemis.Core
protected override void Dispose(bool disposing)
{
_disposed = true;
foreach (var child in Children)
foreach (DataModelConditionPart child in Children)
child.Dispose();
base.Dispose(disposing);
@ -125,7 +125,7 @@ namespace Artemis.Core
Entity.Children.Clear();
Entity.Children.AddRange(Children.Select(c => c.GetEntity()));
foreach (var child in Children)
foreach (DataModelConditionPart child in Children)
child.Save();
}

View File

@ -1,5 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Artemis.Core.DataModelExpansions;
@ -97,7 +98,7 @@ namespace Artemis.Core
if (dataModel != null)
{
var listType = dataModel.GetListTypeAtPath(path);
Type listType = dataModel.GetListTypeAtPath(path);
if (listType == null)
throw new ArtemisCoreException($"Data model of type {dataModel.GetType().Name} does not contain a list at path '{path}'");
@ -130,7 +131,7 @@ namespace Artemis.Core
DataModelStore.DataModelAdded -= DataModelStoreOnDataModelAdded;
DataModelStore.DataModelRemoved -= DataModelStoreOnDataModelRemoved;
foreach (var child in Children)
foreach (DataModelConditionPart child in Children)
child.Dispose();
base.Dispose(disposing);
@ -148,7 +149,7 @@ namespace Artemis.Core
if (!(target is IList list))
return false;
var objectList = list.Cast<object>();
IEnumerable<object> objectList = list.Cast<object>();
return ListOperator switch
{
ListOperator.Any => objectList.Any(o => Children[0].EvaluateObject(o)),
@ -174,7 +175,7 @@ namespace Artemis.Core
// Children
Entity.Children.Clear();
Entity.Children.AddRange(Children.Select(c => c.GetEntity()));
foreach (var child in Children)
foreach (DataModelConditionPart child in Children)
child.Save();
}
@ -191,11 +192,11 @@ namespace Artemis.Core
return;
// Get the data model ...
var dataModel = DataModelStore.Get(Entity.ListDataModelGuid.Value)?.DataModel;
DataModel dataModel = DataModelStore.Get(Entity.ListDataModelGuid.Value)?.DataModel;
if (dataModel == null)
return;
// ... and ensure the path is valid
var listType = dataModel.GetListTypeAtPath(Entity.ListPropertyPath);
Type listType = dataModel.GetListTypeAtPath(Entity.ListPropertyPath);
if (listType == null)
return;
@ -224,14 +225,14 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("DataModelConditionList");
var parameter = Expression.Parameter(typeof(object), "listDataModel");
var accessor = ListPropertyPath.Split('.').Aggregate<string, Expression>(
ParameterExpression parameter = Expression.Parameter(typeof(object), "listDataModel");
Expression accessor = ListPropertyPath.Split('.').Aggregate<string, Expression>(
Expression.Convert(parameter, ListDataModel.GetType()),
Expression.Property
);
accessor = Expression.Convert(accessor, typeof(IList));
var lambda = Expression.Lambda<Func<object, IList>>(accessor, parameter);
Expression<Func<object, IList>> lambda = Expression.Lambda<Func<object, IList>>(accessor, parameter);
CompiledListAccessor = lambda.Compile();
}
@ -240,7 +241,7 @@ namespace Artemis.Core
private void DataModelStoreOnDataModelAdded(object sender, DataModelStoreEvent e)
{
var dataModel = e.Registration.DataModel;
DataModel dataModel = e.Registration.DataModel;
if (dataModel.PluginInfo.Guid == Entity.ListDataModelGuid && dataModel.ContainsPath(Entity.ListPropertyPath))
{
ListDataModel = dataModel;

View File

@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Artemis.Core.DataModelExpansions;
using Artemis.Storage.Entities.Profile.Abstract;
using Artemis.Storage.Entities.Profile.Conditions;
@ -171,7 +172,7 @@ namespace Artemis.Core
return;
}
var leftType = GetTypeAtInnerPath(LeftPropertyPath);
Type leftType = GetTypeAtInnerPath(LeftPropertyPath);
if (conditionOperator.SupportsType(leftType))
Operator = conditionOperator;
@ -195,11 +196,11 @@ namespace Artemis.Core
if (DataModelConditionList.ListType == null)
return false;
var parts = path.Split('.');
var current = DataModelConditionList.ListType;
foreach (var part in parts)
string[] parts = path.Split('.');
Type current = DataModelConditionList.ListType;
foreach (string part in parts)
{
var property = current.GetProperty(part);
PropertyInfo? property = current.GetProperty(part);
current = property?.PropertyType;
if (property == null)
@ -237,13 +238,13 @@ namespace Artemis.Core
if (!ListContainsInnerPath(path))
return null;
var parts = path.Split('.');
var current = DataModelConditionList.ListType;
string[] parts = path.Split('.');
Type current = DataModelConditionList.ListType;
Type result = null;
foreach (var part in parts)
foreach (string part in parts)
{
var property = current.GetProperty(part);
PropertyInfo? property = current.GetProperty(part);
current = property.PropertyType;
result = property.PropertyType;
}
@ -274,7 +275,7 @@ namespace Artemis.Core
private void ApplyParentList()
{
var current = Parent;
DataModelConditionPart current = Parent;
while (current != null)
{
@ -311,7 +312,7 @@ namespace Artemis.Core
// Operator
if (Entity.OperatorPluginGuid != null)
{
var conditionOperator = ConditionOperatorStore.Get(Entity.OperatorPluginGuid.Value, Entity.OperatorType)?.ConditionOperator;
ConditionOperator conditionOperator = ConditionOperatorStore.Get(Entity.OperatorPluginGuid.Value, Entity.OperatorType)?.ConditionOperator;
if (conditionOperator != null)
UpdateOperator(conditionOperator);
}
@ -319,7 +320,7 @@ namespace Artemis.Core
// Right side dynamic
if (PredicateType == ListRightSideType.Dynamic && Entity.RightDataModelGuid != null && Entity.RightPropertyPath != null)
{
var dataModel = DataModelStore.Get(Entity.RightDataModelGuid.Value)?.DataModel;
DataModel dataModel = DataModelStore.Get(Entity.RightDataModelGuid.Value)?.DataModel;
if (dataModel != null && dataModel.ContainsPath(Entity.RightPropertyPath))
UpdateRightSideDynamic(dataModel, Entity.RightPropertyPath);
}
@ -337,7 +338,7 @@ namespace Artemis.Core
if (LeftPropertyPath != null)
{
// Use the left side type so JSON.NET has a better idea what to do
var leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
Type leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
object rightSideValue;
try
@ -385,20 +386,20 @@ namespace Artemis.Core
if (LeftPropertyPath == null || Operator == null)
return;
var leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
Type leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
if (!Operator.SupportsType(leftSideType))
Operator = null;
}
private void ValidateRightSide()
{
var leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
Type leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
if (PredicateType == ListRightSideType.Dynamic)
{
if (RightDataModel == null)
return;
var rightSideType = RightDataModel.GetTypeAtPath(RightPropertyPath);
Type rightSideType = RightDataModel.GetTypeAtPath(RightPropertyPath);
if (!leftSideType.IsCastableFrom(rightSideType))
UpdateRightSideDynamic(null, null);
}
@ -407,7 +408,7 @@ namespace Artemis.Core
if (RightPropertyPath == null)
return;
var rightSideType = GetTypeAtInnerPath(RightPropertyPath);
Type rightSideType = GetTypeAtInnerPath(RightPropertyPath);
if (!leftSideType.IsCastableFrom(rightSideType))
UpdateRightSideDynamic(null);
}
@ -429,7 +430,7 @@ namespace Artemis.Core
return;
}
var leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
Type leftSideType = GetTypeAtInnerPath(LeftPropertyPath);
// If not null ensure the types match and if not, convert it
if (staticValue != null && staticValue.GetType() == leftSideType)
@ -449,9 +450,9 @@ namespace Artemis.Core
return;
// List accessors share the same parameter because a list always contains one item per entry
var leftSideParameter = Expression.Parameter(typeof(object), "listItem");
var leftSideAccessor = CreateListAccessor(LeftPropertyPath, leftSideParameter);
var rightSideAccessor = CreateListAccessor(RightPropertyPath, leftSideParameter);
ParameterExpression leftSideParameter = Expression.Parameter(typeof(object), "listItem");
Expression leftSideAccessor = CreateListAccessor(LeftPropertyPath, leftSideParameter);
Expression rightSideAccessor = CreateListAccessor(RightPropertyPath, leftSideParameter);
// A conversion may be required if the types differ
// This can cause issues if the DataModelConditionOperator wasn't accurate in it's supported types but that is not a concern here
@ -468,9 +469,9 @@ namespace Artemis.Core
return;
// List accessors share the same parameter because a list always contains one item per entry
var leftSideParameter = Expression.Parameter(typeof(object), "listItem");
var leftSideAccessor = CreateListAccessor(LeftPropertyPath, leftSideParameter);
var rightSideAccessor = ExpressionUtilities.CreateDataModelAccessor(RightDataModel, RightPropertyPath, "right", out var rightSideParameter);
ParameterExpression leftSideParameter = Expression.Parameter(typeof(object), "listItem");
Expression leftSideAccessor = CreateListAccessor(LeftPropertyPath, leftSideParameter);
Expression rightSideAccessor = ExpressionUtilities.CreateDataModelAccessor(RightDataModel, RightPropertyPath, "right", out ParameterExpression rightSideParameter);
// A conversion may be required if the types differ
// This can cause issues if the DataModelConditionOperator wasn't accurate in it's supported types but that is not a concern here
@ -487,8 +488,8 @@ namespace Artemis.Core
return;
// List accessors share the same parameter because a list always contains one item per entry
var leftSideParameter = Expression.Parameter(typeof(object), "listItem");
var leftSideAccessor = DataModelConditionList.IsPrimitiveList
ParameterExpression leftSideParameter = Expression.Parameter(typeof(object), "listItem");
Expression leftSideAccessor = DataModelConditionList.IsPrimitiveList
? Expression.Convert(leftSideParameter, DataModelConditionList.ListType)
: CreateListAccessor(LeftPropertyPath, leftSideParameter);
@ -523,7 +524,7 @@ namespace Artemis.Core
private void DataModelStoreOnDataModelAdded(object sender, DataModelStoreEvent e)
{
var dataModel = e.Registration.DataModel;
DataModel dataModel = e.Registration.DataModel;
if (dataModel.PluginInfo.Guid == Entity.RightDataModelGuid && dataModel.ContainsPath(Entity.RightPropertyPath))
UpdateRightSideDynamic(dataModel, Entity.RightPropertyPath);
}
@ -539,7 +540,7 @@ namespace Artemis.Core
private void ConditionOperatorStoreOnConditionOperatorAdded(object sender, ConditionOperatorStoreEvent e)
{
var conditionOperator = e.Registration.ConditionOperator;
ConditionOperator conditionOperator = e.Registration.ConditionOperator;
if (Entity.OperatorPluginGuid == conditionOperator.PluginInfo.Guid && Entity.OperatorType == conditionOperator.GetType().Name)
UpdateOperator(conditionOperator);
}

View File

@ -147,7 +147,7 @@ namespace Artemis.Core
return;
}
var leftSideType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
Type leftSideType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
// If not null ensure the types match and if not, convert it
if (staticValue != null && staticValue.GetType() == leftSideType)
@ -184,7 +184,7 @@ namespace Artemis.Core
return;
}
var leftType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
Type leftType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
if (!conditionOperator.SupportsType(leftType))
{
throw new ArtemisCoreException($"Cannot apply operator {conditionOperator.GetType().Name} to this predicate because " +
@ -204,7 +204,7 @@ namespace Artemis.Core
// Compare with a static value
if (PredicateType == ProfileRightSideType.Static)
{
var leftSideValue = LeftSideAccessor(LeftDataModel);
object leftSideValue = LeftSideAccessor(LeftDataModel);
if (leftSideValue.GetType().IsValueType && RightStaticValue == null)
return false;
@ -256,7 +256,7 @@ namespace Artemis.Core
// Left side
if (Entity.LeftDataModelGuid != null)
{
var dataModel = DataModelStore.Get(Entity.LeftDataModelGuid.Value)?.DataModel;
DataModel dataModel = DataModelStore.Get(Entity.LeftDataModelGuid.Value)?.DataModel;
if (dataModel != null && dataModel.ContainsPath(Entity.LeftPropertyPath))
UpdateLeftSide(dataModel, Entity.LeftPropertyPath);
}
@ -264,7 +264,7 @@ namespace Artemis.Core
// Operator
if (Entity.OperatorPluginGuid != null)
{
var conditionOperator = ConditionOperatorStore.Get(Entity.OperatorPluginGuid.Value, Entity.OperatorType)?.ConditionOperator;
ConditionOperator conditionOperator = ConditionOperatorStore.Get(Entity.OperatorPluginGuid.Value, Entity.OperatorType)?.ConditionOperator;
if (conditionOperator != null)
UpdateOperator(conditionOperator);
}
@ -272,7 +272,7 @@ namespace Artemis.Core
// Right side dynamic
if (PredicateType == ProfileRightSideType.Dynamic && Entity.RightDataModelGuid != null)
{
var dataModel = DataModelStore.Get(Entity.RightDataModelGuid.Value)?.DataModel;
DataModel dataModel = DataModelStore.Get(Entity.RightDataModelGuid.Value)?.DataModel;
if (dataModel != null && dataModel.ContainsPath(Entity.RightPropertyPath))
UpdateRightSide(dataModel, Entity.RightPropertyPath);
}
@ -284,7 +284,7 @@ namespace Artemis.Core
if (LeftDataModel != null)
{
// Use the left side type so JSON.NET has a better idea what to do
var leftSideType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
Type leftSideType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
object rightSideValue;
try
@ -336,20 +336,20 @@ namespace Artemis.Core
if (LeftDataModel == null || Operator == null)
return;
var leftType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
Type leftType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
if (!Operator.SupportsType(leftType))
Operator = null;
}
private void ValidateRightSide()
{
var leftSideType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
Type leftSideType = LeftDataModel.GetTypeAtPath(LeftPropertyPath);
if (PredicateType == ProfileRightSideType.Dynamic)
{
if (RightDataModel == null)
return;
var rightSideType = RightDataModel.GetTypeAtPath(RightPropertyPath);
Type rightSideType = RightDataModel.GetTypeAtPath(RightPropertyPath);
if (!leftSideType.IsCastableFrom(rightSideType))
UpdateRightSide(null, null);
}
@ -367,8 +367,8 @@ namespace Artemis.Core
if (LeftDataModel == null || RightDataModel == null || Operator == null)
return;
var leftSideAccessor = ExpressionUtilities.CreateDataModelAccessor(LeftDataModel, LeftPropertyPath, "left", out var leftSideParameter);
var rightSideAccessor = ExpressionUtilities.CreateDataModelAccessor(RightDataModel, RightPropertyPath, "right", out var rightSideParameter);
Expression leftSideAccessor = ExpressionUtilities.CreateDataModelAccessor(LeftDataModel, LeftPropertyPath, "left", out ParameterExpression leftSideParameter);
Expression rightSideAccessor = ExpressionUtilities.CreateDataModelAccessor(RightDataModel, RightPropertyPath, "right", out ParameterExpression rightSideParameter);
// A conversion may be required if the types differ
// This can cause issues if the DataModelConditionOperator wasn't accurate in it's supported types but that is not a concern here
@ -384,8 +384,8 @@ namespace Artemis.Core
if (LeftDataModel == null || Operator == null)
return;
var leftSideAccessor = Expression.Convert(
ExpressionUtilities.CreateDataModelAccessor(LeftDataModel, LeftPropertyPath, "left", out var leftSideParameter),
UnaryExpression leftSideAccessor = Expression.Convert(
ExpressionUtilities.CreateDataModelAccessor(LeftDataModel, LeftPropertyPath, "left", out ParameterExpression leftSideParameter),
typeof(object)
);
@ -402,7 +402,7 @@ namespace Artemis.Core
private void DataModelStoreOnDataModelAdded(object sender, DataModelStoreEvent e)
{
var dataModel = e.Registration.DataModel;
DataModel dataModel = e.Registration.DataModel;
if (dataModel.PluginInfo.Guid == Entity.LeftDataModelGuid && dataModel.ContainsPath(Entity.LeftPropertyPath))
UpdateLeftSide(dataModel, Entity.LeftPropertyPath);
if (dataModel.PluginInfo.Guid == Entity.RightDataModelGuid && dataModel.ContainsPath(Entity.RightPropertyPath))
@ -426,7 +426,7 @@ namespace Artemis.Core
private void ConditionOperatorStoreOnConditionOperatorAdded(object sender, ConditionOperatorStoreEvent e)
{
var conditionOperator = e.Registration.ConditionOperator;
ConditionOperator conditionOperator = e.Registration.ConditionOperator;
if (Entity.OperatorPluginGuid == conditionOperator.PluginInfo.Guid && Entity.OperatorType == conditionOperator.GetType().Name)
UpdateOperator(conditionOperator);
}

View File

@ -93,8 +93,8 @@ namespace Artemis.Core
if (Converter == null)
return;
var converterValue = Converter.GetValue();
var value = GetValue(converterValue);
TProperty converterValue = Converter.GetValue();
TProperty value = GetValue(converterValue);
Converter.ApplyValue(value);
}
@ -121,7 +121,7 @@ namespace Artemis.Core
if (Converter == null || DataBindingMode == null)
return baseValue;
var value = DataBindingMode.GetValue(baseValue);
TProperty value = DataBindingMode.GetValue(baseValue);
// If no easing is to be applied simple return whatever the current value is
if (EasingTime == TimeSpan.Zero || !Converter.SupportsInterpolate)
@ -175,7 +175,7 @@ namespace Artemis.Core
if (_easingProgress == EasingTime || !Converter.SupportsInterpolate)
return _currentValue;
var easingAmount = _easingProgress.TotalSeconds / EasingTime.TotalSeconds;
double easingAmount = _easingProgress.TotalSeconds / EasingTime.TotalSeconds;
return Converter.Interpolate(_previousValue, _currentValue, Easings.Interpolate(easingAmount, EasingFunction));
}
@ -229,7 +229,7 @@ namespace Artemis.Core
throw new ObjectDisposedException("DataBinding");
// General
var registration = LayerProperty.GetDataBindingRegistration<TProperty>(Entity.TargetExpression);
DataBindingRegistration<TLayerProperty, TProperty> registration = LayerProperty.GetDataBindingRegistration<TProperty>(Entity.TargetExpression);
if (registration != null)
ApplyRegistration(registration);

View File

@ -130,43 +130,43 @@ namespace Artemis.Core
private void CreateSetReferenceTypeExpression()
{
var propertyValue = Expression.Parameter(typeof(TProperty), "propertyValue");
var parameter = Expression.Parameter(typeof(TLayerProperty), "currentValue");
var memberAccess = Expression.MakeMemberAccess(parameter, DataBinding.Registration.Member);
var assignment = Expression.Assign(memberAccess, propertyValue);
var referenceTypeLambda = Expression.Lambda<Action<TLayerProperty, TProperty>>(assignment, parameter, propertyValue);
ParameterExpression propertyValue = Expression.Parameter(typeof(TProperty), "propertyValue");
ParameterExpression parameter = Expression.Parameter(typeof(TLayerProperty), "currentValue");
MemberExpression memberAccess = Expression.MakeMemberAccess(parameter, DataBinding.Registration.Member);
BinaryExpression assignment = Expression.Assign(memberAccess, propertyValue);
Expression<Action<TLayerProperty, TProperty>> referenceTypeLambda = Expression.Lambda<Action<TLayerProperty, TProperty>>(assignment, parameter, propertyValue);
ReferenceTypeSetExpression = referenceTypeLambda.Compile();
}
private void CreateSetValueTypeExpression()
{
var propertyValue = Expression.Parameter(typeof(TProperty), "propertyValue");
var variableCurrent = Expression.Variable(typeof(TLayerProperty), "current");
var layerProperty = Expression.Constant(DataBinding.LayerProperty);
var layerPropertyMemberAccess = Expression.MakeMemberAccess(layerProperty,
ParameterExpression propertyValue = Expression.Parameter(typeof(TProperty), "propertyValue");
ParameterExpression variableCurrent = Expression.Variable(typeof(TLayerProperty), "current");
ConstantExpression layerProperty = Expression.Constant(DataBinding.LayerProperty);
MemberExpression layerPropertyMemberAccess = Expression.MakeMemberAccess(layerProperty,
DataBinding.LayerProperty.GetType().GetMember(nameof(DataBinding.LayerProperty.CurrentValue))[0]);
var body = Expression.Block(
BlockExpression body = Expression.Block(
new[] {variableCurrent},
Expression.Assign(variableCurrent, layerPropertyMemberAccess),
Expression.Assign(Expression.MakeMemberAccess(variableCurrent, DataBinding.Registration.Member), propertyValue),
Expression.Assign(layerPropertyMemberAccess, variableCurrent)
);
var valueTypeLambda = Expression.Lambda<Action<TProperty>>(body, propertyValue);
Expression<Action<TProperty>> valueTypeLambda = Expression.Lambda<Action<TProperty>>(body, propertyValue);
ValueTypeSetExpression = valueTypeLambda.Compile();
}
private void CreateSetCurrentValueExpression()
{
var propertyValue = Expression.Parameter(typeof(TProperty), "propertyValue");
var layerProperty = Expression.Constant(DataBinding.LayerProperty);
var layerPropertyMemberAccess = Expression.MakeMemberAccess(layerProperty,
ParameterExpression propertyValue = Expression.Parameter(typeof(TProperty), "propertyValue");
ConstantExpression layerProperty = Expression.Constant(DataBinding.LayerProperty);
MemberExpression layerPropertyMemberAccess = Expression.MakeMemberAccess(layerProperty,
DataBinding.LayerProperty.GetType().GetMember(nameof(DataBinding.LayerProperty.CurrentValue))[0]);
var body = Expression.Assign(layerPropertyMemberAccess, propertyValue);
var lambda = Expression.Lambda<Action<TProperty>>(body, propertyValue);
BinaryExpression body = Expression.Assign(layerPropertyMemberAccess, propertyValue);
Expression<Action<TProperty>> lambda = Expression.Lambda<Action<TProperty>>(body, propertyValue);
ValueTypeSetExpression = lambda.Compile();
}
}

View File

@ -2,6 +2,7 @@
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Artemis.Storage.Entities.Profile.DataBindings;
namespace Artemis.Core
{
@ -58,7 +59,7 @@ namespace Artemis.Core
if (DataBinding != null)
return DataBinding;
var dataBinding = LayerProperty.Entity.DataBindingEntities.FirstOrDefault(e => e.TargetExpression == PropertyExpression.ToString());
DataBindingEntity dataBinding = LayerProperty.Entity.DataBindingEntities.FirstOrDefault(e => e.TargetExpression == PropertyExpression.ToString());
if (dataBinding == null)
return null;

View File

@ -36,7 +36,7 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("ConditionalDataBinding");
var condition = Conditions.FirstOrDefault(c => c.Evaluate());
DataBindingCondition<TLayerProperty, TProperty> condition = Conditions.FirstOrDefault(c => c.Evaluate());
if (condition != null)
Console.WriteLine();
return condition == null ? baseValue : condition.Value;
@ -49,7 +49,7 @@ namespace Artemis.Core
{
_disposed = true;
foreach (var dataBindingCondition in Conditions)
foreach (DataBindingCondition<TLayerProperty, TProperty> dataBindingCondition in Conditions)
dataBindingCondition.Dispose();
}
@ -66,7 +66,7 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("ConditionalDataBinding");
var condition = new DataBindingCondition<TLayerProperty, TProperty>(this);
DataBindingCondition<TLayerProperty, TProperty> condition = new DataBindingCondition<TLayerProperty, TProperty>(this);
_conditions.Add(condition);
ApplyOrder();
@ -102,9 +102,9 @@ namespace Artemis.Core
throw new ObjectDisposedException("ConditionalDataBinding");
_conditions.Sort((a, b) => a.Order.CompareTo(b.Order));
for (var index = 0; index < _conditions.Count; index++)
for (int index = 0; index < _conditions.Count; index++)
{
var condition = _conditions[index];
DataBindingCondition<TLayerProperty, TProperty> condition = _conditions[index];
condition.Order = index + 1;
}
}
@ -116,7 +116,7 @@ namespace Artemis.Core
/// <inheritdoc />
public void Load()
{
foreach (var dataBindingConditionEntity in Entity.Values)
foreach (DataBindingConditionEntity dataBindingConditionEntity in Entity.Values)
_conditions.Add(new DataBindingCondition<TLayerProperty, TProperty>(this, dataBindingConditionEntity));
ApplyOrder();
@ -126,7 +126,7 @@ namespace Artemis.Core
public void Save()
{
Entity.Values.Clear();
foreach (var dataBindingCondition in Conditions)
foreach (DataBindingCondition<TLayerProperty, TProperty> dataBindingCondition in Conditions)
dataBindingCondition.Save();
}

View File

@ -147,7 +147,7 @@ namespace Artemis.Core
if (ParameterType == ProfileRightSideType.Dynamic && CompiledParameterAccessor != null)
{
var value = CompiledParameterAccessor(ParameterDataModel);
object value = CompiledParameterAccessor(ParameterDataModel);
return ModifierType.Apply(currentValue, value);
}
@ -174,7 +174,7 @@ namespace Artemis.Core
return;
}
var targetType = DirectDataBinding.DataBinding.GetTargetType();
Type targetType = DirectDataBinding.DataBinding.GetTargetType();
if (!modifierType.SupportsType(targetType))
{
throw new ArtemisCoreException($"Cannot apply modifier type {modifierType.GetType().Name} to this modifier because " +
@ -226,7 +226,7 @@ namespace Artemis.Core
ParameterDataModel = null;
ParameterPropertyPath = null;
var parameterType = ModifierType?.ParameterType ?? DirectDataBinding.DataBinding.GetTargetType();
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)
@ -252,7 +252,7 @@ namespace Artemis.Core
// Modifier type
if (Entity.ModifierTypePluginGuid != null && ModifierType == null)
{
var modifierType = DataBindingModifierTypeStore.Get(Entity.ModifierTypePluginGuid.Value, Entity.ModifierType)?.DataBindingModifierType;
DataBindingModifierType modifierType = DataBindingModifierTypeStore.Get(Entity.ModifierTypePluginGuid.Value, Entity.ModifierType)?.DataBindingModifierType;
if (modifierType != null)
UpdateModifierType(modifierType);
}
@ -260,7 +260,7 @@ namespace Artemis.Core
// Dynamic parameter
if (ParameterType == ProfileRightSideType.Dynamic && Entity.ParameterDataModelGuid != null && ParameterDataModel == null)
{
var dataModel = DataModelStore.Get(Entity.ParameterDataModelGuid.Value)?.DataModel;
DataModel dataModel = DataModelStore.Get(Entity.ParameterDataModelGuid.Value)?.DataModel;
if (dataModel != null && dataModel.ContainsPath(Entity.ParameterPropertyPath))
UpdateParameter(dataModel, Entity.ParameterPropertyPath);
}
@ -268,7 +268,7 @@ namespace Artemis.Core
else if (ParameterType == ProfileRightSideType.Static && Entity.ParameterStaticValue != null && ParameterStaticValue == null)
{
// Use the target type so JSON.NET has a better idea what to do
var parameterType = ModifierType?.ParameterType ?? DirectDataBinding.DataBinding.GetTargetType();
Type parameterType = ModifierType?.ParameterType ?? DirectDataBinding.DataBinding.GetTargetType();
object staticValue;
try
@ -299,10 +299,10 @@ namespace Artemis.Core
return;
// If the right side value is null, the constant type cannot be inferred and must be provided based on the data binding target
var parameterAccessor = ExpressionUtilities.CreateDataModelAccessor(
ParameterDataModel, ParameterPropertyPath, "parameter", out var rightSideParameter
Expression parameterAccessor = ExpressionUtilities.CreateDataModelAccessor(
ParameterDataModel, ParameterPropertyPath, "parameter", out ParameterExpression rightSideParameter
);
var lambda = Expression.Lambda<Func<DataModel, object>>(Expression.Convert(parameterAccessor, typeof(object)), rightSideParameter);
Expression<Func<DataModel, object>> lambda = Expression.Lambda<Func<DataModel, object>>(Expression.Convert(parameterAccessor, typeof(object)), rightSideParameter);
CompiledParameterAccessor = lambda.Compile();
}
}
@ -314,7 +314,7 @@ namespace Artemis.Core
if (ModifierType != null)
return;
var modifierType = e.TypeRegistration.DataBindingModifierType;
DataBindingModifierType modifierType = e.TypeRegistration.DataBindingModifierType;
if (modifierType.PluginInfo.Guid == Entity.ModifierTypePluginGuid && modifierType.GetType().Name == Entity.ModifierType)
UpdateModifierType(modifierType);
}
@ -327,7 +327,7 @@ namespace Artemis.Core
private void DataModelStoreOnDataModelAdded(object sender, DataModelStoreEvent e)
{
var dataModel = e.Registration.DataModel;
DataModel dataModel = e.Registration.DataModel;
if (dataModel.PluginInfo.Guid == Entity.ParameterDataModelGuid && dataModel.ContainsPath(Entity.ParameterPropertyPath))
UpdateParameter(dataModel, Entity.ParameterPropertyPath);
}

View File

@ -58,8 +58,8 @@ namespace Artemis.Core
if (CompiledTargetAccessor == null)
return baseValue;
var dataBindingValue = CompiledTargetAccessor(SourceDataModel);
foreach (var dataBindingModifier in Modifiers)
object dataBindingValue = CompiledTargetAccessor(SourceDataModel);
foreach (DataBindingModifier<TLayerProperty, TProperty> dataBindingModifier in Modifiers)
dataBindingValue = dataBindingModifier.Apply(dataBindingValue);
return DataBinding.Converter.ConvertFromObject(dataBindingValue);
@ -75,7 +75,7 @@ namespace Artemis.Core
DataModelStore.DataModelAdded -= DataModelStoreOnDataModelAdded;
DataModelStore.DataModelRemoved -= DataModelStoreOnDataModelRemoved;
foreach (var dataBindingModifier in Modifiers)
foreach (DataBindingModifier<TLayerProperty, TProperty> dataBindingModifier in Modifiers)
dataBindingModifier.Dispose();
}
@ -89,7 +89,7 @@ namespace Artemis.Core
// Data model is done during Initialize
// Modifiers
foreach (var dataBindingModifierEntity in Entity.Modifiers)
foreach (DataBindingModifierEntity dataBindingModifierEntity in Entity.Modifiers)
_modifiers.Add(new DataBindingModifier<TLayerProperty, TProperty>(this, dataBindingModifierEntity));
ApplyOrder();
@ -107,7 +107,7 @@ namespace Artemis.Core
// Modifiers
Entity.Modifiers.Clear();
foreach (var dataBindingModifier in Modifiers)
foreach (DataBindingModifier<TLayerProperty, TProperty> dataBindingModifier in Modifiers)
dataBindingModifier.Save();
}
@ -123,7 +123,7 @@ namespace Artemis.Core
// Source
if (Entity.SourceDataModelGuid != null && SourceDataModel == null)
{
var dataModel = DataModelStore.Get(Entity.SourceDataModelGuid.Value)?.DataModel;
DataModel dataModel = DataModelStore.Get(Entity.SourceDataModelGuid.Value)?.DataModel;
if (dataModel != null && dataModel.ContainsPath(Entity.SourcePropertyPath))
UpdateSource(dataModel, Entity.SourcePropertyPath);
}
@ -131,19 +131,19 @@ namespace Artemis.Core
private void CreateExpression()
{
var listType = SourceDataModel.GetListTypeInPath(SourcePropertyPath);
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");
var parameter = Expression.Parameter(typeof(DataModel), "targetDataModel");
var accessor = SourcePropertyPath.Split('.').Aggregate<string, Expression>(
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
);
var returnValue = Expression.Convert(accessor, typeof(object));
UnaryExpression returnValue = Expression.Convert(accessor, typeof(object));
var lambda = Expression.Lambda<Func<DataModel, object>>(returnValue, parameter);
Expression<Func<DataModel, object>> lambda = Expression.Lambda<Func<DataModel, object>>(returnValue, parameter);
CompiledTargetAccessor = lambda.Compile();
}
@ -198,7 +198,7 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("DirectDataBinding");
var modifier = new DataBindingModifier<TLayerProperty, TProperty>(this, type);
DataBindingModifier<TLayerProperty, TProperty> modifier = new DataBindingModifier<TLayerProperty, TProperty>(this, type);
_modifiers.Add(modifier);
ApplyOrder();
@ -230,9 +230,9 @@ namespace Artemis.Core
public void ApplyOrder()
{
_modifiers.Sort((a, b) => a.Order.CompareTo(b.Order));
for (var index = 0; index < _modifiers.Count; index++)
for (int index = 0; index < _modifiers.Count; index++)
{
var modifier = _modifiers[index];
DataBindingModifier<TLayerProperty, TProperty> modifier = _modifiers[index];
modifier.Order = index + 1;
}
}
@ -243,7 +243,7 @@ namespace Artemis.Core
private void DataModelStoreOnDataModelAdded(object sender, DataModelStoreEvent e)
{
var dataModel = e.Registration.DataModel;
DataModel dataModel = e.Registration.DataModel;
if (dataModel.PluginInfo.Guid == Entity.SourceDataModelGuid && dataModel.ContainsPath(Entity.SourcePropertyPath))
UpdateSource(dataModel, Entity.SourcePropertyPath);
}

View File

@ -119,12 +119,12 @@ namespace Artemis.Core
if (IsStartSegment)
return null;
var propertyInfo = GetPropertyInfo();
PropertyInfo propertyInfo = GetPropertyInfo();
if (propertyInfo == null)
return null;
// Static types may have one as an attribute
var attribute = (DataModelPropertyAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(DataModelPropertyAttribute));
DataModelPropertyAttribute attribute = (DataModelPropertyAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(DataModelPropertyAttribute));
if (attribute != null)
{
if (string.IsNullOrWhiteSpace(attribute.Name))
@ -145,12 +145,12 @@ namespace Artemis.Core
return DataModelPath.Target.GetType();
// Prefer basing the type on the property info
var propertyInfo = GetPropertyInfo();
var type = propertyInfo?.PropertyType;
PropertyInfo propertyInfo = GetPropertyInfo();
Type type = propertyInfo?.PropertyType;
// Property info is not available on dynamic paths though, so fall back on the current value
if (propertyInfo == null)
{
var currentValue = GetValue();
object currentValue = GetValue();
if (currentValue != null)
type = currentValue.GetType();
}
@ -166,7 +166,7 @@ namespace Artemis.Core
return CreateExpression(parameter, expression, nullCondition);
}
var previousType = Previous.GetPropertyType();
Type previousType = Previous.GetPropertyType();
if (previousType == null)
{
Type = DataModelPathSegmentType.Invalid;
@ -179,13 +179,13 @@ namespace Artemis.Core
// If no static type could be found, check if this is a data model and if so, look for a dynamic type
if (Type == DataModelPathSegmentType.Invalid && typeof(DataModel).IsAssignableFrom(previousType))
{
var dataModel = (DataModel) Previous.GetValue();
DataModel dataModel = (DataModel) Previous.GetValue();
// Cannot determine a dynamic type on a null data model, leave the segment invalid
if (dataModel == null)
return CreateExpression(parameter, expression, nullCondition);
// If a dynamic data model is found the use that
var hasDynamicDataModel = dataModel.DynamicDataModels.TryGetValue(Identifier, out var dynamicDataModel);
bool hasDynamicDataModel = dataModel.DynamicDataModels.TryGetValue(Identifier, out DataModel dynamicDataModel);
if (hasDynamicDataModel)
DetermineDynamicType(dynamicDataModel);
}
@ -241,7 +241,7 @@ namespace Artemis.Core
private void DetermineStaticType(Type previousType)
{
var property = previousType.GetProperty(Identifier, BindingFlags.Public | BindingFlags.Instance);
PropertyInfo? property = previousType.GetProperty(Identifier, BindingFlags.Public | BindingFlags.Instance);
Type = property == null ? DataModelPathSegmentType.Invalid : DataModelPathSegmentType.Static;
}
}

View File

@ -61,8 +61,8 @@ namespace Artemis.Core
/// <inheritdoc />
public override List<ILayerProperty> GetAllLayerProperties()
{
var result = new List<ILayerProperty>();
foreach (var layerEffect in LayerEffects)
List<ILayerProperty> result = new List<ILayerProperty>();
foreach (BaseLayerEffect layerEffect in LayerEffects)
{
if (layerEffect.BaseProperties != null)
result.AddRange(layerEffect.BaseProperties.GetAllLayerProperties());
@ -83,7 +83,7 @@ namespace Artemis.Core
return;
// Disable data bindings during an override
var wasApplyingDataBindings = ApplyDataBindingsEnabled;
bool wasApplyingDataBindings = ApplyDataBindingsEnabled;
ApplyDataBindingsEnabled = false;
UpdateDisplayCondition();
@ -92,16 +92,16 @@ namespace Artemis.Core
// to it's start
UpdateTimeline(deltaTime);
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
{
baseLayerEffect.BaseProperties?.Update(deltaTime);
baseLayerEffect.Update(deltaTime);
}
// Iterate the children in reverse because that's how they must be rendered too
for (var index = Children.Count - 1; index > -1; index--)
for (int index = Children.Count - 1; index > -1; index--)
{
var profileElement = Children[index];
ProfileElement profileElement = Children[index];
profileElement.Update(deltaTime);
}
@ -127,19 +127,19 @@ namespace Artemis.Core
if (!Enabled)
return;
var beginTime = TimelinePosition;
TimeSpan beginTime = TimelinePosition;
if (stickToMainSegment)
{
if (!DisplayContinuously)
{
var position = timeOverride + StartSegmentLength;
TimeSpan position = timeOverride + StartSegmentLength;
if (position > StartSegmentLength + EndSegmentLength)
TimelinePosition = StartSegmentLength + EndSegmentLength;
}
else
{
var progress = timeOverride.TotalMilliseconds % MainSegmentLength.TotalMilliseconds;
double progress = timeOverride.TotalMilliseconds % MainSegmentLength.TotalMilliseconds;
if (progress > 0)
TimelinePosition = TimeSpan.FromMilliseconds(progress) + StartSegmentLength;
else
@ -149,9 +149,9 @@ namespace Artemis.Core
else
TimelinePosition = timeOverride;
var delta = (TimelinePosition - beginTime).TotalSeconds;
double delta = (TimelinePosition - beginTime).TotalSeconds;
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
{
baseLayerEffect.BaseProperties?.Update(delta);
baseLayerEffect.Update(delta);
@ -178,24 +178,24 @@ namespace Artemis.Core
_folderBitmap = new SKBitmap(new SKImageInfo((int) Path.Bounds.Width, (int) Path.Bounds.Height));
}
using var folderPath = new SKPath(Path);
using var folderCanvas = new SKCanvas(_folderBitmap);
using var folderPaint = new SKPaint();
using SKPath folderPath = new SKPath(Path);
using SKCanvas folderCanvas = new SKCanvas(_folderBitmap);
using SKPaint folderPaint = new SKPaint();
folderCanvas.Clear();
folderPath.Transform(SKMatrix.MakeTranslation(folderPath.Bounds.Left * -1, folderPath.Bounds.Top * -1));
var targetLocation = Path.Bounds.Location;
SKPoint targetLocation = Path.Bounds.Location;
if (Parent is Folder parentFolder)
targetLocation -= parentFolder.Path.Bounds.Location;
canvas.Save();
using var clipPath = new SKPath(folderPath);
using SKPath clipPath = new SKPath(folderPath);
clipPath.Transform(SKMatrix.MakeTranslation(targetLocation.X, targetLocation.Y));
canvas.ClipPath(clipPath);
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
baseLayerEffect.PreProcess(folderCanvas, _folderBitmap.Info, folderPath, folderPaint);
// No point rendering if the alpha was set to zero by one of the effects
@ -203,10 +203,10 @@ namespace Artemis.Core
return;
// Iterate the children in reverse because the first layer must be rendered last to end up on top
for (var index = Children.Count - 1; index > -1; index--)
for (int index = Children.Count - 1; index > -1; index--)
{
folderCanvas.Save();
var profileElement = Children[index];
ProfileElement profileElement = Children[index];
profileElement.Render(deltaTime, folderCanvas, _folderBitmap.Info);
folderCanvas.Restore();
}
@ -214,11 +214,11 @@ namespace Artemis.Core
// If required, apply the opacity override of the module to the root folder
if (IsRootFolder && Profile.Module.OpacityOverride < 1)
{
var multiplier = Easings.SineEaseInOut(Profile.Module.OpacityOverride);
double multiplier = Easings.SineEaseInOut(Profile.Module.OpacityOverride);
folderPaint.Color = folderPaint.Color.WithAlpha((byte) (folderPaint.Color.Alpha * multiplier));
}
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
baseLayerEffect.PostProcess(canvas, canvasInfo, folderPath, folderPaint);
canvas.DrawBitmap(_folderBitmap, targetLocation, folderPaint);
@ -257,8 +257,8 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("Folder");
var path = new SKPath {FillType = SKPathFillType.Winding};
foreach (var child in Children)
SKPath path = new SKPath {FillType = SKPathFillType.Winding};
foreach (ProfileElement child in Children)
{
if (child is RenderProfileElement effectChild && effectChild.Path != null)
path.AddPath(effectChild.Path);
@ -277,7 +277,7 @@ namespace Artemis.Core
{
_disposed = true;
foreach (var profileElement in Children)
foreach (ProfileElement profileElement in Children)
profileElement.Dispose();
_folderBitmap?.Dispose();
@ -289,15 +289,15 @@ namespace Artemis.Core
_expandedPropertyGroups.AddRange(FolderEntity.ExpandedPropertyGroups);
// Load child folders
foreach (var childFolder in Profile.ProfileEntity.Folders.Where(f => f.ParentId == EntityId))
foreach (FolderEntity childFolder in Profile.ProfileEntity.Folders.Where(f => f.ParentId == EntityId))
ChildrenList.Add(new Folder(Profile, this, childFolder));
// Load child layers
foreach (var childLayer in Profile.ProfileEntity.Layers.Where(f => f.ParentId == EntityId))
foreach (LayerEntity childLayer in Profile.ProfileEntity.Layers.Where(f => f.ParentId == EntityId))
ChildrenList.Add(new Layer(Profile, this, childLayer));
// Ensure order integrity, should be unnecessary but no one is perfect specially me
ChildrenList = ChildrenList.OrderBy(c => c.Order).ToList();
for (var index = 0; index < ChildrenList.Count; index++)
for (int index = 0; index < ChildrenList.Count; index++)
ChildrenList[index].Order = index + 1;
LoadRenderElement();

View File

@ -73,12 +73,12 @@ namespace Artemis.Core
/// <inheritdoc />
public override List<ILayerProperty> GetAllLayerProperties()
{
var result = new List<ILayerProperty>();
List<ILayerProperty> result = new List<ILayerProperty>();
result.AddRange(General.GetAllLayerProperties());
result.AddRange(Transform.GetAllLayerProperties());
if (LayerBrush?.BaseProperties != null)
result.AddRange(LayerBrush.BaseProperties.GetAllLayerProperties());
foreach (var layerEffect in LayerEffects)
foreach (BaseLayerEffect layerEffect in LayerEffects)
{
if (layerEffect.BaseProperties != null)
result.AddRange(layerEffect.BaseProperties.GetAllLayerProperties());
@ -162,11 +162,11 @@ namespace Artemis.Core
LayerBrushStore.LayerBrushRemoved += LayerBrushStoreOnLayerBrushRemoved;
// Layers have two hardcoded property groups, instantiate them
var generalAttribute = Attribute.GetCustomAttribute(
Attribute? generalAttribute = Attribute.GetCustomAttribute(
GetType().GetProperty(nameof(General)),
typeof(PropertyGroupDescriptionAttribute)
);
var transformAttribute = Attribute.GetCustomAttribute(
Attribute? transformAttribute = Attribute.GetCustomAttribute(
GetType().GetProperty(nameof(Transform)),
typeof(PropertyGroupDescriptionAttribute)
);
@ -214,9 +214,9 @@ namespace Artemis.Core
// LEDs
LayerEntity.Leds.Clear();
foreach (var artemisLed in Leds)
foreach (ArtemisLed artemisLed in Leds)
{
var ledEntity = new LedEntity
LedEntity ledEntity = new LedEntity
{
DeviceIdentifier = artemisLed.Device.RgbDevice.GetDeviceIdentifier(),
LedName = artemisLed.RgbLed.Id.ToString()
@ -280,7 +280,7 @@ namespace Artemis.Core
LayerBrush.BaseProperties?.Update(deltaTime);
LayerBrush.Update(deltaTime);
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
{
baseLayerEffect.BaseProperties?.Update(deltaTime);
baseLayerEffect.Update(deltaTime);
@ -301,10 +301,10 @@ namespace Artemis.Core
return;
// Disable data bindings during an override
var wasApplyingDataBindings = ApplyDataBindingsEnabled;
bool wasApplyingDataBindings = ApplyDataBindingsEnabled;
ApplyDataBindingsEnabled = false;
var beginTime = TimelinePosition;
TimeSpan beginTime = TimelinePosition;
if (stickToMainSegment)
{
@ -312,7 +312,7 @@ namespace Artemis.Core
TimelinePosition = StartSegmentLength + timeOverride;
else
{
var progress = timeOverride.TotalMilliseconds % MainSegmentLength.TotalMilliseconds;
double progress = timeOverride.TotalMilliseconds % MainSegmentLength.TotalMilliseconds;
if (progress > 0)
TimelinePosition = TimeSpan.FromMilliseconds(progress) + StartSegmentLength;
else
@ -322,14 +322,14 @@ namespace Artemis.Core
else
TimelinePosition = timeOverride;
var delta = (TimelinePosition - beginTime).TotalSeconds;
double delta = (TimelinePosition - beginTime).TotalSeconds;
General.Update(delta);
Transform.Update(delta);
LayerBrush.BaseProperties?.Update(delta);
LayerBrush.Update(delta);
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
{
baseLayerEffect.BaseProperties?.Update(delta);
baseLayerEffect.Update(delta);
@ -363,9 +363,9 @@ namespace Artemis.Core
_layerBitmap = new SKBitmap(new SKImageInfo((int) Path.Bounds.Width, (int) Path.Bounds.Height));
}
using var layerPath = new SKPath(Path);
using var layerCanvas = new SKCanvas(_layerBitmap);
using var layerPaint = new SKPaint
using SKPath layerPath = new SKPath(Path);
using SKCanvas layerCanvas = new SKCanvas(_layerBitmap);
using SKPaint layerPaint = new SKPaint
{
FilterQuality = SKFilterQuality.Low,
Color = new SKColor(0, 0, 0, (byte) (Transform.Opacity.CurrentValue * 2.55f))
@ -374,7 +374,7 @@ namespace Artemis.Core
layerPath.Transform(SKMatrix.MakeTranslation(layerPath.Bounds.Left * -1, layerPath.Bounds.Top * -1));
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
baseLayerEffect.PreProcess(layerCanvas, _layerBitmap.Info, layerPath, layerPaint);
// No point rendering if the alpha was set to zero by one of the effects
@ -388,15 +388,15 @@ namespace Artemis.Core
else if (General.ResizeMode.CurrentValue == LayerResizeMode.Clip)
ClipRender(layerCanvas, _layerBitmap.Info, layerPaint, layerPath);
foreach (var baseLayerEffect in LayerEffects.Where(e => e.Enabled))
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.Where(e => e.Enabled))
baseLayerEffect.PostProcess(layerCanvas, _layerBitmap.Info, layerPath, layerPaint);
var targetLocation = new SKPoint(0, 0);
SKPoint targetLocation = new SKPoint(0, 0);
if (Parent is Folder parentFolder)
targetLocation = Path.Bounds.Location - parentFolder.Path.Bounds.Location;
using var canvasPaint = new SKPaint {BlendMode = General.BlendMode.CurrentValue};
using var canvasPath = new SKPath(Path);
using SKPaint canvasPaint = new SKPaint {BlendMode = General.BlendMode.CurrentValue};
using SKPath canvasPath = new SKPath(Path);
canvasPath.Transform(SKMatrix.MakeTranslation(
(canvasPath.Bounds.Left - targetLocation.X) * -1,
(canvasPath.Bounds.Top - targetLocation.Y) * -1)
@ -407,46 +407,46 @@ namespace Artemis.Core
private void SimpleRender(SKCanvas canvas, SKImageInfo canvasInfo, SKPaint paint, SKPath layerPath)
{
using var renderPath = new SKPath(LayerShape.Path);
using SKPath renderPath = new SKPath(LayerShape.Path);
LayerBrush.InternalRender(canvas, canvasInfo, renderPath, paint);
}
private void StretchRender(SKCanvas canvas, SKImageInfo canvasInfo, SKPaint paint, SKPath layerPath)
{
// Apply transformations
var sizeProperty = Transform.Scale.CurrentValue;
var rotationProperty = Transform.Rotation.CurrentValue;
SKSize sizeProperty = Transform.Scale.CurrentValue;
float rotationProperty = Transform.Rotation.CurrentValue;
var anchorPosition = GetLayerAnchorPosition(layerPath);
var anchorProperty = Transform.AnchorPoint.CurrentValue;
SKPoint anchorPosition = GetLayerAnchorPosition(layerPath);
SKPoint anchorProperty = Transform.AnchorPoint.CurrentValue;
// Translation originates from the unscaled center of the shape and is tied to the anchor
var x = anchorPosition.X - layerPath.Bounds.MidX - anchorProperty.X * layerPath.Bounds.Width;
var y = anchorPosition.Y - layerPath.Bounds.MidY - anchorProperty.Y * layerPath.Bounds.Height;
float x = anchorPosition.X - layerPath.Bounds.MidX - anchorProperty.X * layerPath.Bounds.Width;
float y = anchorPosition.Y - layerPath.Bounds.MidY - anchorProperty.Y * layerPath.Bounds.Height;
// Apply these before translation because anchorPosition takes translation into account
canvas.RotateDegrees(rotationProperty, anchorPosition.X, anchorPosition.Y);
canvas.Scale(sizeProperty.Width / 100f, sizeProperty.Height / 100f, anchorPosition.X, anchorPosition.Y);
canvas.Translate(x, y);
using var renderPath = new SKPath(LayerShape.Path);
using SKPath renderPath = new SKPath(LayerShape.Path);
LayerBrush.InternalRender(canvas, canvasInfo, renderPath, paint);
}
private void ClipRender(SKCanvas canvas, SKImageInfo canvasInfo, SKPaint paint, SKPath layerPath)
{
// Apply transformation
var sizeProperty = Transform.Scale.CurrentValue;
var rotationProperty = Transform.Rotation.CurrentValue;
SKSize sizeProperty = Transform.Scale.CurrentValue;
float rotationProperty = Transform.Rotation.CurrentValue;
var anchorPosition = GetLayerAnchorPosition(layerPath);
var anchorProperty = Transform.AnchorPoint.CurrentValue;
SKPoint anchorPosition = GetLayerAnchorPosition(layerPath);
SKPoint anchorProperty = Transform.AnchorPoint.CurrentValue;
// Translation originates from the unscaled center of the shape and is tied to the anchor
var x = anchorPosition.X - layerPath.Bounds.MidX - anchorProperty.X * layerPath.Bounds.Width;
var y = anchorPosition.Y - layerPath.Bounds.MidY - anchorProperty.Y * layerPath.Bounds.Height;
float x = anchorPosition.X - layerPath.Bounds.MidX - anchorProperty.X * layerPath.Bounds.Width;
float y = anchorPosition.Y - layerPath.Bounds.MidY - anchorProperty.Y * layerPath.Bounds.Height;
using var clipPath = new SKPath(LayerShape.Path);
using SKPath clipPath = new SKPath(LayerShape.Path);
clipPath.Transform(SKMatrix.MakeTranslation(x, y));
clipPath.Transform(SKMatrix.MakeScale(sizeProperty.Width / 100f, sizeProperty.Height / 100f, anchorPosition.X, anchorPosition.Y));
clipPath.Transform(SKMatrix.MakeRotationDegrees(rotationProperty, anchorPosition.X, anchorPosition.Y));
@ -457,13 +457,13 @@ namespace Artemis.Core
// Render the layer in the largest required bounds, this still creates stretching in some situations
// but the only alternative I see right now is always forcing brushes to render on the entire canvas
var boundsRect = new SKRect(
SKRect boundsRect = new SKRect(
Math.Min(clipPath.Bounds.Left - x, Bounds.Left - x),
Math.Min(clipPath.Bounds.Top - y, Bounds.Top - y),
Math.Max(clipPath.Bounds.Right - x, Bounds.Right - x),
Math.Max(clipPath.Bounds.Bottom - y, Bounds.Bottom - y)
);
using var renderPath = new SKPath();
using SKPath renderPath = new SKPath();
renderPath.AddRect(boundsRect);
LayerBrush.InternalRender(canvas, canvasInfo, renderPath, paint);
@ -478,8 +478,8 @@ namespace Artemis.Core
Path = new SKPath();
else
{
var path = new SKPath {FillType = SKPathFillType.Winding};
foreach (var artemisLed in Leds)
SKPath path = new SKPath {FillType = SKPathFillType.Winding};
foreach (ArtemisLed artemisLed in Leds)
path.AddRect(artemisLed.AbsoluteRenderRectangle);
Path = path;
@ -501,10 +501,10 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("Layer");
var positionProperty = Transform.Position.CurrentValue;
SKPoint positionProperty = Transform.Position.CurrentValue;
// Start at the center of the shape
var position = zeroBased
SKPoint position = zeroBased
? new SKPoint(layerPath.Bounds.MidX - layerPath.Bounds.Left, layerPath.Bounds.MidY - layerPath.Bounds.Top)
: new SKPoint(layerPath.Bounds.MidX, layerPath.Bounds.MidY);
@ -525,15 +525,15 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("Layer");
var sizeProperty = Transform.Scale.CurrentValue;
var rotationProperty = Transform.Rotation.CurrentValue;
SKSize sizeProperty = Transform.Scale.CurrentValue;
float rotationProperty = Transform.Rotation.CurrentValue;
var anchorPosition = GetLayerAnchorPosition(Path, zeroBased);
var anchorProperty = Transform.AnchorPoint.CurrentValue;
SKPoint anchorPosition = GetLayerAnchorPosition(Path, zeroBased);
SKPoint anchorProperty = Transform.AnchorPoint.CurrentValue;
// Translation originates from the unscaled center of the shape and is tied to the anchor
var x = anchorPosition.X - (zeroBased ? Bounds.MidX - Bounds.Left : Bounds.MidX) - anchorProperty.X * Bounds.Width;
var y = anchorPosition.Y - (zeroBased ? Bounds.MidY - Bounds.Top : Bounds.MidY) - anchorProperty.Y * Bounds.Height;
float x = anchorPosition.X - (zeroBased ? Bounds.MidX - Bounds.Left : Bounds.MidX) - anchorProperty.X * Bounds.Width;
float y = anchorPosition.Y - (zeroBased ? Bounds.MidY - Bounds.Top : Bounds.MidY) - anchorProperty.Y * Bounds.Height;
if (General.ResizeMode == LayerResizeMode.Normal)
{
@ -557,18 +557,18 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("Layer");
var sizeProperty = Transform.Scale.CurrentValue;
var rotationProperty = Transform.Rotation.CurrentValue;
SKSize sizeProperty = Transform.Scale.CurrentValue;
float rotationProperty = Transform.Rotation.CurrentValue;
var anchorPosition = GetLayerAnchorPosition(Path, zeroBased);
var anchorProperty = Transform.AnchorPoint.CurrentValue;
SKPoint anchorPosition = GetLayerAnchorPosition(Path, zeroBased);
SKPoint anchorProperty = Transform.AnchorPoint.CurrentValue;
// Translation originates from the unscaled center of the shape and is tied to the anchor
var x = anchorPosition.X - (zeroBased ? Bounds.MidX - Bounds.Left : Bounds.MidX) - anchorProperty.X * Bounds.Width;
var y = anchorPosition.Y - (zeroBased ? Bounds.MidY - Bounds.Top : Bounds.MidY) - anchorProperty.Y * Bounds.Height;
float x = anchorPosition.X - (zeroBased ? Bounds.MidX - Bounds.Left : Bounds.MidX) - anchorProperty.X * Bounds.Width;
float y = anchorPosition.Y - (zeroBased ? Bounds.MidY - Bounds.Top : Bounds.MidY) - anchorProperty.Y * Bounds.Height;
var reversedXScale = 1f / (sizeProperty.Width / 100f);
var reversedYScale = 1f / (sizeProperty.Height / 100f);
float reversedXScale = 1f / (sizeProperty.Width / 100f);
float reversedYScale = 1f / (sizeProperty.Height / 100f);
if (General.ResizeMode == LayerResizeMode.Normal)
{
@ -593,18 +593,18 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("Layer");
var sizeProperty = Transform.Scale.CurrentValue;
var rotationProperty = Transform.Rotation.CurrentValue;
SKSize sizeProperty = Transform.Scale.CurrentValue;
float rotationProperty = Transform.Rotation.CurrentValue;
var anchorPosition = GetLayerAnchorPosition(Path, zeroBased);
var anchorProperty = Transform.AnchorPoint.CurrentValue;
SKPoint anchorPosition = GetLayerAnchorPosition(Path, zeroBased);
SKPoint anchorProperty = Transform.AnchorPoint.CurrentValue;
// Translation originates from the unscaled center of the shape and is tied to the anchor
var x = anchorPosition.X - (zeroBased ? Bounds.MidX - Bounds.Left : Bounds.MidX) - anchorProperty.X * Bounds.Width;
var y = anchorPosition.Y - (zeroBased ? Bounds.MidY - Bounds.Top : Bounds.MidY) - anchorProperty.Y * Bounds.Height;
float x = anchorPosition.X - (zeroBased ? Bounds.MidX - Bounds.Left : Bounds.MidX) - anchorProperty.X * Bounds.Width;
float y = anchorPosition.Y - (zeroBased ? Bounds.MidY - Bounds.Top : Bounds.MidY) - anchorProperty.Y * Bounds.Height;
var reversedXScale = 1f / (sizeProperty.Width / 100f);
var reversedYScale = 1f / (sizeProperty.Height / 100f);
float reversedXScale = 1f / (sizeProperty.Width / 100f);
float reversedYScale = 1f / (sizeProperty.Height / 100f);
if (General.ResizeMode == LayerResizeMode.Normal)
{
@ -680,14 +680,14 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("Layer");
var leds = new List<ArtemisLed>();
List<ArtemisLed> leds = new List<ArtemisLed>();
// Get the surface LEDs for this layer
var availableLeds = surface.Devices.SelectMany(d => d.Leds).ToList();
foreach (var ledEntity in LayerEntity.Leds)
List<ArtemisLed> availableLeds = surface.Devices.SelectMany(d => d.Leds).ToList();
foreach (LedEntity ledEntity in LayerEntity.Leds)
{
var match = availableLeds.FirstOrDefault(a => a.Device.RgbDevice.GetDeviceIdentifier() == ledEntity.DeviceIdentifier &&
a.RgbLed.Id.ToString() == ledEntity.LedName);
ArtemisLed match = availableLeds.FirstOrDefault(a => a.Device.RgbDevice.GetDeviceIdentifier() == ledEntity.DeviceIdentifier &&
a.RgbLed.Id.ToString() == ledEntity.LedName);
if (match != null)
leds.Add(match);
}
@ -710,13 +710,13 @@ namespace Artemis.Core
if (LayerBrush != null)
{
var brush = LayerBrush;
BaseLayerBrush brush = LayerBrush;
LayerBrush = null;
brush.Dispose();
}
// Ensure the brush reference matches the brush
var current = General.BrushReference.BaseValue;
LayerBrushReference current = General.BrushReference.BaseValue;
if (!descriptor.MatchesLayerBrushReference(current))
General.BrushReference.BaseValue = new LayerBrushReference(descriptor);
@ -731,18 +731,18 @@ namespace Artemis.Core
if (LayerBrush == null)
return;
var brush = LayerBrush;
BaseLayerBrush brush = LayerBrush;
DeactivateLayerBrush();
LayerEntity.PropertyEntities.RemoveAll(p => p.PluginGuid == brush.PluginInfo.Guid && p.Path.StartsWith("LayerBrush."));
}
internal void ActivateLayerBrush()
{
var current = General.BrushReference.CurrentValue;
LayerBrushReference current = General.BrushReference.CurrentValue;
if (current == null)
return;
var descriptor = LayerBrushStore.Get(current.BrushPluginGuid, current.BrushType)?.LayerBrushDescriptor;
LayerBrushDescriptor descriptor = LayerBrushStore.Get(current.BrushPluginGuid, current.BrushType)?.LayerBrushDescriptor;
descriptor?.CreateInstance(this);
OnLayerBrushUpdated();
@ -753,7 +753,7 @@ namespace Artemis.Core
if (LayerBrush == null)
return;
var brush = LayerBrush;
BaseLayerBrush brush = LayerBrush;
LayerBrush = null;
brush.Dispose();
@ -775,7 +775,7 @@ namespace Artemis.Core
if (LayerBrush != null || General.BrushReference?.CurrentValue == null)
return;
var current = General.BrushReference.CurrentValue;
LayerBrushReference current = General.BrushReference.CurrentValue;
if (e.Registration.Plugin.PluginInfo.Guid == current.BrushPluginGuid &&
e.Registration.LayerBrushDescriptor.LayerBrushType.Name == current.BrushType)
ActivateLayerBrush();

View File

@ -56,7 +56,7 @@ namespace Artemis.Core
{
_disposed = true;
foreach (var dataBinding in _dataBindings)
foreach (IDataBinding dataBinding in _dataBindings)
dataBinding.Dispose();
}
@ -158,7 +158,7 @@ namespace Artemis.Core
else
{
// If on a keyframe, update the keyframe
var currentKeyframe = Keyframes.FirstOrDefault(k => k.Position == time.Value);
LayerPropertyKeyframe<T> currentKeyframe = Keyframes.FirstOrDefault(k => k.Position == time.Value);
// Create a new keyframe if none found
if (currentKeyframe == null)
AddKeyframe(new LayerPropertyKeyframe<T>(value, time.Value, Easings.Functions.Linear, this));
@ -256,7 +256,7 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("LayerProperty");
var newKeyframe = new LayerPropertyKeyframe<T>(
LayerPropertyKeyframe<T> newKeyframe = new LayerPropertyKeyframe<T>(
keyframe.Value,
keyframe.Position,
keyframe.EasingFunction,
@ -301,7 +301,7 @@ namespace Artemis.Core
// The current keyframe is the last keyframe before the current time
CurrentKeyframe = _keyframes.LastOrDefault(k => k.Position <= ProfileElement.TimelinePosition);
// Keyframes are sorted by position so we can safely assume the next keyframe's position is after the current
var nextIndex = _keyframes.IndexOf(CurrentKeyframe) + 1;
int nextIndex = _keyframes.IndexOf(CurrentKeyframe) + 1;
NextKeyframe = _keyframes.Count > nextIndex ? _keyframes[nextIndex] : null;
// No need to update the current value if either of the keyframes are null
@ -312,9 +312,9 @@ namespace Artemis.Core
// Only determine progress and current value if both keyframes are present
else
{
var timeDiff = NextKeyframe.Position - CurrentKeyframe.Position;
var keyframeProgress = (float) ((ProfileElement.TimelinePosition - CurrentKeyframe.Position).TotalMilliseconds / timeDiff.TotalMilliseconds);
var keyframeProgressEased = (float) Easings.Interpolate(keyframeProgress, CurrentKeyframe.EasingFunction);
TimeSpan timeDiff = NextKeyframe.Position - CurrentKeyframe.Position;
float keyframeProgress = (float) ((ProfileElement.TimelinePosition - CurrentKeyframe.Position).TotalMilliseconds / timeDiff.TotalMilliseconds);
float keyframeProgressEased = (float) Easings.Interpolate(keyframeProgress, CurrentKeyframe.EasingFunction);
UpdateCurrentValue(keyframeProgress, keyframeProgressEased);
}
}
@ -350,8 +350,8 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("LayerProperty");
var match = _dataBindingRegistrations.FirstOrDefault(r => r is DataBindingRegistration<T, TProperty> registration &&
registration.PropertyExpression.ToString() == expression);
IDataBindingRegistration match = _dataBindingRegistrations.FirstOrDefault(r => r is DataBindingRegistration<T, TProperty> registration &&
registration.PropertyExpression.ToString() == expression);
return (DataBindingRegistration<T, TProperty>) match;
}
@ -392,7 +392,7 @@ namespace Artemis.Core
if (dataBindingRegistration.DataBinding != null)
throw new ArtemisCoreException("Provided data binding registration already has an enabled data binding");
var dataBinding = new DataBinding<T, TProperty>(dataBindingRegistration);
DataBinding<T, TProperty> dataBinding = new DataBinding<T, TProperty>(dataBindingRegistration);
_dataBindings.Add(dataBinding);
OnDataBindingEnabled(new LayerPropertyEventArgs<T>(dataBinding.LayerProperty));
@ -417,7 +417,7 @@ namespace Artemis.Core
private void UpdateDataBindings(double deltaTime)
{
foreach (var dataBinding in _dataBindings)
foreach (IDataBinding dataBinding in _dataBindings)
{
dataBinding.Update(deltaTime);
dataBinding.Apply();
@ -497,9 +497,9 @@ namespace Artemis.Core
}
_dataBindings.Clear();
foreach (var dataBindingRegistration in _dataBindingRegistrations)
foreach (IDataBindingRegistration dataBindingRegistration in _dataBindingRegistrations)
{
var dataBinding = dataBindingRegistration.CreateDataBinding();
IDataBinding dataBinding = dataBindingRegistration.CreateDataBinding();
if (dataBinding != null)
_dataBindings.Add(dataBinding);
}
@ -528,7 +528,7 @@ namespace Artemis.Core
}));
Entity.DataBindingEntities.Clear();
foreach (var dataBinding in _dataBindings)
foreach (IDataBinding dataBinding in _dataBindings)
dataBinding.Save();
}

View File

@ -95,9 +95,9 @@ namespace Artemis.Core
_disposed = true;
DisableProperties();
foreach (var layerProperty in _layerProperties)
foreach (ILayerProperty layerProperty in _layerProperties)
layerProperty.Dispose();
foreach (var layerPropertyGroup in _layerPropertyGroups)
foreach (LayerPropertyGroup layerPropertyGroup in _layerPropertyGroups)
layerPropertyGroup.Dispose();
}
@ -114,8 +114,8 @@ namespace Artemis.Core
if (!PropertiesInitialized)
return new List<ILayerProperty>();
var result = new List<ILayerProperty>(LayerProperties);
foreach (var layerPropertyGroup in LayerPropertyGroups)
List<ILayerProperty> result = new List<ILayerProperty>(LayerProperties);
foreach (LayerPropertyGroup layerPropertyGroup in LayerPropertyGroups)
result.AddRange(layerPropertyGroup.GetAllLayerProperties());
return result.AsReadOnly();
@ -161,14 +161,14 @@ namespace Artemis.Core
Path = path.TrimEnd('.');
// Get all properties with a PropertyDescriptionAttribute
foreach (var propertyInfo in GetType().GetProperties())
foreach (PropertyInfo propertyInfo in GetType().GetProperties())
{
var propertyDescription = Attribute.GetCustomAttribute(propertyInfo, typeof(PropertyDescriptionAttribute));
Attribute? propertyDescription = Attribute.GetCustomAttribute(propertyInfo, typeof(PropertyDescriptionAttribute));
if (propertyDescription != null)
InitializeProperty(propertyInfo, (PropertyDescriptionAttribute) propertyDescription);
else
{
var propertyGroupDescription = Attribute.GetCustomAttribute(propertyInfo, typeof(PropertyGroupDescriptionAttribute));
Attribute? propertyGroupDescription = Attribute.GetCustomAttribute(propertyInfo, typeof(PropertyGroupDescriptionAttribute));
if (propertyGroupDescription != null)
InitializeChildGroup(propertyInfo, (PropertyGroupDescriptionAttribute) propertyGroupDescription);
}
@ -178,7 +178,7 @@ namespace Artemis.Core
PopulateDefaults();
// Load the layer properties after defaults have been applied
foreach (var layerProperty in _layerProperties)
foreach (ILayerProperty layerProperty in _layerProperties)
layerProperty.Load();
EnableProperties();
@ -191,10 +191,10 @@ namespace Artemis.Core
if (!PropertiesInitialized)
return;
foreach (var layerProperty in LayerProperties)
foreach (ILayerProperty layerProperty in LayerProperties)
layerProperty.Save();
foreach (var layerPropertyGroup in LayerPropertyGroups)
foreach (LayerPropertyGroup layerPropertyGroup in LayerPropertyGroups)
layerPropertyGroup.ApplyToEntity();
}
@ -207,12 +207,12 @@ namespace Artemis.Core
private void InitializeProperty(PropertyInfo propertyInfo, PropertyDescriptionAttribute propertyDescription)
{
var path = $"{Path}.{propertyInfo.Name}";
string path = $"{Path}.{propertyInfo.Name}";
if (!typeof(ILayerProperty).IsAssignableFrom(propertyInfo.PropertyType))
throw new ArtemisPluginException($"Layer property with PropertyDescription attribute must be of type LayerProperty at {path}");
var instance = (ILayerProperty) Activator.CreateInstance(propertyInfo.PropertyType, true);
ILayerProperty instance = (ILayerProperty) Activator.CreateInstance(propertyInfo.PropertyType, true);
if (instance == null)
throw new ArtemisPluginException($"Failed to create instance of layer property at {path}");
@ -220,7 +220,7 @@ namespace Artemis.Core
if (string.IsNullOrWhiteSpace(propertyDescription.Name))
propertyDescription.Name = propertyInfo.Name.Humanize();
var entity = GetPropertyEntity(ProfileElement, path, out var fromStorage);
PropertyEntity entity = GetPropertyEntity(ProfileElement, path, out bool fromStorage);
instance.Initialize(ProfileElement, this, entity, fromStorage, propertyDescription, path);
propertyInfo.SetValue(this, instance);
_layerProperties.Add(instance);
@ -228,12 +228,12 @@ namespace Artemis.Core
private void InitializeChildGroup(PropertyInfo propertyInfo, PropertyGroupDescriptionAttribute propertyGroupDescription)
{
var path = Path + ".";
string path = Path + ".";
if (!typeof(LayerPropertyGroup).IsAssignableFrom(propertyInfo.PropertyType))
throw new ArtemisPluginException("Layer property with PropertyGroupDescription attribute must be of type LayerPropertyGroup");
var instance = (LayerPropertyGroup) Activator.CreateInstance(propertyInfo.PropertyType);
LayerPropertyGroup instance = (LayerPropertyGroup) Activator.CreateInstance(propertyInfo.PropertyType);
if (instance == null)
throw new ArtemisPluginException($"Failed to create instance of layer property group at {path + propertyInfo.Name}");
@ -253,7 +253,7 @@ namespace Artemis.Core
private PropertyEntity GetPropertyEntity(RenderProfileElement profileElement, string path, out bool fromStorage)
{
var entity = profileElement.RenderElementEntity.PropertyEntities.FirstOrDefault(p => p.PluginGuid == PluginInfo.Guid && p.Path == path);
PropertyEntity entity = profileElement.RenderElementEntity.PropertyEntities.FirstOrDefault(p => p.PluginGuid == PluginInfo.Guid && p.Path == path);
fromStorage = entity != null;
if (entity == null)
{

View File

@ -14,7 +14,7 @@ namespace Artemis.Core
/// <inheritdoc />
public override void CalculateRenderProperties()
{
var path = new SKPath();
SKPath path = new SKPath();
path.AddOval(SKRect.Create(Layer.Bounds.Width, Layer.Bounds.Height));
Path = path;
}

View File

@ -14,7 +14,7 @@ namespace Artemis.Core
/// <inheritdoc />
public override void CalculateRenderProperties()
{
var path = new SKPath();
SKPath path = new SKPath();
path.AddRect(SKRect.Create(Layer.Bounds.Width, Layer.Bounds.Height));
Path = path;
}

View File

@ -22,7 +22,7 @@ namespace Artemis.Core
UndoStack = new Stack<string>();
RedoStack = new Stack<string>();
var _ = new Folder(this, "Root folder");
Folder _ = new Folder(this, "Root folder");
Save();
}
@ -61,7 +61,7 @@ namespace Artemis.Core
if (!IsActivated)
throw new ArtemisCoreException($"Cannot update inactive profile: {this}");
foreach (var profileElement in Children)
foreach (ProfileElement profileElement in Children)
profileElement.Update(deltaTime);
}
}
@ -75,7 +75,7 @@ namespace Artemis.Core
if (!IsActivated)
throw new ArtemisCoreException($"Cannot render inactive profile: {this}");
foreach (var profileElement in Children)
foreach (ProfileElement profileElement in Children)
profileElement.Render(deltaTime, canvas, canvasInfo);
}
}
@ -98,15 +98,15 @@ namespace Artemis.Core
lock (ChildrenList)
{
// Remove the old profile tree
foreach (var profileElement in Children)
foreach (ProfileElement profileElement in Children)
profileElement.Dispose();
ChildrenList.Clear();
// Populate the profile starting at the root, the rest is populated recursively
var rootFolder = ProfileEntity.Folders.FirstOrDefault(f => f.ParentId == EntityId);
FolderEntity rootFolder = ProfileEntity.Folders.FirstOrDefault(f => f.ParentId == EntityId);
if (rootFolder == null)
{
var _ = new Folder(this, "Root folder");
Folder _ = new Folder(this, "Root folder");
}
else
AddChild(new Folder(this, this, rootFolder));
@ -125,7 +125,7 @@ namespace Artemis.Core
OnDeactivating();
foreach (var profileElement in Children)
foreach (ProfileElement profileElement in Children)
profileElement.Dispose();
ChildrenList.Clear();
@ -143,7 +143,7 @@ namespace Artemis.Core
ProfileEntity.Name = Name;
ProfileEntity.IsActive = IsActivated;
foreach (var profileElement in Children)
foreach (ProfileElement profileElement in Children)
profileElement.Save();
ProfileEntity.Folders.Clear();
@ -173,7 +173,7 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException("Profile");
foreach (var layer in GetAllLayers())
foreach (Layer layer in GetAllLayers())
layer.PopulateLeds(surface);
}

View File

@ -125,7 +125,7 @@ namespace Artemis.Core
// Shift everything after the given order
else
{
foreach (var profileElement in ChildrenList.Where(c => c.Order >= order).ToList())
foreach (ProfileElement profileElement in ChildrenList.Where(c => c.Order >= order).ToList())
profileElement.Order++;
int targetIndex;
@ -160,7 +160,7 @@ namespace Artemis.Core
ChildrenList.Remove(child);
// Shift everything after the given order
foreach (var profileElement in ChildrenList.Where(c => c.Order > child.Order).ToList())
foreach (ProfileElement profileElement in ChildrenList.Where(c => c.Order > child.Order).ToList())
profileElement.Order--;
child.Parent = null;
@ -178,8 +178,8 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
var folders = new List<Folder>();
foreach (var childFolder in Children.Where(c => c is Folder).Cast<Folder>())
List<Folder> folders = new List<Folder>();
foreach (Folder childFolder in Children.Where(c => c is Folder).Cast<Folder>())
{
// Add all folders in this element
folders.Add(childFolder);
@ -199,13 +199,13 @@ namespace Artemis.Core
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
var layers = new List<Layer>();
List<Layer> layers = new List<Layer>();
// Add all layers in this element
layers.AddRange(Children.Where(c => c is Layer).Cast<Layer>());
// Add all layers in folders inside this element
foreach (var childFolder in Children.Where(c => c is Folder).Cast<Folder>())
foreach (Folder childFolder in Children.Where(c => c is Folder).Cast<Folder>())
layers.AddRange(childFolder.GetAllLayers());
return layers;

View File

@ -31,7 +31,7 @@ namespace Artemis.Core
LayerEffectStore.LayerEffectAdded -= LayerEffectStoreOnLayerEffectAdded;
LayerEffectStore.LayerEffectRemoved -= LayerEffectStoreOnLayerEffectRemoved;
foreach (var baseLayerEffect in LayerEffects)
foreach (BaseLayerEffect baseLayerEffect in LayerEffects)
baseLayerEffect.Dispose();
base.Dispose(disposing);
@ -68,9 +68,9 @@ namespace Artemis.Core
RenderElementEntity.AlwaysFinishTimeline = AlwaysFinishTimeline;
RenderElementEntity.LayerEffects.Clear();
foreach (var layerEffect in LayerEffects)
foreach (BaseLayerEffect layerEffect in LayerEffects)
{
var layerEffectEntity = new LayerEffectEntity
LayerEffectEntity layerEffectEntity = new LayerEffectEntity
{
Id = layerEffect.EntityId,
PluginGuid = layerEffect.Descriptor.PlaceholderFor ?? layerEffect.PluginInfo.Guid,
@ -228,9 +228,9 @@ namespace Artemis.Core
protected double UpdateTimeline(double deltaTime)
{
var oldPosition = _timelinePosition;
var deltaTimeSpan = TimeSpan.FromSeconds(deltaTime);
var mainSegmentEnd = StartSegmentLength + MainSegmentLength;
TimeSpan oldPosition = _timelinePosition;
TimeSpan deltaTimeSpan = TimeSpan.FromSeconds(deltaTime);
TimeSpan mainSegmentEnd = StartSegmentLength + MainSegmentLength;
TimelinePosition += deltaTimeSpan;
// Manage segments while the condition is met
@ -278,7 +278,7 @@ namespace Artemis.Core
if (descriptor == null)
throw new ArgumentNullException(nameof(descriptor));
var entity = new LayerEffectEntity
LayerEffectEntity entity = new LayerEffectEntity
{
Id = Guid.NewGuid(),
Enabled = true,
@ -309,8 +309,8 @@ namespace Artemis.Core
private void OrderEffects()
{
var index = 0;
foreach (var baseLayerEffect in LayerEffects.OrderBy(e => e.Order))
int index = 0;
foreach (BaseLayerEffect baseLayerEffect in LayerEffects.OrderBy(e => e.Order))
{
baseLayerEffect.Order = Order = index + 1;
index++;
@ -321,14 +321,14 @@ namespace Artemis.Core
internal void ActivateEffects()
{
foreach (var layerEffectEntity in RenderElementEntity.LayerEffects)
foreach (LayerEffectEntity layerEffectEntity in RenderElementEntity.LayerEffects)
{
// If there is a non-placeholder existing effect, skip this entity
var existing = _layerEffects.FirstOrDefault(e => e.EntityId == layerEffectEntity.Id);
BaseLayerEffect existing = _layerEffects.FirstOrDefault(e => e.EntityId == layerEffectEntity.Id);
if (existing != null && existing.Descriptor.PlaceholderFor == null)
continue;
var descriptor = LayerEffectStore.Get(layerEffectEntity.PluginGuid, layerEffectEntity.EffectType)?.LayerEffectDescriptor;
LayerEffectDescriptor descriptor = LayerEffectStore.Get(layerEffectEntity.PluginGuid, layerEffectEntity.EffectType)?.LayerEffectDescriptor;
if (descriptor != null)
{
// If a descriptor is found but there is an existing placeholder, remove the placeholder
@ -362,15 +362,15 @@ namespace Artemis.Core
private void LayerEffectStoreOnLayerEffectRemoved(object sender, LayerEffectStoreEvent e)
{
// If effects provided by the plugin are on the element, replace them with placeholders
var pluginEffects = _layerEffects.Where(ef => ef.Descriptor.LayerEffectProvider != null &&
ef.PluginInfo.Guid == e.Registration.Plugin.PluginInfo.Guid).ToList();
foreach (var pluginEffect in pluginEffects)
List<BaseLayerEffect> pluginEffects = _layerEffects.Where(ef => ef.Descriptor.LayerEffectProvider != null &&
ef.PluginInfo.Guid == e.Registration.Plugin.PluginInfo.Guid).ToList();
foreach (BaseLayerEffect pluginEffect in pluginEffects)
{
var entity = RenderElementEntity.LayerEffects.First(en => en.Id == pluginEffect.EntityId);
LayerEffectEntity entity = RenderElementEntity.LayerEffects.First(en => en.Id == pluginEffect.EntityId);
_layerEffects.Remove(pluginEffect);
pluginEffect.Dispose();
var descriptor = PlaceholderLayerEffectDescriptor.Create(pluginEffect.PluginInfo.Guid);
LayerEffectDescriptor descriptor = PlaceholderLayerEffectDescriptor.Create(pluginEffect.PluginInfo.Guid);
descriptor.CreateInstance(this, entity);
}
}
@ -420,7 +420,7 @@ namespace Artemis.Core
public void UpdateDisplayCondition()
{
var conditionMet = DisplayCondition == null || DisplayCondition.Evaluate();
bool conditionMet = DisplayCondition == null || DisplayCondition.Evaluate();
if (conditionMet && !DisplayConditionMet)
TimelinePosition = TimeSpan.Zero;

View File

@ -156,11 +156,11 @@ namespace Artemis.Core
if (!Leds.Any())
return;
foreach (var led in Leds)
foreach (ArtemisLed led in Leds)
led.CalculateRenderRectangle();
var path = new SKPath {FillType = SKPathFillType.Winding};
foreach (var artemisLed in Leds)
SKPath path = new SKPath {FillType = SKPathFillType.Winding};
foreach (ArtemisLed artemisLed in Leds)
path.AddRect(artemisLed.AbsoluteRenderRectangle);
RenderPath = path;

View File

@ -76,7 +76,7 @@ namespace Artemis.Core
public void UpdateScale(double value)
{
Scale = value;
foreach (var device in Devices)
foreach (ArtemisDevice device in Devices)
device.CalculateRenderProperties();
OnScaleChanged();
@ -89,7 +89,7 @@ namespace Artemis.Core
SurfaceEntity.IsActive = IsActive;
// Add missing device entities, don't remove old ones in case they come back later
foreach (var deviceEntity in Devices.Select(d => d.DeviceEntity).ToList())
foreach (DeviceEntity deviceEntity in Devices.Select(d => d.DeviceEntity).ToList())
{
if (!SurfaceEntity.DeviceEntities.Contains(deviceEntity))
SurfaceEntity.DeviceEntities.Add(deviceEntity);

View File

@ -1,4 +1,5 @@
using Ninject.Activation;
using System;
using Ninject.Activation;
using Serilog;
using Serilog.Core;
using Serilog.Events;
@ -21,7 +22,7 @@ namespace Artemis.Core.Ninject
protected override ILogger CreateInstance(IContext context)
{
var requestingType = context.Request.ParentContext?.Plan?.Type;
Type requestingType = context.Request.ParentContext?.Plan?.Type;
if (requestingType != null)
return Logger.ForContext(requestingType);
return Logger;

View File

@ -18,12 +18,12 @@ namespace Artemis.Core.Ninject
protected override PluginSettings CreateInstance(IContext context)
{
var parentRequest = context.Request.ParentRequest;
IRequest parentRequest = context.Request.ParentRequest;
if (parentRequest == null)
throw new ArtemisCoreException("PluginSettings couldn't be injected, failed to get the injection parent request");
// First try by PluginInfo parameter
var pluginInfo = parentRequest.Parameters.FirstOrDefault(p => p.Name == "PluginInfo")?.GetValue(context, null) as PluginInfo;
PluginInfo pluginInfo = parentRequest.Parameters.FirstOrDefault(p => p.Name == "PluginInfo")?.GetValue(context, null) as PluginInfo;
if (pluginInfo == null)
pluginInfo = _pluginService.GetPluginByAssembly(parentRequest.Service.Assembly)?.PluginInfo;
// Fall back to assembly based detection

View File

@ -16,7 +16,7 @@ namespace Artemis.Core.Ninject
protected override ISettingsService CreateInstance(IContext context)
{
var parentRequest = context.Request.ParentRequest;
IRequest parentRequest = context.Request.ParentRequest;
if (parentRequest == null || typeof(Plugin).IsAssignableFrom(parentRequest.Service))
throw new ArtemisPluginException($"SettingsService can not be injected into a plugin. Inject {nameof(PluginSettings)} instead.");

View File

@ -74,7 +74,7 @@ namespace Artemis.Core.DataModelExpansions
if (_dynamicDataModels.ContainsValue(dynamicDataModel))
{
var existingKey = _dynamicDataModels.First(kvp => kvp.Value == dynamicDataModel).Key;
string existingKey = _dynamicDataModels.First(kvp => kvp.Value == dynamicDataModel).Key;
throw new ArtemisCoreException($"Cannot add a dynamic data model with key '{key}' " +
$"because the dynamic data model is already added with key '{existingKey}.");
}
@ -111,8 +111,8 @@ namespace Artemis.Core.DataModelExpansions
/// <param name="dynamicDataModel">The dynamic data model to remove</param>
public void RemoveDynamicChild(DataModel dynamicDataModel)
{
var keys = _dynamicDataModels.Where(kvp => kvp.Value == dynamicDataModel).Select(kvp => kvp.Key).ToList();
foreach (var key in keys)
List<string> keys = _dynamicDataModels.Where(kvp => kvp.Value == dynamicDataModel).Select(kvp => kvp.Key).ToList();
foreach (string key in keys)
_dynamicDataModels.Remove(key);
}
@ -124,17 +124,17 @@ namespace Artemis.Core.DataModelExpansions
/// <returns>If found, the dynamic data model otherwise <c>null</c></returns>
public T DynamicChild<T>(string key) where T : DataModel
{
_dynamicDataModels.TryGetValue(key, out var value);
_dynamicDataModels.TryGetValue(key, out DataModel value);
return value as T;
}
internal bool ContainsPath(string path)
{
var parts = path.Split('.');
var current = GetType();
foreach (var part in parts)
string[] parts = path.Split('.');
Type current = GetType();
foreach (string part in parts)
{
var property = current?.GetProperty(part);
PropertyInfo? property = current?.GetProperty(part);
current = property?.PropertyType;
if (property == null)
return false;
@ -148,13 +148,13 @@ namespace Artemis.Core.DataModelExpansions
if (!ContainsPath(path))
return null;
var parts = path.Split('.');
var current = GetType();
string[] parts = path.Split('.');
Type current = GetType();
Type result = null;
foreach (var part in parts)
foreach (string part in parts)
{
var property = current.GetProperty(part);
PropertyInfo? property = current.GetProperty(part);
current = property.PropertyType;
result = property.PropertyType;
}
@ -167,17 +167,17 @@ namespace Artemis.Core.DataModelExpansions
if (!ContainsPath(path))
return null;
var parts = path.Split('.');
var current = GetType();
string[] parts = path.Split('.');
Type current = GetType();
var index = 0;
foreach (var part in parts)
int index = 0;
foreach (string part in parts)
{
// Only return a type if the path CONTAINS a list, not if it points TO a list
if (index == parts.Length - 1)
return null;
var property = current.GetProperty(part);
PropertyInfo? property = current.GetProperty(part);
// For lists, look into the list type instead of the list itself
if (typeof(IList).IsAssignableFrom(property.PropertyType))
@ -195,7 +195,7 @@ namespace Artemis.Core.DataModelExpansions
if (!ContainsPath(path))
return null;
var child = GetTypeAtPath(path);
Type child = GetTypeAtPath(path);
return child.GenericTypeArguments.Length > 0 ? child.GenericTypeArguments[0] : null;
}

View File

@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Artemis.Core.DataModelExpansions
{
@ -25,7 +26,7 @@ namespace Artemis.Core.DataModelExpansions
/// <param name="propertyLambda">A lambda expression pointing to the property to ignore</param>
public void HideProperty<TProperty>(Expression<Func<T, TProperty>> propertyLambda)
{
var propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
PropertyInfo propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
if (!HiddenPropertiesList.Any(p => p.Equals(propertyInfo)))
HiddenPropertiesList.Add(propertyInfo);
}
@ -37,7 +38,7 @@ namespace Artemis.Core.DataModelExpansions
/// <param name="propertyLambda">A lambda expression pointing to the property to stop ignoring</param>
public void ShowProperty<TProperty>(Expression<Func<T, TProperty>> propertyLambda)
{
var propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
PropertyInfo propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
HiddenPropertiesList.RemoveAll(p => p.Equals(propertyInfo));
}

View File

@ -54,7 +54,7 @@ namespace Artemis.Core.DeviceProviders
else if (e.RelativePath != null)
e.FinalPath = Path.Combine(PluginInfo.Directory.FullName, e.RelativePath);
var deviceInfo = ((IRGBDevice) sender).DeviceInfo;
IRGBDeviceInfo deviceInfo = ((IRGBDevice) sender).DeviceInfo;
if (e.FileName != null && !File.Exists(e.FinalPath))
{
Logger?.Information("Couldn't find a layout for device {deviceName}, model {deviceModel} at {filePath}",

View File

@ -62,7 +62,7 @@ namespace Artemis.Core.LayerBrushes
if (layer.LayerBrush != null)
throw new ArtemisCoreException("Layer already has an instantiated layer brush");
var brush = (BaseLayerBrush) LayerBrushProvider.PluginInfo.Kernel.Get(LayerBrushType);
BaseLayerBrush brush = (BaseLayerBrush) LayerBrushProvider.PluginInfo.Kernel.Get(LayerBrushType);
brush.Layer = layer;
brush.Descriptor = this;
brush.Initialize();

View File

@ -41,7 +41,7 @@ namespace Artemis.Core.LayerBrushes
if (!Enabled)
throw new ArtemisPluginException(PluginInfo, "Can only add a layer brush descriptor when the plugin is enabled");
var descriptor = new LayerBrushDescriptor(displayName, description, icon, typeof(T), this);
LayerBrushDescriptor descriptor = new LayerBrushDescriptor(displayName, description, icon, typeof(T), this);
_layerBrushDescriptors.Add(descriptor);
LayerBrushStore.Add(descriptor);
}

View File

@ -36,14 +36,14 @@ namespace Artemis.Core.LayerBrushes
if (Layer.General.ResizeMode == LayerResizeMode.Normal)
{
// Apply a translated version of the shape as the clipping mask
var shapePath = new SKPath(Layer.LayerShape.Path);
SKPath shapePath = new SKPath(Layer.LayerShape.Path);
Layer.IncludePathInTranslation(shapePath, true);
canvas.ClipPath(shapePath);
}
using var pointsPath = new SKPath();
using var ledPaint = new SKPaint();
foreach (var artemisLed in Layer.Leds)
using SKPath pointsPath = new SKPath();
using SKPaint ledPaint = new SKPaint();
foreach (ArtemisLed artemisLed in Layer.Leds)
{
pointsPath.AddPoly(new[]
{
@ -53,18 +53,18 @@ namespace Artemis.Core.LayerBrushes
}
Layer.ExcludePathFromTranslation(pointsPath, true);
var points = pointsPath.Points;
for (var index = 0; index < Layer.Leds.Count; index++)
SKPoint[] points = pointsPath.Points;
for (int index = 0; index < Layer.Leds.Count; index++)
{
var artemisLed = Layer.Leds[index];
var renderPoint = points[index * 2 + 1];
ArtemisLed artemisLed = Layer.Leds[index];
SKPoint renderPoint = points[index * 2 + 1];
if (!float.IsFinite(renderPoint.X) || !float.IsFinite(renderPoint.Y))
continue;
// Let the brush determine the color
ledPaint.Color = GetColor(artemisLed, renderPoint);
var ledRectangle = SKRect.Create(
SKRect ledRectangle = SKRect.Create(
artemisLed.AbsoluteRenderRectangle.Left - Layer.Bounds.Left,
artemisLed.AbsoluteRenderRectangle.Top - Layer.Bounds.Top,
artemisLed.AbsoluteRenderRectangle.Width,

View File

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Artemis.Core.Services;
using RGB.NET.Core;
@ -39,8 +40,8 @@ namespace Artemis.Core.LayerBrushes
// TODO: This simply renders it on top of the rest, get a ZIndex based on layer position
LedGroup.ZIndex = 1;
var missingLeds = Layer.Leds.Where(l => !LedGroup.ContainsLed(l.RgbLed)).Select(l => l.RgbLed).ToList();
var extraLeds = LedGroup.GetLeds().Where(l => Layer.Leds.All(layerLed => layerLed.RgbLed != l)).ToList();
List<Led> missingLeds = Layer.Leds.Where(l => !LedGroup.ContainsLed(l.RgbLed)).Select(l => l.RgbLed).ToList();
List<Led> extraLeds = LedGroup.GetLeds().Where(l => Layer.Leds.All(layerLed => layerLed.RgbLed != l)).ToList();
LedGroup.AddLeds(missingLeds);
LedGroup.RemoveLeds(extraLeds);
LedGroup.Brush = GetBrush();

View File

@ -67,7 +67,7 @@ namespace Artemis.Core.LayerEffects
return;
}
var effect = (BaseLayerEffect) LayerEffectProvider.PluginInfo.Kernel.Get(LayerEffectType);
BaseLayerEffect effect = (BaseLayerEffect) LayerEffectProvider.PluginInfo.Kernel.Get(LayerEffectType);
effect.ProfileElement = renderElement;
effect.EntityId = entity.Id;
effect.Order = entity.Order;
@ -83,7 +83,7 @@ namespace Artemis.Core.LayerEffects
private void CreatePlaceHolderInstance(RenderProfileElement renderElement, LayerEffectEntity entity)
{
var effect = new PlaceholderLayerEffect(entity, PlaceholderFor.Value) {ProfileElement = renderElement, Descriptor = this};
PlaceholderLayerEffect effect = new PlaceholderLayerEffect(entity, PlaceholderFor.Value) {ProfileElement = renderElement, Descriptor = this};
effect.Initialize();
renderElement.ActivateLayerEffect(effect);
}

View File

@ -41,7 +41,7 @@ namespace Artemis.Core.LayerEffects
if (!Enabled)
throw new ArtemisPluginException(PluginInfo, "Can only add a layer effect descriptor when the plugin is enabled");
var descriptor = new LayerEffectDescriptor(displayName, description, icon, typeof(T), this);
LayerEffectDescriptor descriptor = new LayerEffectDescriptor(displayName, description, icon, typeof(T), this);
_layerEffectDescriptors.Add(descriptor);
LayerEffectStore.Add(descriptor);
}

View File

@ -6,7 +6,7 @@ namespace Artemis.Core.LayerEffects.Placeholder
{
public static LayerEffectDescriptor Create(Guid missingPluginGuid)
{
var descriptor = new LayerEffectDescriptor("Missing effect", "This effect could not be loaded", "FileQuestion", null, Constants.EffectPlaceholderPlugin)
LayerEffectDescriptor descriptor = new LayerEffectDescriptor("Missing effect", "This effect could not be loaded", "FileQuestion", null, Constants.EffectPlaceholderPlugin)
{
PlaceholderFor = missingPluginGuid
};

View File

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
@ -37,7 +38,7 @@ namespace Artemis.Core.Modules
if (ProcessName == null && Location == null)
return false;
var processes = ProcessName != null ? Process.GetProcessesByName(ProcessName).Where(p => !p.HasExited) : Process.GetProcesses().Where(p => !p.HasExited);
IEnumerable<Process> processes = ProcessName != null ? Process.GetProcessesByName(ProcessName).Where(p => !p.HasExited) : Process.GetProcesses().Where(p => !p.HasExited);
return Location != null
? processes.Any(p => string.Equals(Path.GetDirectoryName(p.GetProcessFilename()), Location, StringComparison.CurrentCultureIgnoreCase))
: processes.Any();
@ -46,7 +47,7 @@ namespace Artemis.Core.Modules
/// <inheritdoc />
public string GetUserFriendlyDescription()
{
var description = $"Requirement met when \"{ProcessName}.exe\" is running";
string description = $"Requirement met when \"{ProcessName}.exe\" is running";
if (Location != null)
description += $" from \"{Location}\"";

View File

@ -55,7 +55,7 @@ namespace Artemis.Core.Modules
/// <param name="propertyLambda">A lambda expression pointing to the property to ignore</param>
public void HideProperty<TProperty>(Expression<Func<T, TProperty>> propertyLambda)
{
var propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
PropertyInfo propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
if (!HiddenPropertiesList.Any(p => p.Equals(propertyInfo)))
HiddenPropertiesList.Add(propertyInfo);
}
@ -67,7 +67,7 @@ namespace Artemis.Core.Modules
/// <param name="propertyLambda">A lambda expression pointing to the property to stop ignoring</param>
public void ShowProperty<TProperty>(Expression<Func<T, TProperty>> propertyLambda)
{
var propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
PropertyInfo propertyInfo = ReflectionUtilities.GetPropertyInfo(DataModel, propertyLambda);
HiddenPropertiesList.RemoveAll(p => p.Equals(propertyInfo));
}
@ -227,7 +227,7 @@ namespace Artemis.Core.Modules
{
base.Deactivate(isOverride);
var profile = ActiveProfile;
Profile profile = ActiveProfile;
ActiveProfile = null;
profile?.Dispose();
}

View File

@ -75,7 +75,7 @@ namespace Artemis.Core
// Allow up to 15 seconds for plugins to activate.
// This means plugins that need more time should do their long running tasks in a background thread, which is intentional
// Little meh: Running this from a different thread could cause deadlocks
var enableTask = Task.Run(InternalEnablePlugin);
Task enableTask = Task.Run(InternalEnablePlugin);
if (!enableTask.Wait(TimeSpan.FromSeconds(15)))
throw new ArtemisPluginException(PluginInfo, "Plugin load timeout");

View File

@ -83,7 +83,7 @@ namespace Artemis.Core
if (!PluginInfo.Instance.Enabled)
return;
var interval = DateTime.Now - _lastEvent;
TimeSpan interval = DateTime.Now - _lastEvent;
_lastEvent = DateTime.Now;
// Modules don't always want to update, honor that

View File

@ -37,7 +37,7 @@ namespace Artemis.Core
if (_settingEntities.ContainsKey(name))
return (PluginSetting<T>) _settingEntities[name];
// Try to find in database
var settingEntity = _pluginRepository.GetSettingByNameAndGuid(name, _pluginInfo.Guid);
PluginSettingEntity settingEntity = _pluginRepository.GetSettingByNameAndGuid(name, _pluginInfo.Guid);
// If not found, create a new one
if (settingEntity == null)
{
@ -45,7 +45,7 @@ namespace Artemis.Core
_pluginRepository.AddSetting(settingEntity);
}
var pluginSetting = new PluginSetting<T>(_pluginInfo, _pluginRepository, settingEntity);
PluginSetting<T> pluginSetting = new PluginSetting<T>(_pluginInfo, _pluginRepository, settingEntity);
// This overrides null with the default value, I'm not sure if that's desirable because you
// might expect something to go null and you might not

View File

@ -94,9 +94,9 @@ namespace Artemis.Core
private void TakeCenter(IEnumerable<BrushRenderTarget> renderTargets)
{
foreach (var renderTarget in renderTargets)
foreach (BrushRenderTarget renderTarget in renderTargets)
{
var scaledLocation = renderTarget.Point * Scale;
Point scaledLocation = renderTarget.Point * Scale;
if (scaledLocation.X < Bitmap.Width && scaledLocation.Y < Bitmap.Height)
RenderedTargets[renderTarget] = Bitmap.GetPixel(scaledLocation.X.RoundToInt(), scaledLocation.Y.RoundToInt()).ToRgbColor();
}
@ -104,35 +104,35 @@ namespace Artemis.Core
private void TakeSamples(IEnumerable<BrushRenderTarget> renderTargets)
{
var sampleSize = _sampleSizeSetting.Value;
var sampleDepth = Math.Sqrt(sampleSize).RoundToInt();
int sampleSize = _sampleSizeSetting.Value;
int sampleDepth = Math.Sqrt(sampleSize).RoundToInt();
var bitmapWidth = Bitmap.Width;
var bitmapHeight = Bitmap.Height;
int bitmapWidth = Bitmap.Width;
int bitmapHeight = Bitmap.Height;
using var pixmap = Bitmap.PeekPixels();
foreach (var renderTarget in renderTargets)
using SKPixmap pixmap = Bitmap.PeekPixels();
foreach (BrushRenderTarget renderTarget in renderTargets)
{
// SKRect has all the good stuff we need
var left = (int) ((renderTarget.Rectangle.Location.X + 4) * Scale.Horizontal);
var top = (int) ((renderTarget.Rectangle.Location.Y + 4) * Scale.Vertical);
var width = (int) ((renderTarget.Rectangle.Size.Width - 8) * Scale.Horizontal);
var height = (int) ((renderTarget.Rectangle.Size.Height - 8) * Scale.Vertical);
int left = (int) ((renderTarget.Rectangle.Location.X + 4) * Scale.Horizontal);
int top = (int) ((renderTarget.Rectangle.Location.Y + 4) * Scale.Vertical);
int width = (int) ((renderTarget.Rectangle.Size.Width - 8) * Scale.Horizontal);
int height = (int) ((renderTarget.Rectangle.Size.Height - 8) * Scale.Vertical);
var verticalSteps = height / (sampleDepth - 1);
var horizontalSteps = width / (sampleDepth - 1);
int verticalSteps = height / (sampleDepth - 1);
int horizontalSteps = width / (sampleDepth - 1);
int a = 0, r = 0, g = 0, b = 0;
for (var horizontalStep = 0; horizontalStep < sampleDepth; horizontalStep++)
for (int horizontalStep = 0; horizontalStep < sampleDepth; horizontalStep++)
{
for (var verticalStep = 0; verticalStep < sampleDepth; verticalStep++)
for (int verticalStep = 0; verticalStep < sampleDepth; verticalStep++)
{
var x = left + horizontalSteps * horizontalStep;
var y = top + verticalSteps * verticalStep;
int x = left + horizontalSteps * horizontalStep;
int y = top + verticalSteps * verticalStep;
if (x < 0 || x >= bitmapWidth || y < 0 || y >= bitmapHeight)
continue;
var color = pixmap.GetPixelColor(x, y);
SKColor color = pixmap.GetPixelColor(x, y);
a += color.Alpha;
r += color.Red;
g += color.Green;
@ -149,8 +149,8 @@ namespace Artemis.Core
private void CreateBitmap(Rectangle rectangle)
{
var width = Math.Min((rectangle.Location.X + rectangle.Size.Width) * Scale.Horizontal, 4096);
var height = Math.Min((rectangle.Location.Y + rectangle.Size.Height) * Scale.Vertical, 4096);
double width = Math.Min((rectangle.Location.X + rectangle.Size.Width) * Scale.Horizontal, 4096);
double height = Math.Min((rectangle.Location.Y + rectangle.Size.Height) * Scale.Vertical, 4096);
Bitmap = new SKBitmap(new SKImageInfo(width.RoundToInt(), height.RoundToInt(), SKColorType.Rgb888x));
}

View File

@ -79,7 +79,7 @@ namespace Artemis.Core.Services
if (IsInitialized)
throw new ArtemisCoreException("Cannot initialize the core as it is already initialized.");
var versionAttribute = typeof(CoreService).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
AssemblyInformationalVersionAttribute? versionAttribute = typeof(CoreService).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
_logger.Information("Initializing Artemis Core version {version}", versionAttribute?.InformationalVersion);
ApplyLoggingLevel();
@ -89,7 +89,7 @@ namespace Artemis.Core.Services
_pluginService.CopyBuiltInPlugins();
_pluginService.LoadPlugins(StartupArguments.Contains("--ignore-plugin-lock"));
var surfaceConfig = _surfaceService.ActiveSurface;
ArtemisSurface surfaceConfig = _surfaceService.ActiveSurface;
if (surfaceConfig != null)
_logger.Information("Initialized with active surface entity {surfaceConfig}-{guid}", surfaceConfig.Name, surfaceConfig.EntityId);
else
@ -123,7 +123,7 @@ namespace Artemis.Core.Services
_introAnimation.Render(args.DeltaTime, args.Canvas, _rgbService.BitmapBrush.Bitmap.Info);
}
var introLength = _introAnimation.AnimationProfile.GetAllLayers().Max(l => l.TimelineLength);
TimeSpan introLength = _introAnimation.AnimationProfile.GetAllLayers().Max(l => l.TimelineLength);
// Stop rendering after the profile finishes (take 1 second extra in case of slow updates)
Task.Run(async () =>
@ -167,7 +167,7 @@ namespace Artemis.Core.Services
lock (_dataModelExpansions)
{
// Update all active modules
foreach (var dataModelExpansion in _dataModelExpansions)
foreach (BaseDataModelExpansion dataModelExpansion in _dataModelExpansions)
dataModelExpansion.Update(args.DeltaTime);
}
@ -181,7 +181,7 @@ namespace Artemis.Core.Services
}
// Update all active modules
foreach (var module in modules)
foreach (Module module in modules)
module.InternalUpdate(args.DeltaTime);
// If there is no ready bitmap brush, skip the frame
@ -194,12 +194,12 @@ namespace Artemis.Core.Services
return;
// Render all active modules
using var canvas = new SKCanvas(_rgbService.BitmapBrush.Bitmap);
using SKCanvas canvas = new SKCanvas(_rgbService.BitmapBrush.Bitmap);
canvas.Clear(new SKColor(0, 0, 0));
if (!ModuleRenderingDisabled)
{
// While non-activated modules may be updated above if they expand the main data model, they may never render
foreach (var module in modules.Where(m => m.IsActivated))
foreach (Module module in modules.Where(m => m.IsActivated))
module.InternalRender(args.DeltaTime, _surfaceService.ActiveSurface, canvas, _rgbService.BitmapBrush.Bitmap.Info);
}

View File

@ -16,7 +16,7 @@ namespace Artemis.Core.Services
private void BlinkDevice(ArtemisDevice device, int blinkCount)
{
// Create a LED group way at the top
var ledGroup = new ListLedGroup(device.Leds.Select(l => l.RgbLed))
ListLedGroup ledGroup = new ListLedGroup(device.Leds.Select(l => l.RgbLed))
{
Brush = new SolidColorBrush(new Color(255, 255, 255)),
ZIndex = 999

View File

@ -28,11 +28,11 @@ namespace Artemis.Core.Services
_profileService = profileService;
_pluginService.PluginEnabled += PluginServiceOnPluginEnabled;
var activationUpdateTimer = new Timer(2000);
Timer activationUpdateTimer = new Timer(2000);
activationUpdateTimer.Start();
activationUpdateTimer.Elapsed += ActivationUpdateTimerOnElapsed;
foreach (var module in _pluginService.GetPluginsOfType<Module>())
foreach (Module module in _pluginService.GetPluginsOfType<Module>())
InitialiseOrApplyPriority(module);
}
@ -56,8 +56,8 @@ namespace Artemis.Core.Services
_logger.Information("Clearing active module override");
// Always deactivate all other modules whenever override is called
var modules = _pluginService.GetPluginsOfType<Module>().ToList();
foreach (var module in modules.Where(m => m != overrideModule))
List<Module> modules = _pluginService.GetPluginsOfType<Module>().ToList();
foreach (Module module in modules.Where(m => m != overrideModule))
OverrideDeactivate(module);
ActiveModuleOverride = overrideModule;
@ -81,7 +81,7 @@ namespace Artemis.Core.Services
{
// The conditions of the active module override may be matched, in that case reactivate as a non-override
// the principle is different for this service but not for the module
var shouldBeActivated = ActiveModuleOverride.EvaluateActivationRequirements();
bool shouldBeActivated = ActiveModuleOverride.EvaluateActivationRequirements();
if (shouldBeActivated && ActiveModuleOverride.IsActivatedOverride)
{
ActiveModuleOverride.Deactivate(true);
@ -96,14 +96,14 @@ namespace Artemis.Core.Services
return;
}
var stopwatch = new Stopwatch();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var modules = _pluginService.GetPluginsOfType<Module>().ToList();
var tasks = new List<Task>();
foreach (var module in modules)
List<Module> modules = _pluginService.GetPluginsOfType<Module>().ToList();
List<Task> tasks = new List<Task>();
foreach (Module module in modules)
{
var shouldBeActivated = module.EvaluateActivationRequirements();
bool shouldBeActivated = module.EvaluateActivationRequirements();
if (shouldBeActivated && !module.IsActivated)
tasks.Add(ActivateModule(module));
else if (!shouldBeActivated && module.IsActivated)
@ -127,7 +127,7 @@ namespace Artemis.Core.Services
if (module.PriorityCategory == category && module.Priority == priority)
return;
var modules = _pluginService.GetPluginsOfType<Module>().Where(m => m.PriorityCategory == category).OrderBy(m => m.Priority).ToList();
List<Module> modules = _pluginService.GetPluginsOfType<Module>().Where(m => m.PriorityCategory == category).OrderBy(m => m.Priority).ToList();
if (modules.Contains(module))
modules.Remove(module);
@ -135,9 +135,9 @@ namespace Artemis.Core.Services
modules.Insert(priority, module);
module.PriorityCategory = category;
for (var index = 0; index < modules.Count; index++)
for (int index = 0; index < modules.Count; index++)
{
var categoryModule = modules[index];
Module categoryModule = modules[index];
categoryModule.Priority = index;
// Don't save modules whose priority hasn't been initialized yet
@ -236,8 +236,8 @@ namespace Artemis.Core.Services
private void InitialiseOrApplyPriority(Module module)
{
var category = module.DefaultPriorityCategory;
var priority = 1;
ModulePriorityCategory category = module.DefaultPriorityCategory;
int priority = 1;
module.Entity = _moduleRepository.GetByPluginGuid(module.PluginInfo.Guid);
if (module.Entity != null)

View File

@ -44,26 +44,26 @@ namespace Artemis.Core.Services
public void CopyBuiltInPlugins()
{
OnCopyingBuildInPlugins();
var pluginDirectory = new DirectoryInfo(Path.Combine(Constants.DataFolder, "plugins"));
DirectoryInfo pluginDirectory = new DirectoryInfo(Path.Combine(Constants.DataFolder, "plugins"));
// Iterate built-in plugins
var builtInPluginDirectory = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "Plugins"));
foreach (var subDirectory in builtInPluginDirectory.EnumerateDirectories())
DirectoryInfo builtInPluginDirectory = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "Plugins"));
foreach (DirectoryInfo subDirectory in builtInPluginDirectory.EnumerateDirectories())
{
// Load the metadata
var builtInMetadataFile = Path.Combine(subDirectory.FullName, "plugin.json");
string builtInMetadataFile = Path.Combine(subDirectory.FullName, "plugin.json");
if (!File.Exists(builtInMetadataFile))
throw new ArtemisPluginException("Couldn't find the built-in plugins metadata file at " + builtInMetadataFile);
var builtInPluginInfo = JsonConvert.DeserializeObject<PluginInfo>(File.ReadAllText(builtInMetadataFile));
PluginInfo builtInPluginInfo = JsonConvert.DeserializeObject<PluginInfo>(File.ReadAllText(builtInMetadataFile));
// Find the matching plugin in the plugin folder
var match = pluginDirectory.EnumerateDirectories().FirstOrDefault(d => d.Name == subDirectory.Name);
DirectoryInfo match = pluginDirectory.EnumerateDirectories().FirstOrDefault(d => d.Name == subDirectory.Name);
if (match == null)
CopyBuiltInPlugin(subDirectory);
else
{
var metadataFile = Path.Combine(match.FullName, "plugin.json");
string metadataFile = Path.Combine(match.FullName, "plugin.json");
if (!File.Exists(metadataFile))
{
_logger.Debug("Copying missing built-in plugin {builtInPluginInfo}", builtInPluginInfo);
@ -74,7 +74,7 @@ namespace Artemis.Core.Services
try
{
// Compare versions, copy if the same when debugging
var pluginInfo = JsonConvert.DeserializeObject<PluginInfo>(File.ReadAllText(metadataFile));
PluginInfo pluginInfo = JsonConvert.DeserializeObject<PluginInfo>(File.ReadAllText(metadataFile));
#if DEBUG
if (builtInPluginInfo.Version >= pluginInfo.Version)
{
@ -111,17 +111,17 @@ namespace Artemis.Core.Services
UnloadPlugins();
// Load the plugin assemblies into the plugin context
var pluginDirectory = new DirectoryInfo(Path.Combine(Constants.DataFolder, "plugins"));
foreach (var subDirectory in pluginDirectory.EnumerateDirectories())
DirectoryInfo pluginDirectory = new DirectoryInfo(Path.Combine(Constants.DataFolder, "plugins"));
foreach (DirectoryInfo subDirectory in pluginDirectory.EnumerateDirectories())
{
try
{
// Load the metadata
var metadataFile = Path.Combine(subDirectory.FullName, "plugin.json");
string metadataFile = Path.Combine(subDirectory.FullName, "plugin.json");
if (!File.Exists(metadataFile)) _logger.Warning(new ArtemisPluginException("Couldn't find the plugins metadata file at " + metadataFile), "Plugin exception");
// Locate the main entry
var pluginInfo = JsonConvert.DeserializeObject<PluginInfo>(File.ReadAllText(metadataFile));
PluginInfo pluginInfo = JsonConvert.DeserializeObject<PluginInfo>(File.ReadAllText(metadataFile));
pluginInfo.Directory = subDirectory;
LoadPlugin(pluginInfo);
@ -133,7 +133,7 @@ namespace Artemis.Core.Services
}
// Activate plugins after they are all loaded
foreach (var pluginInfo in _plugins.Where(p => p.Enabled))
foreach (PluginInfo pluginInfo in _plugins.Where(p => p.Enabled))
{
try
{
@ -172,14 +172,14 @@ namespace Artemis.Core.Services
if (_plugins.Contains(pluginInfo))
UnloadPlugin(pluginInfo);
var pluginEntity = _pluginRepository.GetPluginByGuid(pluginInfo.Guid);
PluginEntity pluginEntity = _pluginRepository.GetPluginByGuid(pluginInfo.Guid);
if (pluginEntity == null)
pluginEntity = new PluginEntity {Id = pluginInfo.Guid, IsEnabled = true};
pluginInfo.PluginEntity = pluginEntity;
pluginInfo.Enabled = pluginEntity.IsEnabled;
var mainFile = Path.Combine(pluginInfo.Directory.FullName, pluginInfo.Main);
string mainFile = Path.Combine(pluginInfo.Directory.FullName, pluginInfo.Main);
if (!File.Exists(mainFile))
throw new ArtemisPluginException(pluginInfo, "Couldn't find the plugins main entry at " + mainFile);
@ -215,10 +215,10 @@ namespace Artemis.Core.Services
if (pluginTypes.Count == 0)
throw new ArtemisPluginException(pluginInfo, "Plugin contains no implementation of Plugin");
var pluginType = pluginTypes.Single();
Type pluginType = pluginTypes.Single();
try
{
var parameters = new IParameter[]
IParameter[] parameters = new IParameter[]
{
new Parameter("PluginInfo", pluginInfo, false)
};
@ -365,8 +365,8 @@ namespace Artemis.Core.Services
private static void CopyBuiltInPlugin(DirectoryInfo builtInPluginDirectory)
{
var pluginDirectory = new DirectoryInfo(Path.Combine(Constants.DataFolder, "plugins", builtInPluginDirectory.Name));
var createLockFile = File.Exists(Path.Combine(pluginDirectory.FullName, "artemis.lock"));
DirectoryInfo pluginDirectory = new DirectoryInfo(Path.Combine(Constants.DataFolder, "plugins", builtInPluginDirectory.Name));
bool createLockFile = File.Exists(Path.Combine(pluginDirectory.FullName, "artemis.lock"));
// Remove the old directory if it exists
if (Directory.Exists(pluginDirectory.FullName))

View File

@ -11,9 +11,9 @@ namespace Artemis.Core.Services
public DataModelService(IPluginService pluginService)
{
// Add data models of already loaded plugins
foreach (var module in pluginService.GetPluginsOfType<Module>().Where(p => p.Enabled))
foreach (Module module in pluginService.GetPluginsOfType<Module>().Where(p => p.Enabled))
AddModuleDataModel(module);
foreach (var dataModelExpansion in pluginService.GetPluginsOfType<BaseDataModelExpansion>().Where(p => p.Enabled))
foreach (BaseDataModelExpansion dataModelExpansion in pluginService.GetPluginsOfType<BaseDataModelExpansion>().Where(p => p.Enabled))
AddDataModelExpansionDataModel(dataModelExpansion);
// Add data models of new plugins when they get enabled

View File

@ -36,7 +36,7 @@ namespace Artemis.Core.Services
public LayerBrushDescriptor GetDefaultLayerBrush()
{
var defaultReference = _settingsService.GetSetting("ProfileEditor.DefaultLayerBrushDescriptor", new LayerBrushReference
PluginSetting<LayerBrushReference> defaultReference = _settingsService.GetSetting("ProfileEditor.DefaultLayerBrushDescriptor", new LayerBrushReference
{
BrushPluginGuid = Guid.Parse("92a9d6ba-6f7a-4937-94d5-c1d715b4141a"),
BrushType = "ColorBrush"

View File

@ -64,7 +64,7 @@ namespace Artemis.Core.Services
return;
}
foreach (var surfaceDevice in deviceProvider.Devices)
foreach (IRGBDevice surfaceDevice in deviceProvider.Devices)
{
_logger.Debug("Device provider {deviceProvider} added {deviceName}",
deviceProvider.GetType().Name, surfaceDevice.DeviceInfo?.DeviceName);

View File

@ -38,13 +38,13 @@ namespace Artemis.Core.Services
public List<ProfileDescriptor> GetProfileDescriptors(ProfileModule module)
{
var profileEntities = _profileRepository.GetByPluginGuid(module.PluginInfo.Guid);
List<ProfileEntity> profileEntities = _profileRepository.GetByPluginGuid(module.PluginInfo.Guid);
return profileEntities.Select(e => new ProfileDescriptor(module, e)).ToList();
}
public ProfileDescriptor CreateProfileDescriptor(ProfileModule module, string name)
{
var profileEntity = new ProfileEntity {Id = Guid.NewGuid(), Name = name, PluginGuid = module.PluginInfo.Guid};
ProfileEntity profileEntity = new ProfileEntity {Id = Guid.NewGuid(), Name = name, PluginGuid = module.PluginInfo.Guid};
_profileRepository.Add(profileEntity);
return new ProfileDescriptor(module, profileEntity);
@ -52,14 +52,14 @@ namespace Artemis.Core.Services
public void ActivateLastProfile(ProfileModule profileModule)
{
var activeProfile = GetLastActiveProfile(profileModule);
ProfileDescriptor activeProfile = GetLastActiveProfile(profileModule);
if (activeProfile != null)
ActivateProfile(activeProfile);
}
public async Task ActivateLastProfileAnimated(ProfileModule profileModule)
{
var activeProfile = GetLastActiveProfile(profileModule);
ProfileDescriptor activeProfile = GetLastActiveProfile(profileModule);
if (activeProfile != null)
await ActivateProfileAnimated(activeProfile);
}
@ -69,11 +69,11 @@ namespace Artemis.Core.Services
if (profileDescriptor.ProfileModule.ActiveProfile?.EntityId == profileDescriptor.Id)
return profileDescriptor.ProfileModule.ActiveProfile;
var profileEntity = _profileRepository.Get(profileDescriptor.Id);
ProfileEntity profileEntity = _profileRepository.Get(profileDescriptor.Id);
if (profileEntity == null)
throw new ArtemisCoreException($"Cannot find profile named: {profileDescriptor.Name} ID: {profileDescriptor.Id}");
var profile = new Profile(profileDescriptor.ProfileModule, profileEntity);
Profile profile = new Profile(profileDescriptor.ProfileModule, profileEntity);
InstantiateProfile(profile);
profileDescriptor.ProfileModule.ChangeActiveProfile(profile, _surfaceService.ActiveSurface);
@ -87,11 +87,11 @@ namespace Artemis.Core.Services
if (profileDescriptor.ProfileModule.ActiveProfile?.EntityId == profileDescriptor.Id)
return profileDescriptor.ProfileModule.ActiveProfile;
var profileEntity = _profileRepository.Get(profileDescriptor.Id);
ProfileEntity profileEntity = _profileRepository.Get(profileDescriptor.Id);
if (profileEntity == null)
throw new ArtemisCoreException($"Cannot find profile named: {profileDescriptor.Name} ID: {profileDescriptor.Id}");
var profile = new Profile(profileDescriptor.ProfileModule, profileEntity);
Profile profile = new Profile(profileDescriptor.ProfileModule, profileEntity);
InstantiateProfile(profile);
void ActivatingProfileSurfaceUpdate(object sender, SurfaceConfigurationEventArgs e)
@ -146,23 +146,23 @@ namespace Artemis.Core.Services
public void DeleteProfile(ProfileDescriptor profileDescriptor)
{
var profileEntity = _profileRepository.Get(profileDescriptor.Id);
ProfileEntity profileEntity = _profileRepository.Get(profileDescriptor.Id);
_profileRepository.Remove(profileEntity);
}
public void UpdateProfile(Profile profile, bool includeChildren)
{
_logger.Debug("Updating profile " + profile);
var memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
string memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
profile.RedoStack.Clear();
profile.UndoStack.Push(memento);
profile.Save();
if (includeChildren)
{
foreach (var folder in profile.GetAllFolders())
foreach (Folder folder in profile.GetAllFolders())
folder.Save();
foreach (var layer in profile.GetAllLayers())
foreach (Layer layer in profile.GetAllLayers())
layer.Save();
}
@ -180,8 +180,8 @@ namespace Artemis.Core.Services
return false;
}
var top = profile.UndoStack.Pop();
var memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
string top = profile.UndoStack.Pop();
string memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
profile.RedoStack.Push(memento);
profile.ProfileEntity = JsonConvert.DeserializeObject<ProfileEntity>(top, MementoSettings);
@ -204,8 +204,8 @@ namespace Artemis.Core.Services
return false;
}
var top = profile.RedoStack.Pop();
var memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
string top = profile.RedoStack.Pop();
string memento = JsonConvert.SerializeObject(profile.ProfileEntity, MementoSettings);
profile.UndoStack.Push(memento);
profile.ProfileEntity = JsonConvert.DeserializeObject<ProfileEntity>(top, MementoSettings);
@ -224,7 +224,7 @@ namespace Artemis.Core.Services
public string ExportProfile(ProfileDescriptor profileDescriptor)
{
var profileEntity = _profileRepository.Get(profileDescriptor.Id);
ProfileEntity profileEntity = _profileRepository.Get(profileDescriptor.Id);
if (profileEntity == null)
throw new ArtemisCoreException($"Cannot find profile named: {profileDescriptor.Name} ID: {profileDescriptor.Id}");
@ -233,7 +233,7 @@ namespace Artemis.Core.Services
public ProfileDescriptor ImportProfile(string json, ProfileModule profileModule)
{
var profileEntity = JsonConvert.DeserializeObject<ProfileEntity>(json, ExportSettings);
ProfileEntity profileEntity = JsonConvert.DeserializeObject<ProfileEntity>(json, ExportSettings);
// Assign a new GUID to make sure it is unique in case of a previous import of the same content
profileEntity.UpdateGuid(Guid.NewGuid());
@ -245,11 +245,11 @@ namespace Artemis.Core.Services
public ProfileDescriptor GetLastActiveProfile(ProfileModule module)
{
var moduleProfiles = _profileRepository.GetByPluginGuid(module.PluginInfo.Guid);
List<ProfileEntity> moduleProfiles = _profileRepository.GetByPluginGuid(module.PluginInfo.Guid);
if (!moduleProfiles.Any())
return CreateProfileDescriptor(module, "Default");
var profileEntity = moduleProfiles.FirstOrDefault(p => p.IsActive) ?? moduleProfiles.FirstOrDefault();
ProfileEntity profileEntity = moduleProfiles.FirstOrDefault(p => p.IsActive) ?? moduleProfiles.FirstOrDefault();
return profileEntity == null ? null : new ProfileDescriptor(module, profileEntity);
}
@ -258,8 +258,8 @@ namespace Artemis.Core.Services
if (module.ActiveProfile == null)
return;
var profileEntities = _profileRepository.GetByPluginGuid(module.PluginInfo.Guid);
foreach (var profileEntity in profileEntities)
List<ProfileEntity> profileEntities = _profileRepository.GetByPluginGuid(module.PluginInfo.Guid);
foreach (ProfileEntity profileEntity in profileEntities)
{
profileEntity.IsActive = module.ActiveProfile.EntityId == profileEntity.Id;
_profileRepository.Save(profileEntity);
@ -272,8 +272,8 @@ namespace Artemis.Core.Services
/// <param name="surface"></param>
private void ActiveProfilesPopulateLeds(ArtemisSurface surface)
{
var profileModules = _pluginService.GetPluginsOfType<ProfileModule>();
foreach (var profileModule in profileModules.Where(p => p.ActiveProfile != null).ToList())
List<ProfileModule> profileModules = _pluginService.GetPluginsOfType<ProfileModule>();
foreach (ProfileModule profileModule in profileModules.Where(p => p.ActiveProfile != null).ToList())
profileModule.ActiveProfile.PopulateLeds(surface);
}

View File

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Artemis.Storage.Entities.Surface;
using Artemis.Storage.Repositories.Interfaces;
using RGB.NET.Core;
using Serilog;
@ -38,12 +39,12 @@ namespace Artemis.Core.Services
public ArtemisSurface CreateSurfaceConfiguration(string name)
{
// Create a blank config
var configuration = new ArtemisSurface(_rgbService.Surface, name, _renderScaleSetting.Value);
ArtemisSurface configuration = new ArtemisSurface(_rgbService.Surface, name, _renderScaleSetting.Value);
// Add all current devices
foreach (var rgbDevice in _rgbService.LoadedDevices)
foreach (IRGBDevice rgbDevice in _rgbService.LoadedDevices)
{
var plugin = _pluginService.GetPluginByDevice(rgbDevice);
Plugin plugin = _pluginService.GetPluginByDevice(rgbDevice);
configuration.Devices.Add(new ArtemisDevice(rgbDevice, plugin, configuration));
}
@ -69,7 +70,7 @@ namespace Artemis.Core.Services
lock (_surfaceConfigurations)
{
// Mark only the new surface as active
foreach (var configuration in _surfaceConfigurations)
foreach (ArtemisSurface configuration in _surfaceConfigurations)
{
configuration.IsActive = configuration == ActiveSurface;
configuration.ApplyToEntity();
@ -81,7 +82,7 @@ namespace Artemis.Core.Services
// Apply the active surface entity to the devices
if (ActiveSurface != null)
{
foreach (var device in ActiveSurface.Devices)
foreach (ArtemisDevice device in ActiveSurface.Devices)
device.ApplyToRgbDevice();
}
@ -95,7 +96,7 @@ namespace Artemis.Core.Services
surface.ApplyToEntity();
if (includeDevices)
{
foreach (var deviceConfiguration in surface.Devices)
foreach (ArtemisDevice deviceConfiguration in surface.Devices)
{
deviceConfiguration.ApplyToEntity();
if (surface.IsActive)
@ -115,7 +116,7 @@ namespace Artemis.Core.Services
lock (_surfaceConfigurations)
{
var entity = surface.SurfaceEntity;
SurfaceEntity entity = surface.SurfaceEntity;
_surfaceConfigurations.Remove(surface);
_surfaceRepository.Remove(entity);
}
@ -125,17 +126,17 @@ namespace Artemis.Core.Services
private void LoadFromRepository()
{
var configs = _surfaceRepository.GetAll();
foreach (var surfaceEntity in configs)
List<SurfaceEntity> configs = _surfaceRepository.GetAll();
foreach (SurfaceEntity surfaceEntity in configs)
{
// Create the surface entity
var surfaceConfiguration = new ArtemisSurface(_rgbService.Surface, surfaceEntity, _renderScaleSetting.Value);
foreach (var position in surfaceEntity.DeviceEntities)
ArtemisSurface surfaceConfiguration = new ArtemisSurface(_rgbService.Surface, surfaceEntity, _renderScaleSetting.Value);
foreach (DeviceEntity position in surfaceEntity.DeviceEntities)
{
var device = _rgbService.Surface.Devices.FirstOrDefault(d => d.GetDeviceIdentifier() == position.DeviceIdentifier);
IRGBDevice device = _rgbService.Surface.Devices.FirstOrDefault(d => d.GetDeviceIdentifier() == position.DeviceIdentifier);
if (device != null)
{
var plugin = _pluginService.GetPluginByDevice(device);
Plugin plugin = _pluginService.GetPluginByDevice(device);
surfaceConfiguration.Devices.Add(new ArtemisDevice(device, plugin, surfaceConfiguration, position));
}
}
@ -148,7 +149,7 @@ namespace Artemis.Core.Services
}
// When all surface configs are loaded, apply the active surface config
var active = SurfaceConfigurations.FirstOrDefault(c => c.IsActive);
ArtemisSurface active = SurfaceConfigurations.FirstOrDefault(c => c.IsActive);
if (active != null)
SetActiveSurfaceConfiguration(active);
else
@ -167,17 +168,17 @@ namespace Artemis.Core.Services
private void AddDeviceIfMissing(IRGBDevice rgbDevice, ArtemisSurface surface)
{
var deviceIdentifier = rgbDevice.GetDeviceIdentifier();
var device = surface.Devices.FirstOrDefault(d => d.DeviceEntity.DeviceIdentifier == deviceIdentifier);
string deviceIdentifier = rgbDevice.GetDeviceIdentifier();
ArtemisDevice device = surface.Devices.FirstOrDefault(d => d.DeviceEntity.DeviceIdentifier == deviceIdentifier);
if (device != null)
return;
// Find an existing device config and use that
var existingDeviceConfig = surface.SurfaceEntity.DeviceEntities.FirstOrDefault(d => d.DeviceIdentifier == deviceIdentifier);
DeviceEntity existingDeviceConfig = surface.SurfaceEntity.DeviceEntities.FirstOrDefault(d => d.DeviceIdentifier == deviceIdentifier);
if (existingDeviceConfig != null)
{
var plugin = _pluginService.GetPluginByDevice(rgbDevice);
Plugin plugin = _pluginService.GetPluginByDevice(rgbDevice);
device = new ArtemisDevice(rgbDevice, plugin, surface, existingDeviceConfig);
}
// Fall back on creating a new device
@ -188,7 +189,7 @@ namespace Artemis.Core.Services
rgbDevice.DeviceInfo,
deviceIdentifier
);
var plugin = _pluginService.GetPluginByDevice(rgbDevice);
Plugin plugin = _pluginService.GetPluginByDevice(rgbDevice);
device = new ArtemisDevice(rgbDevice, plugin, surface);
}
@ -203,7 +204,7 @@ namespace Artemis.Core.Services
{
lock (_surfaceConfigurations)
{
foreach (var surfaceConfiguration in _surfaceConfigurations)
foreach (ArtemisSurface surfaceConfiguration in _surfaceConfigurations)
AddDeviceIfMissing(e.Device, surfaceConfiguration);
}
@ -212,7 +213,7 @@ namespace Artemis.Core.Services
private void RenderScaleSettingOnSettingChanged(object sender, EventArgs e)
{
foreach (var surfaceConfiguration in SurfaceConfigurations)
foreach (ArtemisSurface surfaceConfiguration in SurfaceConfigurations)
{
surfaceConfiguration.UpdateScale(_renderScaleSetting.Value);
OnSurfaceConfigurationUpdated(new SurfaceConfigurationEventArgs(surfaceConfiguration));

View File

@ -53,13 +53,13 @@ namespace Artemis.Core
if (type == null)
return new List<ConditionOperatorRegistration>(Registrations);
var candidates = Registrations.Where(r => r.ConditionOperator.CompatibleTypes.Any(t => t.IsCastableFrom(type))).ToList();
List<ConditionOperatorRegistration> candidates = Registrations.Where(r => r.ConditionOperator.CompatibleTypes.Any(t => t.IsCastableFrom(type))).ToList();
// If there are multiple operators with the same description, use the closest match
foreach (var candidate in candidates.GroupBy(r => r.ConditionOperator.Description).Where(g => g.Count() > 1).ToList())
foreach (IGrouping<string, ConditionOperatorRegistration> candidate in candidates.GroupBy(r => r.ConditionOperator.Description).Where(g => g.Count() > 1).ToList())
{
var closest = candidate.OrderByDescending(r => r.ConditionOperator.CompatibleTypes.Contains(type)).FirstOrDefault();
foreach (var conditionOperator in candidate)
ConditionOperatorRegistration closest = candidate.OrderByDescending(r => r.ConditionOperator.CompatibleTypes.Contains(type)).FirstOrDefault();
foreach (ConditionOperatorRegistration conditionOperator in candidate)
{
if (conditionOperator != closest)
candidates.Remove(conditionOperator);

View File

@ -53,13 +53,13 @@ namespace Artemis.Core
if (type == null)
return new List<DataBindingModifierTypeRegistration>(Registrations);
var candidates = Registrations.Where(r => r.DataBindingModifierType.CompatibleTypes.Any(t => t == type)).ToList();
List<DataBindingModifierTypeRegistration> candidates = Registrations.Where(r => r.DataBindingModifierType.CompatibleTypes.Any(t => t == type)).ToList();
// If there are multiple operators with the same description, use the closest match
foreach (var displayDataBindingModifiers in candidates.GroupBy(r => r.DataBindingModifierType.Name).Where(g => g.Count() > 1).ToList())
foreach (IGrouping<string, DataBindingModifierTypeRegistration> displayDataBindingModifiers in candidates.GroupBy(r => r.DataBindingModifierType.Name).Where(g => g.Count() > 1).ToList())
{
var closest = displayDataBindingModifiers.OrderByDescending(r => r.DataBindingModifierType.CompatibleTypes.Contains(type)).FirstOrDefault();
foreach (var displayDataBindingModifier in displayDataBindingModifiers)
DataBindingModifierTypeRegistration closest = displayDataBindingModifiers.OrderByDescending(r => r.DataBindingModifierType.CompatibleTypes.Contains(type)).FirstOrDefault();
foreach (DataBindingModifierTypeRegistration displayDataBindingModifier in displayDataBindingModifiers)
{
if (displayDataBindingModifier != closest)
candidates.Remove(displayDataBindingModifier);

View File

@ -21,12 +21,12 @@ namespace Artemis.Core
public static void Shutdown(int delay, bool restart)
{
// Always kill the process after the delay has passed, with all the plugins a graceful shutdown cannot be guaranteed
var arguments = "-Command \"& {Start-Sleep -s " + delay + "; (Get-Process 'Artemis.UI').kill()}";
string arguments = "-Command \"& {Start-Sleep -s " + delay + "; (Get-Process 'Artemis.UI').kill()}";
// If restart is required, start the executable again after the process was killed
if (restart)
arguments = "-Command \"& {Start-Sleep -s " + delay + "; (Get-Process 'Artemis.UI').kill(); Start-Process -FilePath '" + Process.GetCurrentProcess().MainModule.FileName + "'}\"";
var info = new ProcessStartInfo
ProcessStartInfo info = new ProcessStartInfo
{
Arguments = arguments,
WindowStyle = ProcessWindowStyle.Hidden,

View File

@ -106,7 +106,7 @@ namespace Artemis.Core
/// </summary>
public static double CubicEaseOut(double p)
{
var f = p - 1;
double f = p - 1;
return f * f * f + 1;
}
@ -119,7 +119,7 @@ namespace Artemis.Core
{
if (p < 0.5)
return 4 * p * p * p;
var f = 2 * p - 2;
double f = 2 * p - 2;
return 0.5 * f * f * f + 1;
}
@ -136,7 +136,7 @@ namespace Artemis.Core
/// </summary>
public static double QuarticEaseOut(double p)
{
var f = p - 1;
double f = p - 1;
return f * f * f * (1 - p) + 1;
}
@ -149,7 +149,7 @@ namespace Artemis.Core
{
if (p < 0.5)
return 8 * p * p * p * p;
var f = p - 1;
double f = p - 1;
return -8 * f * f * f * f + 1;
}
@ -166,7 +166,7 @@ namespace Artemis.Core
/// </summary>
public static double QuinticEaseOut(double p)
{
var f = p - 1;
double f = p - 1;
return f * f * f * f * f + 1;
}
@ -179,7 +179,7 @@ namespace Artemis.Core
{
if (p < 0.5)
return 16 * p * p * p * p * p;
var f = 2 * p - 2;
double f = 2 * p - 2;
return 0.5 * f * f * f * f * f + 1;
}
@ -306,7 +306,7 @@ namespace Artemis.Core
/// </summary>
public static double BackEaseOut(double p)
{
var f = 1 - p;
double f = 1 - p;
return 1 - (f * f * f - f * Math.Sin(f * PI));
}
@ -319,12 +319,12 @@ namespace Artemis.Core
{
if (p < 0.5)
{
var f = 2 * p;
double f = 2 * p;
return 0.5 * (f * f * f - f * Math.Sin(f * PI));
}
else
{
var f = 1 - (2 * p - 1);
double f = 1 - (2 * p - 1);
return 0.5 * (1 - (f * f * f - f * Math.Sin(f * PI))) + 0.5;
}
}

View File

@ -20,9 +20,9 @@ namespace Artemis.Core
// Create an expression that checks every part of the path for null
// In the same iteration, create the accessor
Expression condition = null;
foreach (var memberName in path.Split('.'))
foreach (string memberName in path.Split('.'))
{
var notNull = Expression.NotEqual(source, Expression.Constant(null));
BinaryExpression notNull = Expression.NotEqual(source, Expression.Constant(null));
condition = condition != null ? Expression.AndAlso(condition, notNull) : notNull;
source = Expression.PropertyOrField(source, memberName);
}

View File

@ -40,10 +40,10 @@ namespace Artemis.Core
try
{
// Load the intro profile from JSON into a ProfileEntity
var json = File.ReadAllText(Path.Combine(Constants.ApplicationFolder, "Resources", "intro-profile.json"));
var profileEntity = JsonConvert.DeserializeObject<ProfileEntity>(json);
string json = File.ReadAllText(Path.Combine(Constants.ApplicationFolder, "Resources", "intro-profile.json"));
ProfileEntity profileEntity = JsonConvert.DeserializeObject<ProfileEntity>(json);
// Inject every LED on the surface into each layer
foreach (var profileEntityLayer in profileEntity.Layers)
foreach (LayerEntity profileEntityLayer in profileEntity.Layers)
{
profileEntityLayer.Leds.AddRange(_surfaceService.ActiveSurface.Devices.SelectMany(d => d.Leds).Select(l => new LedEntity
{
@ -52,7 +52,7 @@ namespace Artemis.Core
}));
}
var profile = new Profile(new DummyModule(), profileEntity);
Profile profile = new Profile(new DummyModule(), profileEntity);
profile.Activate(_surfaceService.ActiveSurface);
_profileService.InstantiateProfile(profile);

View File

@ -8,13 +8,13 @@ namespace Artemis.Core
{
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(TSource source, Expression<Func<TSource, TProperty>> propertyLambda)
{
var type = typeof(TSource);
Type type = typeof(TSource);
var member = propertyLambda.Body as MemberExpression;
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.", propertyLambda));
var propInfo = member.Member as PropertyInfo;
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.", propertyLambda));

View File

@ -23,10 +23,10 @@ namespace Artemis.Storage.Entities.Profile
public void UpdateGuid(Guid guid)
{
var oldGuid = Id;
Guid oldGuid = Id;
Id = guid;
var rootFolder = Folders.FirstOrDefault(f => f.ParentId == oldGuid);
FolderEntity rootFolder = Folders.FirstOrDefault(f => f.ParentId == oldGuid);
if (rootFolder != null)
rootFolder.ParentId = Id;
}

View File

@ -1,4 +1,5 @@
using Artemis.Storage.Entities.Profile;
using System.Collections.Generic;
using Artemis.Storage.Entities.Profile;
using Artemis.Storage.Migrations.Interfaces;
using LiteDB;
@ -10,20 +11,20 @@ namespace Artemis.Storage.Migrations
public void Apply(LiteRepository repository)
{
var profiles = repository.Query<ProfileEntity>().ToList();
foreach (var profileEntity in profiles)
List<ProfileEntity> profiles = repository.Query<ProfileEntity>().ToList();
foreach (ProfileEntity profileEntity in profiles)
{
foreach (var profileEntityFolder in profileEntity.Folders)
foreach (FolderEntity profileEntityFolder in profileEntity.Folders)
{
profileEntityFolder.Enabled = true;
foreach (var layerEffectEntity in profileEntityFolder.LayerEffects)
foreach (LayerEffectEntity layerEffectEntity in profileEntityFolder.LayerEffects)
layerEffectEntity.Enabled = true;
}
foreach (var profileEntityLayer in profileEntity.Layers)
foreach (LayerEntity profileEntityLayer in profileEntity.Layers)
{
profileEntityLayer.Enabled = true;
foreach (var layerEffectEntity in profileEntityLayer.LayerEffects)
foreach (LayerEffectEntity layerEffectEntity in profileEntityLayer.LayerEffects)
layerEffectEntity.Enabled = true;
}

View File

@ -2,6 +2,7 @@
using Artemis.Storage.Migrations.Interfaces;
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Artemis.Storage.Migrations
@ -12,10 +13,10 @@ namespace Artemis.Storage.Migrations
public void Apply(LiteRepository repository)
{
var profiles = repository.Query<ProfileEntity>().ToList();
foreach (var profileEntity in profiles)
List<ProfileEntity> profiles = repository.Query<ProfileEntity>().ToList();
foreach (ProfileEntity profileEntity in profiles)
{
foreach (var folder in profileEntity.Folders.Where(f => f.MainSegmentLength == TimeSpan.Zero))
foreach (FolderEntity folder in profileEntity.Folders.Where(f => f.MainSegmentLength == TimeSpan.Zero))
{
if (folder.PropertyEntities.Any(p => p.KeyframeEntities.Any()))
folder.MainSegmentLength = folder.PropertyEntities.Where(p => p.KeyframeEntities.Any()).Max(p => p.KeyframeEntities.Max(k => k.Position));
@ -25,7 +26,7 @@ namespace Artemis.Storage.Migrations
folder.DisplayContinuously = true;
}
foreach (var layer in profileEntity.Layers.Where(l => l.MainSegmentLength == TimeSpan.Zero))
foreach (LayerEntity layer in profileEntity.Layers.Where(l => l.MainSegmentLength == TimeSpan.Zero))
{
if (layer.PropertyEntities.Any(p => p.KeyframeEntities.Any()))
layer.MainSegmentLength = layer.PropertyEntities.Where(p => p.KeyframeEntities.Any()).Max(p => p.KeyframeEntities.Max(k => k.Position));

View File

@ -9,18 +9,18 @@ namespace Artemis.Storage.Migrations
public void Apply(LiteRepository repository)
{
var collection = repository.Database.GetCollection("ProfileEntity");
foreach (var bsonDocument in collection.FindAll())
ILiteCollection<BsonDocument> collection = repository.Database.GetCollection("ProfileEntity");
foreach (BsonDocument bsonDocument in collection.FindAll())
{
foreach (var bsonLayer in bsonDocument["Layers"].AsArray)
foreach (BsonValue bsonLayer in bsonDocument["Layers"].AsArray)
{
foreach (var bsonPropertyEntity in bsonLayer["PropertyEntities"].AsArray)
foreach (BsonValue bsonPropertyEntity in bsonLayer["PropertyEntities"].AsArray)
bsonPropertyEntity["DataBindingEntities"].AsArray.Clear();
}
foreach (var bsonLayer in bsonDocument["Folders"].AsArray)
foreach (BsonValue bsonLayer in bsonDocument["Folders"].AsArray)
{
foreach (var bsonPropertyEntity in bsonLayer["PropertyEntities"].AsArray)
foreach (BsonValue bsonPropertyEntity in bsonLayer["PropertyEntities"].AsArray)
bsonPropertyEntity["DataBindingEntities"].AsArray.Clear();
}

View File

@ -23,7 +23,7 @@ namespace Artemis.Storage
public void ApplyPendingMigrations()
{
foreach (var storageMigration in _migrations.OrderBy(m => m.UserVersion))
foreach (IStorageMigration storageMigration in _migrations.OrderBy(m => m.UserVersion))
{
if (_repository.Database.UserVersion >= storageMigration.UserVersion)
continue;

View File

@ -12,7 +12,7 @@ namespace Artemis.UI.Shared
if (Initialized)
return;
var colorPickerService = kernel.Get<IColorPickerService>();
IColorPickerService colorPickerService = kernel.Get<IColorPickerService>();
GradientPicker.ColorPickerService = colorPickerService;
ColorPicker.ColorPickerService = colorPickerService;

View File

@ -97,7 +97,7 @@ namespace Artemis.UI.Shared
private static void ColorPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorPicker = (ColorPicker) d;
ColorPicker colorPicker = (ColorPicker) d;
if (colorPicker._inCallback)
return;
@ -112,7 +112,7 @@ namespace Artemis.UI.Shared
private static void PopupOpenPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorPicker = (ColorPicker) d;
ColorPicker colorPicker = (ColorPicker) d;
if (colorPicker._inCallback)
return;
@ -123,7 +123,7 @@ namespace Artemis.UI.Shared
private static void StaysOpenPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorPicker = (ColorPicker) d;
ColorPicker colorPicker = (ColorPicker) d;
if (colorPicker._inCallback)
return;
@ -134,13 +134,13 @@ namespace Artemis.UI.Shared
private static void ColorOpacityPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorPicker = (ColorPicker) d;
ColorPicker colorPicker = (ColorPicker) d;
if (colorPicker._inCallback)
return;
colorPicker._inCallback = true;
var color = colorPicker.Color;
Color color = colorPicker.Color;
if (e.NewValue is byte opacity)
color = Color.FromArgb(opacity, color.R, color.G, color.B);
colorPicker.SetCurrentValue(ColorProperty, color);

View File

@ -97,9 +97,9 @@ namespace Artemis.UI.Shared
return;
// Determine the scale required to fit the desired size of the control
var measureSize = MeasureDevice();
var scale = Math.Min(DesiredSize.Width / measureSize.Width, DesiredSize.Height / measureSize.Height);
var scaledRect = new Rect(0, 0, measureSize.Width * scale, measureSize.Height * scale);
Size measureSize = MeasureDevice();
double scale = Math.Min(DesiredSize.Width / measureSize.Width, DesiredSize.Height / measureSize.Height);
Rect scaledRect = new Rect(0, 0, measureSize.Width * scale, measureSize.Height * scale);
// Center and scale the visualization in the desired bounding box
if (DesiredSize.Width > 0 && DesiredSize.Height > 0)
@ -109,7 +109,7 @@ namespace Artemis.UI.Shared
}
// Determine the offset required to rotate within bounds
var rotationRect = new Rect(0, 0, Device.RgbDevice.ActualSize.Width, Device.RgbDevice.ActualSize.Height);
Rect rotationRect = new Rect(0, 0, Device.RgbDevice.ActualSize.Width, Device.RgbDevice.ActualSize.Height);
rotationRect.Transform(new RotateTransform(Device.Rotation).Value);
// Apply device rotation
@ -123,7 +123,7 @@ namespace Artemis.UI.Shared
if (_deviceImage != null)
drawingContext.DrawImage(_deviceImage, new Rect(0, 0, Device.RgbDevice.Size.Width, Device.RgbDevice.Size.Height));
foreach (var deviceVisualizerLed in _deviceVisualizerLeds)
foreach (DeviceVisualizerLed deviceVisualizerLed in _deviceVisualizerLeds)
deviceVisualizerLed.RenderImage(drawingContext);
drawingContext.DrawDrawing(_backingStore);
@ -135,7 +135,7 @@ namespace Artemis.UI.Shared
if (Device == null)
return Size.Empty;
var deviceSize = MeasureDevice();
Size deviceSize = MeasureDevice();
if (deviceSize.Width <= 0 || deviceSize.Height <= 0)
return Size.Empty;
@ -162,7 +162,7 @@ namespace Artemis.UI.Shared
if (Device == null)
return Size.Empty;
var rotationRect = new Rect(0, 0, Device.RgbDevice.ActualSize.Width, Device.RgbDevice.ActualSize.Height);
Rect rotationRect = new Rect(0, 0, Device.RgbDevice.ActualSize.Width, Device.RgbDevice.ActualSize.Height);
rotationRect.Transform(new RotateTransform(Device.Rotation).Value);
return rotationRect.Size;
@ -198,13 +198,13 @@ namespace Artemis.UI.Shared
private static void DevicePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var deviceVisualizer = (DeviceVisualizer) d;
DeviceVisualizer deviceVisualizer = (DeviceVisualizer) d;
deviceVisualizer.Dispatcher.Invoke(() => { deviceVisualizer.SetupForDevice(); });
}
private static void ShowColorsPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var deviceVisualizer = (DeviceVisualizer) d;
DeviceVisualizer deviceVisualizer = (DeviceVisualizer) d;
deviceVisualizer.Dispatcher.Invoke(() => { deviceVisualizer.SetupForDevice(); });
}
@ -228,7 +228,7 @@ namespace Artemis.UI.Shared
_deviceImage = new BitmapImage(Device.RgbDevice.DeviceInfo.Image);
// Create all the LEDs
foreach (var artemisLed in Device.Leds)
foreach (ArtemisLed artemisLed in Device.Leds)
_deviceVisualizerLeds.Add(new DeviceVisualizerLed(artemisLed));
if (!ShowColors)
@ -238,16 +238,16 @@ namespace Artemis.UI.Shared
}
// Create the opacity drawing group
var opacityDrawingGroup = new DrawingGroup();
var drawingContext = opacityDrawingGroup.Open();
foreach (var deviceVisualizerLed in _deviceVisualizerLeds)
DrawingGroup opacityDrawingGroup = new DrawingGroup();
DrawingContext drawingContext = opacityDrawingGroup.Open();
foreach (DeviceVisualizerLed deviceVisualizerLed in _deviceVisualizerLeds)
deviceVisualizerLed.RenderOpacityMask(drawingContext);
drawingContext.Close();
// Render the store as a bitmap
var drawingImage = new DrawingImage(opacityDrawingGroup);
var image = new Image {Source = drawingImage};
var bitmap = new RenderTargetBitmap(
DrawingImage drawingImage = new DrawingImage(opacityDrawingGroup);
Image image = new Image {Source = drawingImage};
RenderTargetBitmap bitmap = new RenderTargetBitmap(
Math.Max(1, (int) (opacityDrawingGroup.Bounds.Width * 2.5)),
Math.Max(1, (int) (opacityDrawingGroup.Bounds.Height * 2.5)),
96,
@ -259,7 +259,7 @@ namespace Artemis.UI.Shared
bitmap.Freeze();
// Set the bitmap as the opacity mask for the colors backing store
var bitmapBrush = new ImageBrush(bitmap);
ImageBrush bitmapBrush = new ImageBrush(bitmap);
bitmapBrush.Freeze();
_backingStore.OpacityMask = bitmapBrush;
@ -275,16 +275,16 @@ namespace Artemis.UI.Shared
private void Render()
{
var drawingContext = _backingStore.Open();
DrawingContext drawingContext = _backingStore.Open();
if (HighlightedLeds != null && HighlightedLeds.Any())
{
foreach (var deviceVisualizerLed in _deviceVisualizerLeds)
foreach (DeviceVisualizerLed deviceVisualizerLed in _deviceVisualizerLeds)
deviceVisualizerLed.RenderColor(drawingContext, !HighlightedLeds.Contains(deviceVisualizerLed.Led));
}
else
{
foreach (var deviceVisualizerLed in _deviceVisualizerLeds)
foreach (DeviceVisualizerLed deviceVisualizerLed in _deviceVisualizerLeds)
deviceVisualizerLed.RenderColor(drawingContext, false);
}

View File

@ -39,9 +39,9 @@ namespace Artemis.UI.Shared
if (DisplayGeometry == null)
return;
var r = Led.RgbLed.Color.GetR();
var g = Led.RgbLed.Color.GetG();
var b = Led.RgbLed.Color.GetB();
byte r = Led.RgbLed.Color.GetR();
byte g = Led.RgbLed.Color.GetG();
byte b = Led.RgbLed.Color.GetB();
drawingContext.DrawRectangle(isDimmed
? new SolidColorBrush(Color.FromArgb(100, r, g, b))
@ -61,9 +61,9 @@ namespace Artemis.UI.Shared
if (DisplayGeometry == null)
return;
var fillBrush = new SolidColorBrush(Color.FromArgb(100, 255, 255, 255));
SolidColorBrush fillBrush = new SolidColorBrush(Color.FromArgb(100, 255, 255, 255));
fillBrush.Freeze();
var penBrush = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
SolidColorBrush penBrush = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
penBrush.Freeze();
// Create transparent pixels covering the entire LedRect so the image size matched the LedRect size

View File

@ -72,7 +72,7 @@ namespace Artemis.UI.Shared
private void UpdateValue(string value)
{
if (!float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedResult))
if (!float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float parsedResult))
return;
Value = parsedResult;
@ -110,7 +110,7 @@ namespace Artemis.UI.Shared
private static void FloatPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var draggableFloat = (DraggableFloat) d;
DraggableFloat draggableFloat = (DraggableFloat) d;
if (draggableFloat._inCallback)
return;
@ -133,7 +133,7 @@ namespace Artemis.UI.Shared
{
e.Handled = true;
var position = e.GetPosition((IInputElement) sender);
Point position = e.GetPosition((IInputElement) sender);
if (position == _mouseDragStartPoint)
DisplayInput();
else
@ -159,17 +159,17 @@ namespace Artemis.UI.Shared
}
// Use decimals for everything to avoid floating point errors
var startValue = new decimal(_startValue);
var startX = new decimal(_mouseDragStartPoint.X);
var x = new decimal(e.GetPosition((IInputElement) sender).X);
var stepSize = new decimal(StepSize);
decimal startValue = new decimal(_startValue);
decimal startX = new decimal(_mouseDragStartPoint.X);
decimal x = new decimal(e.GetPosition((IInputElement) sender).X);
decimal stepSize = new decimal(StepSize);
if (stepSize == 0)
stepSize = 0.1m;
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
stepSize = stepSize * 10;
var value = (float) RoundToNearestOf(startValue + stepSize * (x - startX), stepSize);
float value = (float) RoundToNearestOf(startValue + stepSize * (x - startX), stepSize);
if (Min != null)
value = Math.Max(value, Min.Value);
if (Max != null)
@ -208,7 +208,7 @@ namespace Artemis.UI.Shared
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
var text = (string) e.DataObject.GetData(typeof(string));
string text = (string) e.DataObject.GetData(typeof(string));
if (!_inputRegex.IsMatch(text))
e.CancelCommand();
}

View File

@ -78,7 +78,7 @@ namespace Artemis.UI.Shared
private static void ColorGradientPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var gradientPicker = (GradientPicker) d;
GradientPicker gradientPicker = (GradientPicker) d;
if (gradientPicker._inCallback)
return;

View File

@ -20,12 +20,12 @@ namespace Artemis.UI.Shared
/// <inheritdoc />
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var colorGradients = (BindableCollection<ColorGradientStop>) value;
var collection = new GradientStopCollection();
BindableCollection<ColorGradientStop> colorGradients = (BindableCollection<ColorGradientStop>) value;
GradientStopCollection collection = new GradientStopCollection();
if (colorGradients == null)
return collection;
foreach (var c in colorGradients.OrderBy(s => s.Position))
foreach (ColorGradientStop c in colorGradients.OrderBy(s => s.Position))
collection.Add(new GradientStop(Color.FromArgb(c.Color.Alpha, c.Color.Red, c.Color.Green, c.Color.Blue), c.Position));
return collection;
}
@ -33,12 +33,12 @@ namespace Artemis.UI.Shared
/// <inheritdoc />
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var collection = (GradientStopCollection) value;
var colorGradients = new BindableCollection<ColorGradientStop>();
GradientStopCollection collection = (GradientStopCollection) value;
BindableCollection<ColorGradientStop> colorGradients = new BindableCollection<ColorGradientStop>();
if (collection == null)
return colorGradients;
foreach (var c in collection.OrderBy(s => s.Offset))
foreach (GradientStop c in collection.OrderBy(s => s.Offset))
colorGradients.Add(new ColorGradientStop(new SKColor(c.Color.R, c.Color.G, c.Color.B, c.Color.A), (float) c.Offset));
return colorGradients;
}

View File

@ -16,14 +16,14 @@ namespace Artemis.UI.Shared
/// <inheritdoc />
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var skColor = (SKColor) value;
SKColor skColor = (SKColor) value;
return Color.FromArgb(skColor.Alpha, skColor.Red, skColor.Green, skColor.Blue);
}
/// <inheritdoc />
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var color = (Color) value;
Color color = (Color) value;
return new SKColor(color.R, color.G, color.B, color.A);
}
}

View File

@ -16,7 +16,7 @@ namespace Artemis.UI.Shared
/// <inheritdoc />
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var color = (Color) value;
Color color = (Color) value;
return Color.FromRgb(color.R, color.G, color.B);
}

View File

@ -26,7 +26,7 @@ namespace Artemis.UI.Shared
if (string.IsNullOrWhiteSpace((string) value))
return default(Color);
var color = ColorConverter.ConvertFromString((string) value);
object color = ColorConverter.ConvertFromString((string) value);
if (color is Color c)
return c;

View File

@ -25,7 +25,7 @@ namespace Artemis.UI.Shared
if (string.IsNullOrWhiteSpace((string) value))
return SKColor.Empty;
return SKColor.TryParse((string) value, out var color) ? color : SKColor.Empty;
return SKColor.TryParse((string) value, out SKColor color) ? color : SKColor.Empty;
}
}
}

View File

@ -36,7 +36,7 @@ namespace Artemis.UI.Shared
return;
_closed = true;
foreach (var sourceUpdatingBinding in BindingOperations.GetSourceUpdatingBindings(View))
foreach (BindingExpressionBase sourceUpdatingBinding in BindingOperations.GetSourceUpdatingBindings(View))
sourceUpdatingBinding.UpdateSource();
OnSubmit();

Some files were not shown because too many files have changed in this diff Show More