1
0
mirror of https://github.com/DarthAffe/RGB.NET.git synced 2025-12-13 10:08:31 +00:00

Merge pull request #170 from DarthAffe/Core/DeviceHandling

Core/device handling
This commit is contained in:
DarthAffe 2021-02-06 19:58:41 +01:00 committed by GitHub
commit cc01fa74d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
221 changed files with 1902 additions and 3143 deletions

View File

@ -13,11 +13,17 @@
<xsd:element name="Shape" type="xsd:string" />
<xsd:element name="Width" type="xsd:double" />
<xsd:element name="Height" type="xsd:double" />
<xsd:element name="ImageBasePath" type="xsd:string" />
<xsd:element name="DeviceImage" type="xsd:string" />
<xsd:element name="LedUnitWidth" type="xsd:double" />
<xsd:element name="LedUnitHeight" type="xsd:double" />
<xsd:element name="Leds">
<xsd:element name="CustomData">
<xsd:complexType>
<xsd:sequence>
<xsd:any />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="Leds">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="Led">
@ -28,6 +34,13 @@
<xsd:element name="Y" type="xsd:string" />
<xsd:element name="Width" type="xsd:string" />
<xsd:element name="Height" type="xsd:string" />
<xsd:element name="CustomData">
<xsd:complexType>
<xsd:sequence>
<xsd:any />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="Id" type="xsd:string" use="required" />
</xsd:complexType>
@ -35,32 +48,7 @@
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="LedImageLayouts">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="LedImageLayout">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="LedImages">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="LedImage">
<xsd:complexType>
<xsd:attribute name="Id" type="xsd:string" use="required" />
<xsd:attribute name="Image" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="Layout" type="xsd:string" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xs:schema>

View File

@ -29,7 +29,7 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _origin, value);
}
private Point _center = new Point(0.5, 0.5);
private Point _center = new(0.5, 0.5);
/// <summary>
/// Gets or sets the center <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="ConicalGradientBrush"/>. (default: 0.5, 0.5)
/// </summary>
@ -39,12 +39,12 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _center, value);
}
private IGradient _gradient;
private IGradient? _gradient;
/// <inheritdoc />
/// <summary>
/// Gets or sets the gradient drawn by the brush. If null it will default to full transparent.
/// </summary>
public IGradient Gradient
public IGradient? Gradient
{
get => _gradient;
set => SetProperty(ref _gradient, value);
@ -104,6 +104,8 @@ namespace RGB.NET.Brushes
/// <inheritdoc />
protected override Color GetColorAtPoint(Rectangle rectangle, BrushRenderTarget renderTarget)
{
if (Gradient == null) return Color.Transparent;
double centerX = rectangle.Size.Width * Center.X;
double centerY = rectangle.Size.Height * Center.Y;

View File

@ -12,6 +12,6 @@ namespace RGB.NET.Brushes
/// <summary>
/// Gets the <see cref="IGradient"/> used by this <see cref="IGradientBrush"/>.
/// </summary>
IGradient Gradient { get; }
IGradient? Gradient { get; }
}
}

View File

@ -20,7 +20,7 @@ namespace RGB.NET.Brushes
{
#region Properties & Fields
private Point _startPoint = new Point(0, 0.5);
private Point _startPoint = new(0, 0.5);
/// <summary>
/// Gets or sets the start <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="LinearGradientBrush"/>. (default: 0.0, 0.5)
/// </summary>
@ -30,7 +30,7 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _startPoint, value);
}
private Point _endPoint = new Point(1, 0.5);
private Point _endPoint = new(1, 0.5);
/// <summary>
/// Gets or sets the end <see cref="Point"/> (as percentage in the range [0..1]) of the <see cref="IGradient"/> drawn by this <see cref="LinearGradientBrush"/>. (default: 1.0, 0.5)
/// </summary>
@ -40,9 +40,9 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _endPoint, value);
}
private IGradient _gradient;
private IGradient? _gradient;
/// <inheritdoc />
public IGradient Gradient
public IGradient? Gradient
{
get => _gradient;
set => SetProperty(ref _gradient, value);
@ -97,8 +97,8 @@ namespace RGB.NET.Brushes
{
if (Gradient == null) return Color.Transparent;
Point startPoint = new Point(StartPoint.X * rectangle.Size.Width, StartPoint.Y * rectangle.Size.Height);
Point endPoint = new Point(EndPoint.X * rectangle.Size.Width, EndPoint.Y * rectangle.Size.Height);
Point startPoint = new(StartPoint.X * rectangle.Size.Width, StartPoint.Y * rectangle.Size.Height);
Point endPoint = new(EndPoint.X * rectangle.Size.Width, EndPoint.Y * rectangle.Size.Height);
double offset = GradientHelper.CalculateLinearGradientOffset(startPoint, endPoint, renderTarget.Point);
return Gradient.GetColor(offset);

View File

@ -18,7 +18,7 @@ namespace RGB.NET.Brushes
{
#region Properties & Fields
private Point _center = new Point(0.5, 0.5);
private Point _center = new(0.5, 0.5);
/// <summary>
/// Gets or sets the center <see cref="Point"/> (as percentage in the range [0..1]) around which the <see cref="RadialGradientBrush"/> should be drawn. (default: 0.5, 0.5)
/// </summary>
@ -28,9 +28,9 @@ namespace RGB.NET.Brushes
set => SetProperty(ref _center, value);
}
private IGradient _gradient;
private IGradient? _gradient;
/// <inheritdoc />
public IGradient Gradient
public IGradient? Gradient
{
get => _gradient;
set => SetProperty(ref _gradient, value);
@ -78,7 +78,7 @@ namespace RGB.NET.Brushes
{
if (Gradient == null) return Color.Transparent;
Point centerPoint = new Point(rectangle.Location.X + (rectangle.Size.Width * Center.X), rectangle.Location.Y + (rectangle.Size.Height * Center.Y));
Point centerPoint = new(rectangle.Location.X + (rectangle.Size.Width * Center.X), rectangle.Location.Y + (rectangle.Size.Height * Center.Y));
// Calculate the distance to the farthest point from the center as reference (this has to be a corner)
// ReSharper disable once RedundantCast - never trust this ...

View File

@ -52,7 +52,7 @@ namespace RGB.NET.Brushes
/// Converts a <see cref="Color" /> to a <see cref="SolidColorBrush" />.
/// </summary>
/// <param name="color">The <see cref="Color"/> to convert.</param>
public static explicit operator SolidColorBrush(Color color) => new SolidColorBrush(color);
public static explicit operator SolidColorBrush(Color color) => new(color);
/// <summary>
/// Converts a <see cref="SolidColorBrush" /> to a <see cref="Color" />.

View File

@ -23,7 +23,7 @@ namespace RGB.NET.Brushes.Gradients
/// <summary>
/// Gets a list of the stops used by this <see cref="AbstractGradient"/>.
/// </summary>
public ObservableCollection<GradientStop> GradientStops { get; } = new ObservableCollection<GradientStop>();
public ObservableCollection<GradientStop> GradientStops { get; } = new();
private bool _wrapGradient;
/// <summary>
@ -42,7 +42,7 @@ namespace RGB.NET.Brushes.Gradients
#region Events
/// <inheritdoc />
public event EventHandler GradientChanged;
public event EventHandler? GradientChanged;
#endregion
@ -54,7 +54,7 @@ namespace RGB.NET.Brushes.Gradients
protected AbstractGradient()
{
GradientStops.CollectionChanged += GradientCollectionChanged;
PropertyChanged += (sender, args) => OnGradientChanged();
PropertyChanged += (_, _) => OnGradientChanged();
}
/// <summary>
@ -64,7 +64,7 @@ namespace RGB.NET.Brushes.Gradients
protected AbstractGradient(params GradientStop[] gradientStops)
{
GradientStops.CollectionChanged += GradientCollectionChanged;
PropertyChanged += (sender, args) => OnGradientChanged();
PropertyChanged += (_, _) => OnGradientChanged();
foreach (GradientStop gradientStop in gradientStops)
GradientStops.Add(gradientStop);
@ -80,7 +80,7 @@ namespace RGB.NET.Brushes.Gradients
this.WrapGradient = wrapGradient;
GradientStops.CollectionChanged += GradientCollectionChanged;
PropertyChanged += (sender, args) => OnGradientChanged();
PropertyChanged += (_, _) => OnGradientChanged();
foreach (GradientStop gradientStop in gradientStops)
GradientStops.Add(gradientStop);
@ -128,9 +128,9 @@ namespace RGB.NET.Brushes.Gradients
/// <summary>
/// Should be called to indicate that the gradient was changed.
/// </summary>
protected void OnGradientChanged() => GradientChanged?.Invoke(this, null);
protected void OnGradientChanged() => GradientChanged?.Invoke(this, EventArgs.Empty);
private void GradientCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
private void GradientCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (GradientStop gradientStop in e.OldItems)
@ -143,7 +143,7 @@ namespace RGB.NET.Brushes.Gradients
OnGradientChanged();
}
private void GradientStopChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) => OnGradientChanged();
private void GradientStopChanged(object? sender, PropertyChangedEventArgs propertyChangedEventArgs) => OnGradientChanged();
#endregion
}

View File

@ -16,7 +16,7 @@ namespace RGB.NET.Brushes.Gradients
#region Properties & Fields
private bool _isOrderedGradientListDirty = true;
private LinkedList<GradientStop> _orderedGradientStops;
private LinkedList<GradientStop> _orderedGradientStops = new();
#endregion
@ -60,12 +60,12 @@ namespace RGB.NET.Brushes.Gradients
private void Initialize()
{
void OnGradientStopOnPropertyChanged(object sender, PropertyChangedEventArgs args) => _isOrderedGradientListDirty = true;
void OnGradientStopOnPropertyChanged(object? sender, PropertyChangedEventArgs args) => _isOrderedGradientListDirty = true;
foreach (GradientStop gradientStop in GradientStops)
gradientStop.PropertyChanged += OnGradientStopOnPropertyChanged;
GradientStops.CollectionChanged += (sender, args) =>
GradientStops.CollectionChanged += (_, args) =>
{
if (args.OldItems != null)
foreach (GradientStop gradientStop in args.OldItems)
@ -114,18 +114,18 @@ namespace RGB.NET.Brushes.Gradients
/// <returns></returns>
protected virtual (GradientStop gsBefore, GradientStop gsAfter) GetEnclosingGradientStops(double offset, LinkedList<GradientStop> orderedStops, bool wrap)
{
LinkedList<GradientStop> gradientStops = new LinkedList<GradientStop>(orderedStops);
LinkedList<GradientStop> gradientStops = new(orderedStops);
if (wrap)
{
GradientStop gsBefore, gsAfter;
GradientStop? gsBefore, gsAfter;
do
{
gsBefore = gradientStops.LastOrDefault(n => n.Offset <= offset);
if (gsBefore == null)
{
GradientStop lastStop = gradientStops.Last.Value;
GradientStop lastStop = gradientStops.Last!.Value;
gradientStops.AddFirst(new GradientStop(lastStop.Offset - 1, lastStop.Color));
gradientStops.RemoveLast();
}
@ -133,7 +133,7 @@ namespace RGB.NET.Brushes.Gradients
gsAfter = gradientStops.FirstOrDefault(n => n.Offset >= offset);
if (gsAfter == null)
{
GradientStop firstStop = gradientStops.First.Value;
GradientStop firstStop = gradientStops.First!.Value;
gradientStops.AddLast(new GradientStop(firstStop.Offset + 1, firstStop.Color));
gradientStops.RemoveFirst();
}

View File

@ -41,7 +41,7 @@ namespace RGB.NET.Brushes.Gradients
#region Events
/// <inheritdoc />
public event EventHandler GradientChanged;
public event EventHandler? GradientChanged;
#endregion
@ -57,7 +57,7 @@ namespace RGB.NET.Brushes.Gradients
this.StartHue = startHue;
this.EndHue = endHue;
PropertyChanged += (sender, args) => OnGradientChanged();
PropertyChanged += (_, _) => OnGradientChanged();
}
#endregion
@ -85,7 +85,7 @@ namespace RGB.NET.Brushes.Gradients
StartHue += offset;
EndHue += offset;
while ((StartHue > 360) && (EndHue > 360))
{
StartHue -= 360;
@ -101,7 +101,7 @@ namespace RGB.NET.Brushes.Gradients
/// <summary>
/// Should be called to indicate that the gradient was changed.
/// </summary>
protected void OnGradientChanged() => GradientChanged?.Invoke(this, null);
protected void OnGradientChanged() => GradientChanged?.Invoke(this, EventArgs.Empty);
#endregion
}

View File

@ -35,7 +35,7 @@ namespace RGB.NET.Core
public Rectangle RenderedRectangle { get; protected set; }
/// <inheritdoc />
public Dictionary<BrushRenderTarget, Color> RenderedTargets { get; } = new Dictionary<BrushRenderTarget, Color>();
public Dictionary<BrushRenderTarget, Color> RenderedTargets { get; } = new();
#endregion

View File

@ -2,23 +2,6 @@
{
public class DefaultColorBehavior : IColorBehavior
{
#region Properties & Fields
private static DefaultColorBehavior _instance = new DefaultColorBehavior();
/// <summary>
/// Gets the singleton instance of <see cref="DefaultColorBehavior"/>.
/// </summary>
public static DefaultColorBehavior Instance { get; } = _instance;
#endregion
#region Constructors
private DefaultColorBehavior()
{ }
#endregion
#region Methods
/// <summary>
@ -32,7 +15,7 @@
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Color" /> equivalent to this <see cref="Color" />; otherwise, <c>false</c>.</returns>
public virtual bool Equals(Color color, object obj)
public virtual bool Equals(Color color, object? obj)
{
if (!(obj is Color)) return false;

View File

@ -4,7 +4,7 @@
{
string ToString(Color color);
bool Equals(Color color, object obj);
bool Equals(Color color, object? obj);
int GetHashCode(Color color);

View File

@ -7,33 +7,27 @@ using System.Diagnostics;
namespace RGB.NET.Core
{
/// <inheritdoc />
/// <summary>
/// Represents an ARGB (alpha, red, green, blue) color.
/// </summary>
[DebuggerDisplay("[A: {A}, R: {R}, G: {G}, B: {B}]")]
public struct Color
public readonly struct Color
{
#region Constants
/// <summary>
/// Gets an transparent color [A: 0, R: 0, G: 0, B: 0]
/// </summary>
public static Color Transparent => new Color(0, 0, 0, 0);
public static Color Transparent => new(0, 0, 0, 0);
#endregion
#region Properties & Fields
private static IColorBehavior _behavior = DefaultColorBehavior.Instance;
/// <summary>
/// Gets or sets the <see cref="IColorBehavior"/> used to perform operations on colors.
/// </summary>
public static IColorBehavior Behavior
{
get => _behavior;
set => _behavior = value ?? DefaultColorBehavior.Instance;
}
public static IColorBehavior Behavior { get; set; } = new DefaultColorBehavior();
/// <summary>
/// Gets the alpha component value of this <see cref="Color"/> as percentage in the range [0..1].
@ -199,12 +193,13 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Color" /> equivalent to this <see cref="Color" />; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj) => Behavior.Equals(this, obj);
public override bool Equals(object? obj) => Behavior.Equals(this, obj);
/// <summary>
/// Returns a hash code for this <see cref="Color" />, as defined by the current <see cref="Behavior"/>.
/// </summary>
/// <returns>An integer value that specifies the hash code for this <see cref="Color" />.</returns>
// ReSharper disable once NonReadonlyMemberInGetHashCode
public override int GetHashCode() => Behavior.GetHashCode(this);
/// <summary>
@ -246,42 +241,42 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="components">The <see cref="ValueTuple"/> containing the components.</param>
/// <returns>The color.</returns>
public static implicit operator Color((byte r, byte g, byte b) components) => new Color(components.r, components.g, components.b);
public static implicit operator Color((byte r, byte g, byte b) components) => new(components.r, components.g, components.b);
/// <summary>
/// Converts a <see cref="ValueTuple"/> of ARGB-components to a <see cref="Color"/>.
/// </summary>
/// <param name="components">The <see cref="ValueTuple"/> containing the components.</param>
/// <returns>The color.</returns>
public static implicit operator Color((byte a, byte r, byte g, byte b) components) => new Color(components.a, components.r, components.g, components.b);
public static implicit operator Color((byte a, byte r, byte g, byte b) components) => new(components.a, components.r, components.g, components.b);
/// <summary>
/// Converts a <see cref="ValueTuple"/> of ARGB-components to a <see cref="Color"/>.
/// </summary>
/// <param name="components">The <see cref="ValueTuple"/> containing the components.</param>
/// <returns>The color.</returns>
public static implicit operator Color((int r, int g, int b) components) => new Color(components.r, components.g, components.b);
public static implicit operator Color((int r, int g, int b) components) => new(components.r, components.g, components.b);
/// <summary>
/// Converts a <see cref="ValueTuple"/> of ARGB-components to a <see cref="Color"/>.
/// </summary>
/// <param name="components">The <see cref="ValueTuple"/> containing the components.</param>
/// <returns>The color.</returns>
public static implicit operator Color((int a, int r, int g, int b) components) => new Color(components.a, components.r, components.g, components.b);
public static implicit operator Color((int a, int r, int g, int b) components) => new(components.a, components.r, components.g, components.b);
/// <summary>
/// Converts a <see cref="ValueTuple"/> of ARGB-components to a <see cref="Color"/>.
/// </summary>
/// <param name="components">The <see cref="ValueTuple"/> containing the components.</param>
/// <returns>The color.</returns>
public static implicit operator Color((double r, double g, double b) components) => new Color(components.r, components.g, components.b);
public static implicit operator Color((double r, double g, double b) components) => new(components.r, components.g, components.b);
/// <summary>
/// Converts a <see cref="ValueTuple"/> of ARGB-components to a <see cref="Color"/>.
/// </summary>
/// <param name="components">The <see cref="ValueTuple"/> containing the components.</param>
/// <returns>The color.</returns>
public static implicit operator Color((double a, double r, double g, double b) components) => new Color(components.a, components.r, components.g, components.b);
public static implicit operator Color((double a, double r, double g, double b) components) => new(components.a, components.r, components.g, components.b);
#endregion
}

View File

@ -82,7 +82,7 @@ namespace RGB.NET.Core
(double cHue, double cSaturation, double cValue) = color.GetHSV();
return Create(color.A, cHue * hue, cSaturation * saturation, cValue * value);
}
/// <summary>
/// Divides the given HSV values to this color.
/// </summary>
@ -180,7 +180,7 @@ namespace RGB.NET.Core
else // b is max
hue = 4.0 + ((r - g) / (max - min));
hue = hue * 60.0;
hue *= 60.0;
hue = hue.Wrap(0, 360);
double saturation = max.EqualsInTolerance(0) ? 0 : 1.0 - (min / max);
@ -205,21 +205,15 @@ namespace RGB.NET.Core
double q = v * (1.0 - (s * ff));
double t = v * (1.0 - (s * (1.0 - ff)));
switch (i)
return i switch
{
case 0:
return (v, t, p);
case 1:
return (q, v, p);
case 2:
return (p, v, t);
case 3:
return (p, q, v);
case 4:
return (t, p, v);
default:
return (v, p, q);
}
0 => (v, t, p),
1 => (q, v, p),
2 => (p, v, t),
3 => (p, q, v),
4 => (t, p, v),
_ => (v, p, q)
};
}
#endregion

View File

@ -66,7 +66,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to add.</param>
/// <returns>The new color after the modification.</returns>
public static Color AddRGB(this Color color, int r = 0, int g = 0, int b = 0)
=> new Color(color.A, color.GetR() + r, color.GetG() + g, color.GetB() + b);
=> new(color.A, color.GetR() + r, color.GetG() + g, color.GetB() + b);
/// <summary>
/// Adds the given RGB-percent values to this color.
@ -76,7 +76,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to add.</param>
/// <returns>The new color after the modification.</returns>
public static Color AddRGB(this Color color, double r = 0, double g = 0, double b = 0)
=> new Color(color.A, color.R + r, color.G + g, color.B + b);
=> new(color.A, color.R + r, color.G + g, color.B + b);
/// <summary>
/// Adds the given alpha value to this color.
@ -84,7 +84,7 @@ namespace RGB.NET.Core
/// <param name="a">The alpha value to add.</param>
/// <returns>The new color after the modification.</returns>
public static Color AddA(this Color color, int a)
=> new Color(color.GetA() + a, color.R, color.G, color.B);
=> new(color.GetA() + a, color.R, color.G, color.B);
/// <summary>
/// Adds the given alpha-percent value to this color.
@ -92,7 +92,7 @@ namespace RGB.NET.Core
/// <param name="a">The alpha value to add.</param>
/// <returns>The new color after the modification.</returns>
public static Color AddA(this Color color, double a)
=> new Color(color.A + a, color.R, color.G, color.B);
=> new(color.A + a, color.R, color.G, color.B);
#endregion
@ -106,7 +106,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to subtract.</param>
/// <returns>The new color after the modification.</returns>
public static Color SubtractRGB(this Color color, int r = 0, int g = 0, int b = 0)
=> new Color(color.A, color.GetR() - r, color.GetG() - g, color.GetB() - b);
=> new(color.A, color.GetR() - r, color.GetG() - g, color.GetB() - b);
/// <summary>
/// Subtracts the given RGB values to this color.
@ -116,7 +116,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to subtract.</param>
/// <returns>The new color after the modification.</returns>
public static Color SubtractRGB(this Color color, double r = 0, double g = 0, double b = 0)
=> new Color(color.A, color.R - r, color.G - g, color.B - b);
=> new(color.A, color.R - r, color.G - g, color.B - b);
/// <summary>
/// Subtracts the given alpha value to this color.
@ -124,7 +124,7 @@ namespace RGB.NET.Core
/// <param name="a">The alpha value to subtract.</param>
/// <returns>The new color after the modification.</returns>
public static Color SubtractA(this Color color, int a)
=> new Color(color.GetA() - a, color.R, color.G, color.B);
=> new(color.GetA() - a, color.R, color.G, color.B);
/// <summary>
/// Subtracts the given alpha-percent value to this color.
@ -132,7 +132,7 @@ namespace RGB.NET.Core
/// <param name="a">The alpha value to subtract.</param>
/// <returns>The new color after the modification.</returns>
public static Color SubtractA(this Color color, double aPercent)
=> new Color(color.A - aPercent, color.R, color.G, color.B);
=> new(color.A - aPercent, color.R, color.G, color.B);
#endregion
@ -146,7 +146,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to multiply.</param>
/// <returns>The new color after the modification.</returns>
public static Color MultiplyRGB(this Color color, double r = 1, double g = 1, double b = 1)
=> new Color(color.A, color.R * r, color.G * g, color.B * b);
=> new(color.A, color.R * r, color.G * g, color.B * b);
/// <summary>
/// Multiplies the given alpha value to this color.
@ -154,7 +154,7 @@ namespace RGB.NET.Core
/// <param name="a">The alpha value to multiply.</param>
/// <returns>The new color after the modification.</returns>
public static Color MultiplyA(this Color color, double a)
=> new Color(color.A * a, color.R, color.G, color.B);
=> new(color.A * a, color.R, color.G, color.B);
#endregion
@ -168,7 +168,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to divide.</param>
/// <returns>The new color after the modification.</returns>
public static Color DivideRGB(this Color color, double r = 1, double g = 1, double b = 1)
=> new Color(color.A, color.R / r, color.G / g, color.B / b);
=> new(color.A, color.R / r, color.G / g, color.B / b);
/// <summary>
/// Divides the given alpha value to this color.
@ -176,7 +176,7 @@ namespace RGB.NET.Core
/// <param name="a">The alpha value to divide.</param>
/// <returns>The new color after the modification.</returns>
public static Color DivideA(this Color color, double a)
=> new Color(color.A / a, color.R, color.G, color.B);
=> new(color.A / a, color.R, color.G, color.B);
#endregion
@ -190,7 +190,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to set.</param>
/// <returns>The new color after the modification.</returns>
public static Color SetRGB(this Color color, byte? r = null, byte? g = null, byte? b = null)
=> new Color(color.A, r ?? color.GetR(), g ?? color.GetG(), b ?? color.GetB());
=> new(color.A, r ?? color.GetR(), g ?? color.GetG(), b ?? color.GetB());
/// <summary>
/// Sets the given RGB value of this color.
@ -200,7 +200,7 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to set.</param>
/// <returns>The new color after the modification.</returns>
public static Color SetRGB(this Color color, int? r = null, int? g = null, int? b = null)
=> new Color(color.A, r ?? color.GetR(), g ?? color.GetG(), b ?? color.GetB());
=> new(color.A, r ?? color.GetR(), g ?? color.GetG(), b ?? color.GetB());
/// <summary>
/// Sets the given RGB value of this color.
@ -210,21 +210,21 @@ namespace RGB.NET.Core
/// <param name="b">The blue value to set.</param>
/// <returns>The new color after the modification.</returns>
public static Color SetRGB(this Color color, double? r = null, double? g = null, double? b = null)
=> new Color(color.A, r ?? color.R, g ?? color.G, b ?? color.B);
=> new(color.A, r ?? color.R, g ?? color.G, b ?? color.B);
/// <summary>
/// Sets the given alpha value of this color.
/// </summary>
/// <param name="a">The alpha value to set.</param>
/// <returns>The new color after the modification.</returns>
public static Color SetA(this Color color, int a) => new Color(a, color.R, color.G, color.B);
public static Color SetA(this Color color, int a) => new(a, color.R, color.G, color.B);
/// <summary>
/// Sets the given alpha value of this color.
/// </summary>
/// <param name="a">The alpha value to set.</param>
/// <returns>The new color after the modification.</returns>
public static Color SetA(this Color color, double a) => new Color(a, color.R, color.G, color.B);
public static Color SetA(this Color color, double a) => new(a, color.R, color.G, color.B);
#endregion
@ -258,16 +258,17 @@ namespace RGB.NET.Core
if ((hexString == null) || (hexString.Length < 6))
throw new ArgumentException("Invalid hex string", nameof(hexString));
if (hexString[0] == '#')
hexString = hexString.Substring(1);
ReadOnlySpan<char> span = hexString.AsSpan();
if (span[0] == '#')
span = span[1..];
byte[] data = ConversionHelper.HexToBytes(hexString);
if (data.Length == 3)
return new Color(data[0], data[1], data[2]);
if (data.Length == 4)
return new Color(data[0], data[1], data[2], data[3]);
throw new ArgumentException("Invalid hex string", nameof(hexString));
byte[] data = ConversionHelper.HexToBytes(span);
return data.Length switch
{
3 => new Color(data[0], data[1], data[2]),
4 => new Color(data[0], data[1], data[2], data[3]),
_ => throw new ArgumentException($"Invalid hex string '{hexString}'", nameof(hexString))
};
}
#endregion

View File

@ -11,7 +11,7 @@ namespace RGB.NET.Core
{
#region Properties & Fields
private readonly List<T> _decorators = new List<T>();
private readonly List<T> _decorators = new();
/// <inheritdoc />
public IReadOnlyCollection<T> Decorators

View File

@ -29,7 +29,7 @@ namespace RGB.NET.Core
/// <summary>
/// Gets a readonly-list of all <see cref="IDecoratable"/> this decorator is attached to.
/// </summary>
protected List<IDecoratable> DecoratedObjects { get; } = new List<IDecoratable>();
protected List<IDecoratable> DecoratedObjects { get; } = new();
#endregion
@ -46,7 +46,7 @@ namespace RGB.NET.Core
/// </summary>
protected virtual void Detach()
{
List<IDecoratable> decoratables = new List<IDecoratable>(DecoratedObjects);
List<IDecoratable> decoratables = new(DecoratedObjects);
foreach (IDecoratable decoratable in decoratables)
{
IEnumerable<Type> types = decoratable.GetType().GetInterfaces().Where(t => t.IsGenericType

View File

@ -8,6 +8,8 @@
{
#region Properties & Fields
protected RGBSurface Surface { get; }
/// <summary>
/// Gets or sets if the <see cref="AbstractUpdateAwareDecorator"/> should call <see cref="Update"/> even if the Decorator is disabled.
/// </summary>
@ -21,8 +23,9 @@
/// Initializes a new instance of the <see cref="AbstractUpdateAwareDecorator"/> class.
/// </summary>
/// <param name="updateIfDisabled">Bool indicating if the <see cref="AbstractUpdateAwareDecorator"/> should call <see cref="Update"/> even if the Decorator is disabled.</param>
protected AbstractUpdateAwareDecorator(bool updateIfDisabled = false)
protected AbstractUpdateAwareDecorator(RGBSurface surface, bool updateIfDisabled = false)
{
this.Surface = surface;
this.UpdateIfDisabled = updateIfDisabled;
}
@ -34,7 +37,7 @@
public override void OnAttached(IDecoratable decoratable)
{
if (DecoratedObjects.Count == 0)
RGBSurface.Instance.Updating += OnSurfaceUpdating;
Surface.Updating += OnSurfaceUpdating;
base.OnAttached(decoratable);
}
@ -45,7 +48,7 @@
base.OnDetached(decoratable);
if (DecoratedObjects.Count == 0)
RGBSurface.Instance.Updating -= OnSurfaceUpdating;
Surface.Updating -= OnSurfaceUpdating;
}
private void OnSurfaceUpdating(UpdatingEventArgs args)

View File

@ -2,12 +2,9 @@
// ReSharper disable UnusedMember.Global
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RGB.NET.Core.Layout;
namespace RGB.NET.Core
{
@ -21,13 +18,15 @@ namespace RGB.NET.Core
{
#region Properties & Fields
RGBSurface? IRGBDevice.Surface { get; set; }
/// <inheritdoc />
public abstract TDeviceInfo DeviceInfo { get; }
/// <inheritdoc />
IRGBDeviceInfo IRGBDevice.DeviceInfo => DeviceInfo;
private Point _location = new Point(0, 0);
private Point _location = new(0, 0);
/// <inheritdoc />
public Point Location
{
@ -44,7 +43,7 @@ namespace RGB.NET.Core
public Size Size
{
get => _size;
protected set
set
{
if (SetProperty(ref _size, value))
UpdateActualData();
@ -67,7 +66,7 @@ namespace RGB.NET.Core
private set => SetProperty(ref _deviceRectangle, value);
}
private Scale _scale = new Scale(1);
private Scale _scale = new(1);
/// <inheritdoc />
public Scale Scale
{
@ -79,7 +78,7 @@ namespace RGB.NET.Core
}
}
private Rotation _rotation = new Rotation(0);
private Rotation _rotation = new(0);
/// <inheritdoc />
public Rotation Rotation
{
@ -96,26 +95,18 @@ namespace RGB.NET.Core
/// </summary>
protected bool RequiresFlush { get; set; } = false;
/// <inheritdoc />
public DeviceUpdateMode UpdateMode { get; set; } = DeviceUpdateMode.Sync;
/// <summary>
/// Gets a dictionary containing all <see cref="Led"/> of the <see cref="IRGBDevice"/>.
/// </summary>
protected Dictionary<LedId, Led> LedMapping { get; } = new Dictionary<LedId, Led>();
/// <summary>
/// Gets a dictionary containing all <see cref="IRGBDeviceSpecialPart"/> associated with this <see cref="IRGBDevice"/>.
/// </summary>
protected Dictionary<Type, IRGBDeviceSpecialPart> SpecialDeviceParts { get; } = new Dictionary<Type, IRGBDeviceSpecialPart>();
protected Dictionary<LedId, Led> LedMapping { get; } = new();
#region Indexer
/// <inheritdoc />
Led IRGBDevice.this[LedId ledId] => LedMapping.TryGetValue(ledId, out Led led) ? led : null;
Led? IRGBDevice.this[LedId ledId] => LedMapping.TryGetValue(ledId, out Led? led) ? led : null;
/// <inheritdoc />
Led IRGBDevice.this[Point location] => LedMapping.Values.FirstOrDefault(x => x.LedRectangle.Contains(location));
Led? IRGBDevice.this[Point location] => LedMapping.Values.FirstOrDefault(x => x.LedRectangle.Contains(location));
/// <inheritdoc />
IEnumerable<Led> IRGBDevice.this[Rectangle referenceRect, double minOverlayPercentage]
@ -140,22 +131,20 @@ namespace RGB.NET.Core
DeviceUpdate();
// Send LEDs to SDK
List<Led> ledsToUpdate = GetLedsToUpdate(flushLeds)?.ToList() ?? new List<Led>();
List<Led> ledsToUpdate = GetLedsToUpdate(flushLeds).ToList();
foreach (Led ledToUpdate in ledsToUpdate)
ledToUpdate.Update();
if (UpdateMode.HasFlag(DeviceUpdateMode.Sync))
UpdateLeds(ledsToUpdate);
UpdateLeds(ledsToUpdate);
}
protected virtual IEnumerable<Led> GetLedsToUpdate(bool flushLeds) => ((RequiresFlush || flushLeds) ? LedMapping.Values : LedMapping.Values.Where(x => x.IsDirty));
/// <inheritdoc />
public virtual void Dispose()
{
try
{
SpecialDeviceParts.Clear();
LedMapping.Clear();
}
catch { /* this really shouldn't happen */ }
@ -172,15 +161,6 @@ namespace RGB.NET.Core
/// </summary>
protected abstract void UpdateLeds(IEnumerable<Led> ledsToUpdate);
/// <summary>
/// Initializes the <see cref="Led"/> with the specified id.
/// </summary>
/// <param name="ledId">The <see cref="LedId"/> to initialize.</param>
/// <param name="ledRectangle">The <see cref="Rectangle"/> representing the position of the <see cref="Led"/> to initialize.</param>
/// <returns></returns>
[Obsolete("Use InitializeLed(LedId ledId, Point location, Size size) instead.")]
protected virtual Led InitializeLed(LedId ledId, Rectangle rectangle) => InitializeLed(ledId, rectangle.Location, rectangle.Size);
/// <summary>
/// Initializes the <see cref="Led"/> with the specified id.
/// </summary>
@ -188,75 +168,25 @@ namespace RGB.NET.Core
/// <param name="location">The location of the <see cref="Led"/> to initialize.</param>
/// <param name="size">The size of the <see cref="Led"/> to initialize.</param>
/// <returns>The initialized led.</returns>
protected virtual Led InitializeLed(LedId ledId, Point location, Size size)
public virtual Led? AddLed(LedId ledId, Point location, Size size, object? customData = null)
{
if ((ledId == LedId.Invalid) || LedMapping.ContainsKey(ledId)) return null;
Led led = new Led(this, ledId, location, size, CreateLedCustomData(ledId));
Led led = new(this, ledId, location, size, customData ?? GetLedCustomData(ledId));
LedMapping.Add(ledId, led);
return led;
}
/// <summary>
/// Applies the given layout.
/// </summary>
/// <param name="layoutPath">The file containing the layout.</param>
/// <param name="imageLayout">The name of the layout used to get the images of the leds.</param>
/// <param name="createMissingLeds">If set to true a new led is initialized for every id in the layout if it doesn't already exist.</param>
protected virtual DeviceLayout ApplyLayoutFromFile(string layoutPath, string imageLayout, bool createMissingLeds = false)
public virtual Led? RemoveLed(LedId ledId)
{
DeviceLayout layout = DeviceLayout.Load(layoutPath);
if (layout != null)
{
string imageBasePath = string.IsNullOrWhiteSpace(layout.ImageBasePath) ? null : PathHelper.GetAbsolutePath(this, layout.ImageBasePath);
if ((imageBasePath != null) && !string.IsNullOrWhiteSpace(layout.DeviceImage) && (DeviceInfo != null))
DeviceInfo.Image = new Uri(Path.Combine(imageBasePath, layout.DeviceImage), UriKind.Absolute);
if (ledId == LedId.Invalid) return null;
if (!LedMapping.TryGetValue(ledId, out Led? led)) return null;
LedImageLayout ledImageLayout = layout.LedImageLayouts.FirstOrDefault(x => string.Equals(x.Layout, imageLayout, StringComparison.OrdinalIgnoreCase));
Size = new Size(layout.Width, layout.Height);
if (layout.Leds != null)
foreach (LedLayout layoutLed in layout.Leds)
{
if (Enum.TryParse(layoutLed.Id, true, out LedId ledId))
{
if (!LedMapping.TryGetValue(ledId, out Led led) && createMissingLeds)
led = InitializeLed(ledId, new Point(), new Size());
if (led != null)
{
led.Location = new Point(layoutLed.X, layoutLed.Y);
led.Size = new Size(layoutLed.Width, layoutLed.Height);
led.Shape = layoutLed.Shape;
led.ShapeData = layoutLed.ShapeData;
LedImage image = ledImageLayout?.LedImages.FirstOrDefault(x => x.Id == layoutLed.Id);
if ((imageBasePath != null) && !string.IsNullOrEmpty(image?.Image))
led.Image = new Uri(Path.Combine(imageBasePath, image.Image), UriKind.Absolute);
}
}
}
}
return layout;
LedMapping.Remove(ledId);
return led;
}
/// <summary>
/// Creates provider-specific data associated with this <see cref="LedId"/>.
/// </summary>
/// <param name="ledId">The <see cref="LedId"/>.</param>
protected virtual object CreateLedCustomData(LedId ledId) => null;
/// <inheritdoc />
public void AddSpecialDevicePart<T>(T specialDevicePart)
where T : class, IRGBDeviceSpecialPart
=> SpecialDeviceParts[typeof(T)] = specialDevicePart;
/// <inheritdoc />
public T GetSpecialDevicePart<T>()
where T : class, IRGBDeviceSpecialPart
=> SpecialDeviceParts.TryGetValue(typeof(T), out IRGBDeviceSpecialPart devicePart) ? (T)devicePart : default;
protected virtual object? GetLedCustomData(LedId ledId) => null;
#region Enumerator

View File

@ -1,26 +0,0 @@
using System;
namespace RGB.NET.Core
{
/// <summary>
/// Contains a list of different device device update modes.
/// </summary>
[Flags]
public enum DeviceUpdateMode
{
/// <summary>
/// Represents nothing.
/// </summary>
None = 0,
/// <summary>
/// Represents a mode which updates the leds of the device.
/// </summary>
Sync = 1 << 0,
/// <summary>
/// Represents all update modes.
/// </summary>
NoUpdate = 1 << 0xFF
}
}

View File

@ -13,6 +13,8 @@ namespace RGB.NET.Core
{
#region Properties
RGBSurface? Surface { get; internal set; }
/// <summary>
/// Gets generic information about the <see cref="IRGBDevice"/>.
/// </summary>
@ -26,7 +28,7 @@ namespace RGB.NET.Core
/// <summary>
/// Gets the <see cref="Size"/> of the <see cref="IRGBDevice"/>.
/// </summary>
Size Size { get; }
Size Size { get; set; }
/// <summary>
/// Gets the actual <see cref="Size"/> of the <see cref="IRGBDevice"/>.
@ -49,11 +51,6 @@ namespace RGB.NET.Core
/// </summary>
Rotation Rotation { get; set; }
/// <summary>
/// Gets or sets the <see cref="DeviceUpdateMode"/> of the <see cref="IRGBDevice"/>.
/// </summary>
DeviceUpdateMode UpdateMode { get; set; }
#endregion
#region Indexer
@ -63,14 +60,14 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="ledId">The <see cref="LedId"/> of the <see cref="Led"/> to get.</param>
/// <returns>The <see cref="Led"/> with the specified <see cref="LedId"/> or null if no <see cref="Led"/> is found.</returns>
Led this[LedId ledId] { get; }
Led? this[LedId ledId] { get; }
/// <summary>
/// Gets the <see cref="Led" /> at the given physical location.
/// </summary>
/// <param name="location">The <see cref="Point"/> to get the location from.</param>
/// <returns>The <see cref="Led"/> at the given <see cref="Point"/> or null if no location is found.</returns>
Led this[Point location] { get; }
Led? this[Point location] { get; }
/// <summary>
/// Gets a list of <see cref="Led" /> inside the given <see cref="Rectangle"/>.
@ -89,21 +86,10 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="flushLeds">Specifies whether all <see cref="Led"/> (including clean ones) should be updated.</param>
void Update(bool flushLeds = false);
/// <summary>
/// Adds the given <see cref="IRGBDeviceSpecialPart"/> to the device.
/// This will override existing <see cref="IRGBDeviceSpecialPart"/> of the same type.
/// </summary>
/// <param name="specialDevicePart">The <see cref="IRGBDeviceSpecialPart"/> to add.</param>
/// <typeparam name="T">The generic typeof of the <see cref="IRGBDeviceSpecialPart"/> to add.</typeparam>
void AddSpecialDevicePart<T>(T specialDevicePart) where T : class, IRGBDeviceSpecialPart;
/// <summary>
/// Gets the requested <see cref="IRGBDeviceSpecialPart"/> if available on this <see cref="IRGBDevice"/>.
/// </summary>
/// <typeparam name="T">The generic type of the requested <see cref="IRGBDeviceSpecialPart"/>.</typeparam>
/// <returns>The requested <see cref="IRGBDeviceSpecialPart"/> or null if not available in this <see cref="IRGBDevice"/>.</returns>
T GetSpecialDevicePart<T>() where T : class, IRGBDeviceSpecialPart;
Led? AddLed(LedId ledId, Point location, Size size, object? customData = null);
Led? RemoveLed(LedId ledId);
#endregion
}

View File

@ -1,6 +1,4 @@
using System;
namespace RGB.NET.Core
namespace RGB.NET.Core
{
/// <summary>
/// Represents a generic information for a <see cref="IRGBDevice"/>
@ -29,15 +27,7 @@ namespace RGB.NET.Core
/// </summary>
string Model { get; }
/// <summary>
/// Gets the lighting capability of the <see cref="IRGBDevice"/>
/// </summary>
RGBDeviceLighting Lighting { get; }
/// <summary>
/// Gets the URI of an image of the <see cref="IRGBDevice"/> or null if there is no image.
/// </summary>
Uri Image { get; set; }
object? LayoutMetadata { get; set; }
#endregion
}

View File

@ -20,28 +20,11 @@ namespace RGB.NET.Core
/// </summary>
IEnumerable<IRGBDevice> Devices { get; }
/// <summary>
/// Gets whether the application has exclusive access to devices or not.
/// </summary>
bool HasExclusiveAccess { get; }
#endregion
#region Methods
/// <summary>
/// Initializes the <see cref="IRGBDeviceProvider"/> if not already happened or reloads it if it is already initialized.
/// </summary>
/// <param name="loadFilter">Specifies which types of devices to load.</param>
/// <param name="exclusiveAccessIfPossible">Specifies whether the application should request exclusive access of possible or not.</param>
/// <param name="throwExceptions">Specifies whether exception during the initialization sequence should be thrown or not.</param>
/// <returns></returns>
bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool exclusiveAccessIfPossible = false, bool throwExceptions = false);
/// <summary>
/// Resets all handled <see cref="IRGBDevice"/> back top default.
/// </summary>
void ResetDevices();
bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool throwExceptions = false);
#endregion
}

View File

@ -1,20 +0,0 @@
namespace RGB.NET.Core
{
/// <summary>
/// Represents a generic device provider loaded used to dynamically load devices into an application.
/// This class should always provide an empty public constructor!
/// </summary>
public interface IRGBDeviceProviderLoader
{
/// <summary>
/// Indicates if the returned device-provider needs some specific initialization before use.
/// </summary>
bool RequiresInitialization { get; }
/// <summary>
/// Gets the device-provider.
/// </summary>
/// <returns>The device-provider.</returns>
IRGBDeviceProvider GetDeviceProvider();
}
}

View File

@ -1,11 +0,0 @@
using System.Collections.Generic;
namespace RGB.NET.Core
{
/// <inheritdoc />
/// <summary>
/// Represents a special part of a <see cref="T:RGB.NET.Core.IRGBDevice" />.
/// </summary>
public interface IRGBDeviceSpecialPart : IEnumerable<Led>
{ }
}

View File

@ -1,25 +0,0 @@
using System;
using System.Xml.Serialization;
namespace RGB.NET.Core.Layout
{
/// <summary>
/// Represents the serializable image-data of a specific <see cref="Led"/>.
/// </summary>
[Serializable]
[XmlRoot("LedImage")]
public class LedImage
{
/// <summary>
/// Gets or sets the Id of the <see cref="LedImage"/>.
/// </summary>
[XmlAttribute("Id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the image of the <see cref="LedImage"/>.
/// </summary>
[XmlAttribute("Image")]
public string Image { get; set; }
}
}

View File

@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
namespace RGB.NET.Core.Layout
{
/// <summary>
/// Represents the serializable collection of <see cref="LedImage"/> for a specific layout.
/// </summary>
[Serializable]
[XmlRoot("LedImageLayout")]
public class LedImageLayout
{
/// <summary>
/// Gets or sets the layout of the <see cref="LedImage"/>.
/// </summary>
[XmlAttribute("Layout")]
[DefaultValue(null)]
public string Layout { get; set; }
/// <summary>
/// Gets or sets a list of <see cref="LedImage"/> representing the images of all the <see cref="Led"/> of the represented layout.
/// </summary>
[XmlArray("LedImages")]
public List<LedImage> LedImages { get; set; } = new List<LedImage>();
}
}

View File

@ -1,25 +0,0 @@
using RGB.NET.Core.Layout;
namespace RGB.NET.Core
{
/// <summary>
/// Contains a list of different lightning-modes used by <see cref="DeviceLayout"/>.
/// </summary>
public enum RGBDeviceLighting
{
/// <summary>
/// The <see cref="IRGBDevice"/> doesn't support lighting,
/// </summary>
None = 0,
/// <summary>
/// The <see cref="IRGBDevice"/> supports per-key-lightning.
/// </summary>
Key = 1,
/// <summary>
/// The <see cref="IRGBDevice"/> supports per-device-lightning.
/// </summary>
Device = 2,
}
}

View File

@ -8,23 +8,21 @@ namespace RGB.NET.Core
/// <summary>
/// Gets the filename used to resolve the path.
/// This has to be checked for null since it'S possible that only <see cref="FileName"/> is used.
/// Also check <see cref="RelativePath "/> before use.
/// </summary>
public string RelativePart { get; }
public string? RelativePart { get; }
/// <summary>
/// Gets the filename used to resolve the path.
/// This has to be checked for null since it'S possible that only <see cref="RelativePart"/> is used.
/// Also check <see cref="RelativePath "/> before use.
/// </summary>
public string FileName { get; }
public string? FileName { get; }
/// <summary>
/// Gets the relative path used to resolve the path.
/// If this is set <see cref="RelativePart" /> and <see cref="FileName" /> are unused.
/// </summary>
public string RelativePath { get; }
public string? RelativePath { get; }
/// <summary>
/// Gets or sets the resolved path.

View File

@ -21,8 +21,8 @@ namespace RGB.NET.Core
/// <summary>
/// Gets the trigger causing this update.
/// </summary>
public IUpdateTrigger Trigger { get; }
public IUpdateTrigger? Trigger { get; }
/// <summary>
/// Gets the custom-data provided by the trigger for this update.
/// </summary>
@ -39,7 +39,7 @@ namespace RGB.NET.Core
/// <param name="deltaTime">The elapsed time (in seconds) since the last update.</param>
/// <param name="trigger">The trigger causing this update.</param>
/// <param name="customData">The custom-data provided by the trigger for this update.</param>
public UpdatingEventArgs(double deltaTime, IUpdateTrigger trigger, CustomUpdateData customData)
public UpdatingEventArgs(double deltaTime, IUpdateTrigger? trigger, CustomUpdateData customData)
{
this.DeltaTime = deltaTime;
this.Trigger = trigger;

View File

@ -16,7 +16,7 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="message">The message which describes the reason of throwing this exception.</param>
/// <param name="innerException">Optional inner exception, which lead to this exception.</param>
public RGBDeviceException(string message, Exception innerException = null)
public RGBDeviceException(string message, Exception? innerException = null)
: base(message, innerException)
{ }

View File

@ -0,0 +1,25 @@
using System;
namespace RGB.NET.Core
{
/// <inheritdoc />
/// <summary>
/// Represents an exception thrown by an <see cref="T:RGB.NET.Core.RGBSurface" />.
/// </summary>
public class RGBSurfaceException : ApplicationException
{
#region Constructors
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:RGB.NET.Core.RGBSurfaceException" /> class.
/// </summary>
/// <param name="message">The message which describes the reason of throwing this exception.</param>
/// <param name="innerException">Optional inner exception, which lead to this exception.</param>
public RGBSurfaceException(string message, Exception? innerException = null)
: base(message, innerException)
{ }
#endregion
}
}

View File

@ -13,7 +13,7 @@ namespace RGB.NET.Core
/// <param name="x">The x-ammount to move.</param>
/// <param name="y">The y-ammount to move.</param>
/// <returns>The new location of the point.</returns>
public static Point Translate(this Point point, double x = 0, double y = 0) => new Point(point.X + x, point.Y + y);
public static Point Translate(this Point point, double x = 0, double y = 0) => new(point.X + x, point.Y + y);
/// <summary>
/// Rotates the specified <see cref="Point"/> by the given amuont around the given origin.
@ -22,7 +22,7 @@ namespace RGB.NET.Core
/// <param name="rotation">The rotation.</param>
/// <param name="origin">The origin to rotate around. [0,0] if not set.</param>
/// <returns>The new location of the point.</returns>
public static Point Rotate(this Point point, Rotation rotation, Point origin = new Point())
public static Point Rotate(this Point point, Rotation rotation, Point origin = new())
{
double sin = Math.Sin(rotation.Radians);
double cos = Math.Cos(rotation.Radians);

View File

@ -12,7 +12,7 @@ namespace RGB.NET.Core
/// <param name="rect">The rectangle to modify.</param>
/// <param name="location">The new location of the rectangle.</param>
/// <returns>The modified <see cref="Rectangle"/>.</returns>
public static Rectangle SetLocation(this Rectangle rect, Point location) => new Rectangle(location, rect.Size);
public static Rectangle SetLocation(this Rectangle rect, Point location) => new(location, rect.Size);
/// <summary>
/// Sets the <see cref="Point.X"/> of the <see cref="Rectangle.Location"/> of the given rectangle.
@ -20,7 +20,7 @@ namespace RGB.NET.Core
/// <param name="rect">The rectangle to modify.</param>
/// <param name="x">The new x-location of the rectangle.</param>
/// <returns>The modified <see cref="Rectangle"/>.</returns>
public static Rectangle SetX(this Rectangle rect, double x) => new Rectangle(new Point(x, rect.Location.Y), rect.Size);
public static Rectangle SetX(this Rectangle rect, double x) => new(new Point(x, rect.Location.Y), rect.Size);
/// <summary>
/// Sets the <see cref="Point.Y"/> of the <see cref="Rectangle.Location"/> of the given rectangle.
@ -28,7 +28,7 @@ namespace RGB.NET.Core
/// <param name="rect">The rectangle to modify.</param>
/// <param name="y">The new y-location of the rectangle.</param>
/// <returns>The modified <see cref="Rectangle"/>.</returns>
public static Rectangle SetY(this Rectangle rect, double y) => new Rectangle(new Point(rect.Location.X, y), rect.Size);
public static Rectangle SetY(this Rectangle rect, double y) => new(new Point(rect.Location.X, y), rect.Size);
/// <summary>
/// Sets the <see cref="Rectangle.Size"/> of the given rectangle.
@ -36,7 +36,7 @@ namespace RGB.NET.Core
/// <param name="rect">The rectangle to modify.</param>
/// <param name="size">The new size of the rectangle.</param>
/// <returns>The modified <see cref="Rectangle"/>.</returns>
public static Rectangle SetSize(this Rectangle rect, Size size) => new Rectangle(rect.Location, size);
public static Rectangle SetSize(this Rectangle rect, Size size) => new(rect.Location, size);
/// <summary>
/// Sets the <see cref="Size.Width"/> of the <see cref="Rectangle.Size"/> of the given rectangle.
@ -44,7 +44,7 @@ namespace RGB.NET.Core
/// <param name="rect">The rectangle to modify.</param>
/// <param name="width">The new width of the rectangle.</param>
/// <returns>The modified <see cref="Rectangle"/>.</returns>
public static Rectangle SetWidth(this Rectangle rect, double width) => new Rectangle(rect.Location, new Size(width, rect.Size.Height));
public static Rectangle SetWidth(this Rectangle rect, double width) => new(rect.Location, new Size(width, rect.Size.Height));
/// <summary>
/// Sets the <see cref="Size.Height"/> of the <see cref="Rectangle.Size"/> of the given rectangle.
@ -52,7 +52,7 @@ namespace RGB.NET.Core
/// <param name="rect">The rectangle to modify.</param>
/// <param name="height">The new height of the rectangle.</param>
/// <returns>The modified <see cref="Rectangle"/>.</returns>
public static Rectangle SetHeight(this Rectangle rect, double height) => new Rectangle(rect.Location, new Size(rect.Size.Width, height));
public static Rectangle SetHeight(this Rectangle rect, double height) => new(rect.Location, new Size(rect.Size.Width, height));
/// <summary>
/// Calculates the percentage of intersection of a rectangle.
@ -125,7 +125,7 @@ namespace RGB.NET.Core
/// <param name="x">The x-ammount to move.</param>
/// <param name="y">The y-ammount to move.</param>
/// <returns>The moved rectangle.</returns>
public static Rectangle Translate(this Rectangle rect, double x = 0, double y = 0) => new Rectangle(rect.Location.Translate(x, y), rect.Size);
public static Rectangle Translate(this Rectangle rect, double x = 0, double y = 0) => new(rect.Location.Translate(x, y), rect.Size);
/// <summary>
/// Rotates the specified <see cref="Rectangle"/> by the given amuont around the given origin.
@ -141,13 +141,13 @@ namespace RGB.NET.Core
/// <param name="rotation">The rotation.</param>
/// <param name="origin">The origin to rotate around. [0,0] if not set.</param>
/// <returns>A array of <see cref="Point"/> containing the new locations of the corners of the original rectangle.</returns>
public static Point[] Rotate(this Rectangle rect, Rotation rotation, Point origin = new Point())
public static Point[] Rotate(this Rectangle rect, Rotation rotation, Point origin = new())
{
Point[] points = {
rect.Location, // top left
new Point(rect.Location.X + rect.Size.Width, rect.Location.Y), // top right
new Point(rect.Location.X + rect.Size.Width, rect.Location.Y + rect.Size.Height), // bottom right
new Point(rect.Location.X, rect.Location.Y + rect.Size.Height), // bottom right
new(rect.Location.X + rect.Size.Width, rect.Location.Y), // top right
new(rect.Location.X + rect.Size.Width, rect.Location.Y + rect.Size.Height), // bottom right
new(rect.Location.X, rect.Location.Y + rect.Size.Height), // bottom right
};
double sin = Math.Sin(rotation.Radians);

View File

@ -11,8 +11,10 @@ namespace RGB.NET.Core
{
#region Properties & Fields
public RGBSurface? Surface { get; private set; }
/// <inheritdoc />
public IBrush Brush { get; set; }
public IBrush? Brush { get; set; }
/// <inheritdoc />
public int ZIndex { get; set; } = 0;
@ -24,11 +26,9 @@ namespace RGB.NET.Core
/// <summary>
/// Initializes a new instance of the <see cref="AbstractLedGroup"/> class.
/// </summary>
/// <param name="autoAttach">Specifies whether this <see cref="AbstractLedGroup"/> should be automatically attached or not.</param>
protected AbstractLedGroup(bool autoAttach)
protected AbstractLedGroup(RGBSurface? attachTo)
{
if (autoAttach)
RGBSurface.Instance.AttachLedGroup(this);
attachTo?.AttachLedGroup(this);
}
#endregion
@ -39,12 +39,10 @@ namespace RGB.NET.Core
public abstract IList<Led> GetLeds();
/// <inheritdoc />
public virtual void OnAttach()
{ }
public virtual void OnAttach(RGBSurface surface) => Surface = surface;
/// <inheritdoc />
public virtual void OnDetach()
{ }
public virtual void OnDetach(RGBSurface surface) => Surface = null;
#endregion
}

View File

@ -11,10 +11,12 @@ namespace RGB.NET.Core
/// </summary>
public interface ILedGroup : IDecoratable<ILedGroupDecorator>
{
public RGBSurface? Surface { get; }
/// <summary>
/// Gets or sets the <see cref="IBrush"/> which should be drawn over this <see cref="ILedGroup"/>.
/// </summary>
IBrush Brush { get; set; }
IBrush? Brush { get; set; }
/// <summary>
/// Gets or sets the z-index of this <see cref="ILedGroup"/> to allow ordering them before drawing. (lowest first) (default: 0)
@ -30,11 +32,11 @@ namespace RGB.NET.Core
/// <summary>
/// Called when the <see cref="ILedGroup"/> is attached to the <see cref="RGBSurface"/>.
/// </summary>
void OnAttach();
void OnAttach(RGBSurface surface);
/// <summary>
/// Called when the <see cref="ILedGroup"/> is detached from the <see cref="RGBSurface"/>.
/// </summary>
void OnDetach();
void OnDetach(RGBSurface surface);
}
}

View File

@ -1,4 +1,6 @@
namespace RGB.NET.Core
using System;
namespace RGB.NET.Core
{
/// <summary>
/// Contains helper methods for converting things.
@ -20,10 +22,10 @@
for (int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
{
byte b = ((byte)(bytes[bx] >> 4));
c[cx] = (char)(b > 9 ? b + 0x37: b + 0x30);
c[cx] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(bytes[bx] & 0x0F));
c[++cx] = (char)(b > 9 ? b + 0x37: b + 0x30);
c[++cx] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
return new string(c);
@ -35,10 +37,10 @@
/// </summary>
/// <param name="hexString">The HEX-string to convert.</param>
/// <returns>The correspondending byte array.</returns>
public static byte[] HexToBytes(string hexString)
public static byte[] HexToBytes(ReadOnlySpan<char> hexString)
{
if ((hexString.Length == 0) || ((hexString.Length % 2) != 0))
return new byte[0];
return Array.Empty<byte>();
byte[] buffer = new byte[hexString.Length / 2];
for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)

View File

@ -1,44 +0,0 @@
using System;
using System.Globalization;
using System.Runtime.InteropServices;
namespace RGB.NET.Core
{
/// <summary>
/// Offers some helper-methods for culture related things.
/// </summary>
public static class CultureHelper
{
#region DLLImports
[DllImport("user32.dll")]
private static extern IntPtr GetKeyboardLayout(uint thread);
#endregion
#region Constructors
#endregion
#region Methods
/// <summary>
/// Gets the current keyboard-layout from the OS.
/// </summary>
/// <returns>The current keyboard-layout</returns>
public static CultureInfo GetCurrentCulture()
{
try
{
int keyboardLayout = GetKeyboardLayout(0).ToInt32() & 0xFFFF;
return new CultureInfo(keyboardLayout);
}
catch
{
return new CultureInfo(1033); // en-US on error.
}
}
#endregion
}
}

View File

@ -1,83 +0,0 @@
using System;
using System.IO;
using System.Reflection;
namespace RGB.NET.Core
{
/// <summary>
/// Offers some helper-methods for file-path related things.
/// </summary>
public static class PathHelper
{
#region Events
/// <summary>
/// Occurs when a path is resolving.
/// </summary>
public static event EventHandler<ResolvePathEventArgs> ResolvingAbsolutePath;
#endregion
#region Methods
/// <summary>
/// Returns an absolute path created from an relative path relatvie to the location of the executung assembly.
/// </summary>
/// <param name="relativePath">The relative part of the path to convert.</param>
/// <returns>The absolute path.</returns>
public static string GetAbsolutePath(string relativePath) => GetAbsolutePath((object)null, relativePath);
/// <summary>
/// Returns an absolute path created from an relative path relatvie to the location of the executung assembly.
/// </summary>
/// <param name="relativePath">The relative part of the path to convert.</param>
/// <param name="fileName">The file name of the path to convert.</param>
/// <returns>The absolute path.</returns>
public static string GetAbsolutePath(string relativePath, string fileName) => GetAbsolutePath(null, relativePath, fileName);
/// <summary>
/// Returns an absolute path created from an relative path relatvie to the location of the executung assembly.
/// </summary>
/// <param name="sender">The requester of this path. (Used for better control when using the event to override this behavior.)</param>
/// <param name="relativePath">The relative path to convert.</param>
/// <param name="fileName">The file name of the path to convert.</param>
/// <returns>The absolute path.</returns>
public static string GetAbsolutePath(object sender, string relativePath, string fileName)
{
string relativePart = Path.Combine(relativePath, fileName);
string assemblyLocation = Assembly.GetEntryAssembly()?.Location;
if (assemblyLocation == null) return relativePart;
string directoryName = Path.GetDirectoryName(assemblyLocation);
string path = directoryName == null ? null : Path.Combine(directoryName, relativePart);
ResolvePathEventArgs args = new ResolvePathEventArgs(relativePath, fileName, path);
ResolvingAbsolutePath?.Invoke(sender, args);
return args.FinalPath;
}
/// <summary>
/// Returns an absolute path created from an relative path relatvie to the location of the executung assembly.
/// </summary>
/// <param name="sender">The requester of this path. (Used for better control when using the event to override this behavior.)</param>
/// <param name="relativePath">The relative path to convert.</param>
/// <returns>The absolute path.</returns>
public static string GetAbsolutePath(object sender, string relativePath)
{
string assemblyLocation = Assembly.GetEntryAssembly()?.Location;
if (assemblyLocation == null) return relativePath;
string directoryName = Path.GetDirectoryName(assemblyLocation);
string path = directoryName == null ? null : Path.Combine(directoryName, relativePath);
ResolvePathEventArgs args = new ResolvePathEventArgs(relativePath, path);
ResolvingAbsolutePath?.Invoke(sender, args);
return args.FinalPath;
}
#endregion
}
}

View File

@ -35,11 +35,11 @@ namespace RGB.NET.Core
set => SetProperty(ref _shape, value);
}
private string _shapeData;
private string? _shapeData;
/// <summary>
/// Gets or sets the data used for by the <see cref="Core.Shape.Custom"/>-<see cref="Core.Shape"/>.
/// </summary>
public string ShapeData
public string? ShapeData
{
get => _shapeData;
set => SetProperty(ref _shapeData, value);
@ -124,7 +124,7 @@ namespace RGB.NET.Core
/// <summary>
/// Indicates whether the <see cref="Led" /> is about to change it's color.
/// </summary>
public bool IsDirty => RequestedColor.HasValue && (RequestedColor != InternalColor);
public bool IsDirty => RequestedColor.HasValue && (RequestedColor != Color);
private Color? _requestedColor;
/// <summary>
@ -152,45 +152,24 @@ namespace RGB.NET.Core
get => _color;
set
{
if (!IsLocked)
{
if (RequestedColor.HasValue)
RequestedColor += value;
else
RequestedColor = value;
}
if (RequestedColor.HasValue)
RequestedColor = RequestedColor.Value + value;
else
RequestedColor = value;
}
}
/// <summary>
/// Gets or set the <see cref="Color"/> ignoring all workflows regarding locks and update-requests. />
/// </summary>
internal Color InternalColor
{
get => _color;
set => SetProperty(ref _color, value);
}
private bool _isLocked;
/// <summary>
/// Gets or sets if the color of this LED can be changed.
/// </summary>
public bool IsLocked
{
get => _isLocked;
set => SetProperty(ref _isLocked, value);
}
/// <summary>
/// Gets the URI of an image of the <see cref="Led"/> or null if there is no image.
/// </summary>
public Uri Image { get; set; }
public Uri? Image { get; set; }
/// <summary>
/// Gets the provider-specific data associated with this led.
/// </summary>
public object CustomData { get; }
public object? CustomData { get; }
public object? LayoutMetadata { get; set; }
#endregion
@ -204,7 +183,7 @@ namespace RGB.NET.Core
/// <param name="location">The physical location of the <see cref="Led"/> relative to the <see cref="Device"/>.</param>
/// <param name="size">The size of the <see cref="Led"/>.</param>
/// <param name="customData">The provider-specific data associated with this led.</param>
internal Led(IRGBDevice device, LedId id, Point location, Size size, object customData = null)
internal Led(IRGBDevice device, LedId id, Point location, Size size, object? customData = null)
{
this.Device = device;
this.Id = id;
@ -219,14 +198,18 @@ namespace RGB.NET.Core
#region Methods
private void DevicePropertyChanged(object sender, PropertyChangedEventArgs e)
private void DevicePropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if ((e.PropertyName == nameof(IRGBDevice.Location)))
UpdateAbsoluteData();
else if (e.PropertyName == nameof(IRGBDevice.DeviceRectangle))
switch (e.PropertyName)
{
UpdateActualData();
UpdateAbsoluteData();
case nameof(IRGBDevice.Location):
UpdateAbsoluteData();
break;
case nameof(IRGBDevice.DeviceRectangle):
UpdateActualData();
UpdateAbsoluteData();
break;
}
}
@ -235,13 +218,13 @@ namespace RGB.NET.Core
ActualSize = Size * Device.Scale;
Point actualLocation = (Location * Device.Scale);
Rectangle ledRectangle = new Rectangle(Location * Device.Scale, Size * Device.Scale);
Rectangle ledRectangle = new(Location * Device.Scale, Size * Device.Scale);
if (Device.Rotation.IsRotated)
{
Point deviceCenter = new Rectangle(Device.ActualSize).Center;
Point actualDeviceCenter = new Rectangle(Device.DeviceRectangle.Size).Center;
Point centerOffset = new Point(actualDeviceCenter.X - deviceCenter.X, actualDeviceCenter.Y - deviceCenter.Y);
Point centerOffset = new(actualDeviceCenter.X - deviceCenter.X, actualDeviceCenter.Y - deviceCenter.Y);
actualLocation = actualLocation.Rotate(Device.Rotation, new Rectangle(Device.ActualSize).Center) + centerOffset;
ledRectangle = new Rectangle(ledRectangle.Rotate(Device.Rotation, new Rectangle(Device.ActualSize).Center)).Translate(centerOffset);
@ -283,7 +266,6 @@ namespace RGB.NET.Core
{
_color = Color.Transparent;
RequestedColor = null;
IsLocked = false;
// ReSharper disable once ExplicitCallerInfoArgument
OnPropertyChanged(nameof(Color));
@ -297,13 +279,13 @@ namespace RGB.NET.Core
/// Converts a <see cref="Led" /> to a <see cref="Core.Color" />.
/// </summary>
/// <param name="led">The <see cref="Led"/> to convert.</param>
public static implicit operator Color(Led led) => led?.Color ?? Color.Transparent;
public static implicit operator Color(Led led) => led.Color;
/// <summary>
/// Converts a <see cref="Led" /> to a <see cref="Rectangle" />.
/// </summary>
/// <param name="led">The <see cref="Led"/> to convert.</param>
public static implicit operator Rectangle(Led led) => led?.LedRectangle ?? new Rectangle();
public static implicit operator Rectangle(Led led) => led.LedRectangle;
#endregion
}

View File

@ -14,7 +14,7 @@ namespace RGB.NET.Core
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangedEventHandler? PropertyChanged;
#endregion
@ -28,10 +28,7 @@ namespace RGB.NET.Core
/// <param name="value">Value to apply.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual bool RequiresUpdate<T>(ref T storage, T value)
{
return !Equals(storage, value);
}
protected virtual bool RequiresUpdate<T>(ref T storage, T value) => !Equals(storage, value);
/// <summary>
/// Checks if the property already matches the desired value and updates it if not.
@ -42,13 +39,13 @@ namespace RGB.NET.Core
/// <param name="propertyName">Name of the property used to notify listeners. This value is optional
/// and can be provided automatically when invoked from compilers that support <see cref="CallerMemberNameAttribute"/>.</param>
/// <returns><c>true</c> if the value was changed, <c>false</c> if the existing value matched the desired value.</returns>
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string? propertyName = null)
{
if (!this.RequiresUpdate(ref storage, value)) return false;
if (!RequiresUpdate(ref storage, value)) return false;
storage = value;
// ReSharper disable once ExplicitCallerInfoArgument
this.OnPropertyChanged(propertyName);
OnPropertyChanged(propertyName);
return true;
}
@ -57,10 +54,8 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="propertyName">Name of the property used to notify listeners. This value is optional
/// and can be provided automatically when invoked from compilers that support <see cref="CallerMemberNameAttribute"/>.</param>
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
#endregion
}

View File

@ -9,14 +9,14 @@ namespace RGB.NET.Core
/// Represents a point consisting of a X- and a Y-position.
/// </summary>
[DebuggerDisplay("[X: {X}, Y: {Y}]")]
public struct Point
public readonly struct Point
{
#region Constants
/// <summary>
/// Gets a [NaN,NaN]-Point.
/// </summary>
public static Point Invalid => new Point(double.NaN, double.NaN);
public static Point Invalid => new(double.NaN, double.NaN);
#endregion
@ -62,13 +62,13 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Point" /> equivalent to this <see cref="Point" />; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (!(obj is Point)) return false;
Point comparePoint = (Point)obj;
return ((double.IsNaN(X) && double.IsNaN(comparePoint.X)) || X.EqualsInTolerance(comparePoint.X))
&& ((double.IsNaN(Y) && double.IsNaN(comparePoint.Y)) || Y.EqualsInTolerance(comparePoint.Y));
&& ((double.IsNaN(Y) && double.IsNaN(comparePoint.Y)) || Y.EqualsInTolerance(comparePoint.Y));
}
/// <summary>
@ -111,7 +111,7 @@ namespace RGB.NET.Core
/// <param name="point1">The first <see cref="Point"/>.</param>
/// <param name="point2">The second <see cref="Point"/>.</param>
/// <returns>A new <see cref="Point"/> representing the addition of the two provided <see cref="Point"/>.</returns>
public static Point operator +(Point point1, Point point2) => new Point(point1.X + point2.X, point1.Y + point2.Y);
public static Point operator +(Point point1, Point point2) => new(point1.X + point2.X, point1.Y + point2.Y);
/// <summary>
/// Returns a new <see cref="Rectangle"/> created from the provided <see cref="Point"/> and <see cref="Size"/>.
@ -119,7 +119,7 @@ namespace RGB.NET.Core
/// <param name="point">The <see cref="Point"/> of the rectangle.</param>
/// <param name="size">The <see cref="Size"/> of the rectangle.</param>
/// <returns>The rectangle created from the provided <see cref="Point"/> and <see cref="Size"/>.</returns>
public static Rectangle operator +(Point point, Size size) => new Rectangle(point, size);
public static Rectangle operator +(Point point, Size size) => new(point, size);
/// <summary>
/// Returns a new <see cref="Point"/> representing the subtraction of the two provided <see cref="Point"/>.
@ -127,7 +127,7 @@ namespace RGB.NET.Core
/// <param name="point1">The first <see cref="Point"/>.</param>
/// <param name="point2">The second <see cref="Point"/>.</param>
/// <returns>A new <see cref="Point"/> representing the subtraction of the two provided <see cref="Point"/>.</returns>
public static Point operator -(Point point1, Point point2) => new Point(point1.X - point2.X, point1.Y - point2.Y);
public static Point operator -(Point point1, Point point2) => new(point1.X - point2.X, point1.Y - point2.Y);
/// <summary>
/// Returns a new <see cref="Point"/> representing the multiplication of the two provided <see cref="Point"/>.
@ -135,7 +135,7 @@ namespace RGB.NET.Core
/// <param name="point1">The first <see cref="Point"/>.</param>
/// <param name="point2">The second <see cref="Point"/>.</param>
/// <returns>A new <see cref="Point"/> representing the multiplication of the two provided <see cref="Point"/>.</returns>
public static Point operator *(Point point1, Point point2) => new Point(point1.X * point2.X, point1.Y * point2.Y);
public static Point operator *(Point point1, Point point2) => new(point1.X * point2.X, point1.Y * point2.Y);
/// <summary>
/// Returns a new <see cref="Point"/> representing the division of the two provided <see cref="Point"/>.
@ -155,7 +155,7 @@ namespace RGB.NET.Core
/// <param name="point">The <see cref="Point"/>.</param>
/// <param name="scale">The <see cref="Scale"/>.</param>
/// <returns>A new <see cref="Point"/> representing the multiplication of the <see cref="Point"/> and the provided <see cref="Scale"/>.</returns>
public static Point operator *(Point point, Scale scale) => new Point(point.X * scale.Horizontal, point.Y * scale.Vertical);
public static Point operator *(Point point, Scale scale) => new(point.X * scale.Horizontal, point.Y * scale.Vertical);
#endregion
}

View File

@ -12,7 +12,7 @@ namespace RGB.NET.Core
/// Represents a rectangle defined by it's position and it's size.
/// </summary>
[DebuggerDisplay("[Location: {Location}, Size: {Size}]")]
public struct Rectangle
public readonly struct Rectangle
{
#region Properties & Fields
@ -69,6 +69,7 @@ namespace RGB.NET.Core
{
this.Location = location;
this.Size = size;
Center = new Point(Location.X + (Size.Width / 2.0), Location.Y + (Size.Height / 2.0));
}
@ -95,15 +96,14 @@ namespace RGB.NET.Core
double posX2 = double.MinValue;
double posY2 = double.MinValue;
if (rectangles != null)
foreach (Rectangle rectangle in rectangles)
{
hasPoint = true;
posX = Math.Min(posX, rectangle.Location.X);
posY = Math.Min(posY, rectangle.Location.Y);
posX2 = Math.Max(posX2, rectangle.Location.X + rectangle.Size.Width);
posY2 = Math.Max(posY2, rectangle.Location.Y + rectangle.Size.Height);
}
foreach (Rectangle rectangle in rectangles)
{
hasPoint = true;
posX = Math.Min(posX, rectangle.Location.X);
posY = Math.Min(posY, rectangle.Location.Y);
posX2 = Math.Max(posX2, rectangle.Location.X + rectangle.Size.Width);
posY2 = Math.Max(posY2, rectangle.Location.Y + rectangle.Size.Height);
}
(Point location, Size size) = hasPoint ? InitializeFromPoints(new Point(posX, posY), new Point(posX2, posY2)) : InitializeFromPoints(new Point(0, 0), new Point(0, 0));
Location = location;
@ -136,15 +136,14 @@ namespace RGB.NET.Core
double posX2 = double.MinValue;
double posY2 = double.MinValue;
if (points != null)
foreach (Point point in points)
{
hasPoint = true;
posX = Math.Min(posX, point.X);
posY = Math.Min(posY, point.Y);
posX2 = Math.Max(posX2, point.X);
posY2 = Math.Max(posY2, point.Y);
}
foreach (Point point in points)
{
hasPoint = true;
posX = Math.Min(posX, point.X);
posY = Math.Min(posY, point.Y);
posX2 = Math.Max(posX2, point.X);
posY2 = Math.Max(posY2, point.Y);
}
(Point location, Size size) = hasPoint ? InitializeFromPoints(new Point(posX, posY), new Point(posX2, posY2)) : InitializeFromPoints(new Point(0, 0), new Point(0, 0));
@ -178,7 +177,7 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Rectangle" /> equivalent to this <see cref="Rectangle" />; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (!(obj is Rectangle compareRect))
return false;

View File

@ -9,8 +9,8 @@ namespace RGB.NET.Core
/// <summary>
/// Represents an angular rotation.
/// </summary>
[DebuggerDisplay("[{Degrees}°]")]
public struct Rotation
[DebuggerDisplay("[{" + nameof(Degrees) + "}°]")]
public readonly struct Rotation
{
#region Constants
@ -64,14 +64,14 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="degrees">The angle in degrees.</param>
/// <returns>The new rotation.</returns>
public static Rotation FromDegrees(double degrees) => new Rotation(degrees);
public static Rotation FromDegrees(double degrees) => new(degrees);
/// <summary>
/// Creates a new Rotation out of the given radian-angle.
/// </summary>
/// <param name="degrees">The angle in radians.</param>
/// <returns>The new rotation.</returns>
public static Rotation FromRadians(double radians) => new Rotation(radians * RADIANS_DEGREES_CONVERSION, radians);
public static Rotation FromRadians(double radians) => new(radians * RADIANS_DEGREES_CONVERSION, radians);
/// <summary>
/// Tests whether the specified <see cref="Rotation" /> is equivalent to this <see cref="Rotation" />.
@ -85,7 +85,7 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Rotation" /> equivalent to this <see cref="Rotation" />; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj) => obj is Rotation other && Equals(other);
public override bool Equals(object? obj) => obj is Rotation other && Equals(other);
/// <summary>
/// Returns a hash code for this <see cref="Rotation" />.
@ -119,7 +119,7 @@ namespace RGB.NET.Core
/// <param name="rotation">The <see cref="Rotation"/>.</param>
/// <param name="value">The value to add.</param>
/// <returns>A new <see cref="Rotation"/> representing the addition of the <see cref="Rotation"/> and the provided value.</returns>
public static Rotation operator +(Rotation rotation, double value) => new Rotation(rotation.Degrees + value);
public static Rotation operator +(Rotation rotation, double value) => new(rotation.Degrees + value);
/// <summary>
/// Returns a new <see cref="Rotation"/> representing the subtraction of the <see cref="Rotation"/> and the provided value.
@ -127,7 +127,7 @@ namespace RGB.NET.Core
/// <param name="rotation">The <see cref="Rotation"/>.</param>
/// <param name="value">The value to substract.</param>
/// <returns>A new <see cref="Rotation"/> representing the subtraction of the <see cref="Rotation"/> and the provided value.</returns>
public static Rotation operator -(Rotation rotation, double value) => new Rotation(rotation.Degrees - value);
public static Rotation operator -(Rotation rotation, double value) => new(rotation.Degrees - value);
/// <summary>
/// Returns a new <see cref="Rotation"/> representing the multiplication of the <see cref="Rotation"/> and the provided value.
@ -135,7 +135,7 @@ namespace RGB.NET.Core
/// <param name="rotation">The <see cref="Rotation"/>.</param>
/// <param name="value">The value to multiply with.</param>
/// <returns>A new <see cref="Rotation"/> representing the multiplication of the <see cref="Rotation"/> and the provided value.</returns>
public static Rotation operator *(Rotation rotation, double value) => new Rotation(rotation.Degrees * value);
public static Rotation operator *(Rotation rotation, double value) => new(rotation.Degrees * value);
/// <summary>
/// Returns a new <see cref="Rotation"/> representing the division of the <see cref="Rotation"/> and the provided value.
@ -149,7 +149,7 @@ namespace RGB.NET.Core
/// Converts a double to a <see cref="Rotation" />.
/// </summary>
/// <param name="rotation">The rotation in degrees to convert.</param>
public static implicit operator Rotation(double rotation) => new Rotation(rotation);
public static implicit operator Rotation(double rotation) => new(rotation);
/// <summary>
/// Converts <see cref="Rotation" /> to a double representing the rotation in degrees.

View File

@ -9,7 +9,7 @@ namespace RGB.NET.Core
/// Represents a scaling.
/// </summary>
[DebuggerDisplay("[Horizontal: {Horizontal}, Vertical: {Vertical}]")]
public struct Scale
public readonly struct Scale
{
#region Properties & Fields
@ -61,7 +61,7 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Scale" /> equivalent to this <see cref="Scale" />; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj) => obj is Scale other && Equals(other);
public override bool Equals(object? obj) => obj is Scale other && Equals(other);
/// <summary>
/// Returns a hash code for this <see cref="Scale" />.
@ -106,7 +106,7 @@ namespace RGB.NET.Core
/// <param name="scale">The <see cref="Scale"/>.</param>
/// <param name="value">The value to add.</param>
/// <returns>A new <see cref="Scale"/> representing the addition of the <see cref="Scale"/> and the provided value.</returns>
public static Scale operator +(Scale scale, double value) => new Scale(scale.Horizontal + value, scale.Vertical + value);
public static Scale operator +(Scale scale, double value) => new(scale.Horizontal + value, scale.Vertical + value);
/// <summary>
/// Returns a new <see cref="Scale"/> representing the subtraction of the <see cref="Scale"/> and the provided value.
@ -114,7 +114,7 @@ namespace RGB.NET.Core
/// <param name="scale">The <see cref="Scale"/>.</param>
/// <param name="value">The value to substract.</param>
/// <returns>A new <see cref="Scale"/> representing the subtraction of the <see cref="Scale"/> and the provided value.</returns>
public static Scale operator -(Scale scale, double value) => new Scale(scale.Horizontal - value, scale.Vertical - value);
public static Scale operator -(Scale scale, double value) => new(scale.Horizontal - value, scale.Vertical - value);
/// <summary>
/// Returns a new <see cref="Scale"/> representing the multiplication of the <see cref="Scale"/> and the provided value.
@ -122,7 +122,7 @@ namespace RGB.NET.Core
/// <param name="scale">The <see cref="Scale"/>.</param>
/// <param name="value">The value to multiply with.</param>
/// <returns>A new <see cref="Scale"/> representing the multiplication of the <see cref="Scale"/> and the provided value.</returns>
public static Scale operator *(Scale scale, double value) => new Scale(scale.Horizontal * value, scale.Vertical * value);
public static Scale operator *(Scale scale, double value) => new(scale.Horizontal * value, scale.Vertical * value);
/// <summary>
/// Returns a new <see cref="Scale"/> representing the division of the <see cref="Scale"/> and the provided value.
@ -137,7 +137,7 @@ namespace RGB.NET.Core
/// Converts a double to a <see cref="Scale" />.
/// </summary>
/// <param name="scale">The scale value to convert.</param>
public static implicit operator Scale(double scale) => new Scale(scale);
public static implicit operator Scale(double scale) => new(scale);
#endregion
}

View File

@ -1,10 +1,9 @@
using System;
using RGB.NET.Core.Layout;
namespace RGB.NET.Core
{
/// <summary>
/// Contains a list of different shapes used by <see cref="DeviceLayout"/>.
/// Contains a list of different shapes used to define the layout of a LED.
/// </summary>
[Serializable]
public enum Shape

View File

@ -9,14 +9,14 @@ namespace RGB.NET.Core
/// Represents a size consisting of a width and a height.
/// </summary>
[DebuggerDisplay("[Width: {Width}, Height: {Height}]")]
public struct Size
public readonly struct Size
{
#region Constants
/// <summary>
/// Gets a [NaN,NaN]-Size.
/// </summary>
public static Size Invalid => new Size(double.NaN, double.NaN);
public static Size Invalid => new(double.NaN, double.NaN);
#endregion
@ -71,13 +71,13 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <paramref name="obj" /> is a <see cref="Size" /> equivalent to this <see cref="Size" />; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (!(obj is Size)) return false;
if (!(obj is Size size)) return false;
Size compareSize = (Size)obj;
return ((double.IsNaN(Width) && double.IsNaN(compareSize.Width)) || Width.EqualsInTolerance(compareSize.Width))
&& ((double.IsNaN(Height) && double.IsNaN(compareSize.Height)) || Height.EqualsInTolerance(compareSize.Height));
(double width, double height) = size;
return ((double.IsNaN(Width) && double.IsNaN(width)) || Width.EqualsInTolerance(width))
&& ((double.IsNaN(Height) && double.IsNaN(height)) || Height.EqualsInTolerance(height));
}
/// <summary>
@ -131,7 +131,7 @@ namespace RGB.NET.Core
/// <param name="size1">The first <see cref="Size"/>.</param>
/// <param name="size2">The second <see cref="Size"/>.</param>
/// <returns>A new <see cref="Size"/> representing the addition of the two provided <see cref="Size"/>.</returns>
public static Size operator +(Size size1, Size size2) => new Size(size1.Width + size2.Width, size1.Height + size2.Height);
public static Size operator +(Size size1, Size size2) => new(size1.Width + size2.Width, size1.Height + size2.Height);
/// <summary>
/// Returns a new <see cref="Rectangle"/> created from the provided <see cref="Point"/> and <see cref="Size"/>.
@ -139,7 +139,7 @@ namespace RGB.NET.Core
/// <param name="size">The <see cref="Size"/> of the rectangle.</param>
/// <param name="point">The <see cref="Point"/> of the rectangle.</param>
/// <returns>The rectangle created from the provided <see cref="Point"/> and <see cref="Size"/>.</returns>
public static Rectangle operator +(Size size, Point point) => new Rectangle(point, size);
public static Rectangle operator +(Size size, Point point) => new(point, size);
/// <summary>
/// Returns a new <see cref="Size"/> representing the subtraction of the two provided <see cref="Size"/>.
@ -147,7 +147,7 @@ namespace RGB.NET.Core
/// <param name="size1">The first <see cref="Size"/>.</param>
/// <param name="size2">The second <see cref="Size"/>.</param>
/// <returns>A new <see cref="Size"/> representing the subtraction of the two provided <see cref="Size"/>.</returns>
public static Size operator -(Size size1, Size size2) => new Size(size1.Width - size2.Width, size1.Height - size2.Height);
public static Size operator -(Size size1, Size size2) => new(size1.Width - size2.Width, size1.Height - size2.Height);
/// <summary>
/// Returns a new <see cref="Size"/> representing the multiplication of the two provided <see cref="Size"/>.
@ -155,7 +155,7 @@ namespace RGB.NET.Core
/// <param name="size1">The first <see cref="Size"/>.</param>
/// <param name="size2">The second <see cref="Size"/>.</param>
/// <returns>A new <see cref="Size"/> representing the multiplication of the two provided <see cref="Size"/>.</returns>
public static Size operator *(Size size1, Size size2) => new Size(size1.Width * size2.Width, size1.Height * size2.Height);
public static Size operator *(Size size1, Size size2) => new(size1.Width * size2.Width, size1.Height * size2.Height);
/// <summary>
/// Returns a new <see cref="Size"/> representing the multiplication of the <see cref="Size"/> and the provided factor.
@ -163,7 +163,7 @@ namespace RGB.NET.Core
/// <param name="size">The <see cref="Size"/>.</param>
/// <param name="factor">The factor by which the <see cref="Size"/> should be multiplied.</param>
/// <returns>A new <see cref="Size"/> representing the multiplication of the <see cref="Size"/> and the provided factor.</returns>
public static Size operator *(Size size, double factor) => new Size(size.Width * factor, size.Height * factor);
public static Size operator *(Size size, double factor) => new(size.Width * factor, size.Height * factor);
/// <summary>
/// Returns a new <see cref="Size"/> representing the division of the two provided <see cref="Size"/>.
@ -189,7 +189,7 @@ namespace RGB.NET.Core
/// <param name="size">The <see cref="Size"/> to scale.</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>A new <see cref="Size"/> representing the multiplication of the <see cref="Size"/> and the given <see cref="Scale"/>.</returns>
public static Size operator *(Size size, Scale scale) => new Size(size.Width * scale.Horizontal, size.Height * scale.Vertical);
public static Size operator *(Size size, Scale scale) => new(size.Width * scale.Horizontal, size.Height * scale.Vertical);
#endregion
}

View File

@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
@ -14,24 +15,18 @@ namespace RGB.NET.Core
/// <summary>
/// Represents a RGB-surface containing multiple devices.
/// </summary>
public partial class RGBSurface : AbstractBindable, IDisposable
public class RGBSurface : AbstractBindable, IDisposable
{
#region Properties & Fields
/// <summary>
/// Gets the singelot-instance of the <see cref="RGBSurface"/> class.
/// </summary>
public static RGBSurface Instance { get; } = new RGBSurface();
private Stopwatch _deltaTimeCounter;
private IList<IRGBDeviceProvider> _deviceProvider = new List<IRGBDeviceProvider>();
private IList<IRGBDevice> _devices = new List<IRGBDevice>();
private IList<IUpdateTrigger> _updateTriggers = new List<IUpdateTrigger>();
// ReSharper disable InconsistentNaming
private readonly LinkedList<ILedGroup> _ledGroups = new LinkedList<ILedGroup>();
private readonly LinkedList<ILedGroup> _ledGroups = new();
// ReSharper restore InconsistentNaming
@ -71,12 +66,68 @@ namespace RGB.NET.Core
#endregion
#region EventHandler
/// <summary>
/// Represents the event-handler of the <see cref="Exception"/>-event.
/// </summary>
/// <param name="args">The arguments provided by the event.</param>
public delegate void ExceptionEventHandler(ExceptionEventArgs args);
/// <summary>
/// Represents the event-handler of the <see cref="Updating"/>-event.
/// </summary>
/// <param name="args">The arguments provided by the event.</param>
public delegate void UpdatingEventHandler(UpdatingEventArgs args);
/// <summary>
/// Represents the event-handler of the <see cref="Updated"/>-event.
/// </summary>
/// <param name="args">The arguments provided by the event.</param>
public delegate void UpdatedEventHandler(UpdatedEventArgs args);
/// <summary>
/// Represents the event-handler of the <see cref="SurfaceLayoutChanged"/>-event.
/// </summary>
/// <param name="args"></param>
public delegate void SurfaceLayoutChangedEventHandler(SurfaceLayoutChangedEventArgs args);
#endregion
#region Events
// ReSharper disable EventNeverSubscribedTo.Global
/// <summary>
/// Occurs when a catched exception is thrown inside the <see cref="RGBSurface"/>.
/// </summary>
public event ExceptionEventHandler? Exception;
/// <summary>
/// Occurs when the <see cref="RGBSurface"/> starts updating.
/// </summary>
public event UpdatingEventHandler? Updating;
/// <summary>
/// Occurs when the <see cref="RGBSurface"/> update is done.
/// </summary>
public event UpdatedEventHandler? Updated;
/// <summary>
/// Occurs when the layout of this <see cref="RGBSurface"/> changed.
/// </summary>
public event SurfaceLayoutChangedEventHandler? SurfaceLayoutChanged;
// ReSharper restore EventNeverSubscribedTo.Global
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="RGBSurface"/> class.
/// </summary>
private RGBSurface()
public RGBSurface()
{
_deltaTimeCounter = Stopwatch.StartNew();
}
@ -91,13 +142,10 @@ namespace RGB.NET.Core
/// <param name="flushLeds">Specifies whether all <see cref="Led"/>, (including clean ones) should be updated.</param>
public void Update(bool flushLeds = false) => Update(null, new CustomUpdateData(("flushLeds", flushLeds)));
private void Update(object updateTrigger, CustomUpdateData customData) => Update(updateTrigger as IUpdateTrigger, customData);
private void Update(object? updateTrigger, CustomUpdateData customData) => Update(updateTrigger as IUpdateTrigger, customData);
private void Update(IUpdateTrigger updateTrigger, CustomUpdateData customData)
private void Update(IUpdateTrigger? updateTrigger, CustomUpdateData customData)
{
if (customData == null)
customData = new CustomUpdateData();
try
{
bool flushLeds = customData["flushLeds"] as bool? ?? false;
@ -108,7 +156,7 @@ namespace RGB.NET.Core
lock (_devices)
{
OnUpdating(updateTrigger, customData);
if (render)
lock (_ledGroups)
{
@ -120,9 +168,8 @@ namespace RGB.NET.Core
if (updateDevices)
foreach (IRGBDevice device in _devices)
if (!device.UpdateMode.HasFlag(DeviceUpdateMode.NoUpdate))
try { device.Update(flushLeds); }
catch (Exception ex) { OnException(ex); }
try { device.Update(flushLeds); }
catch (Exception ex) { OnException(ex); }
OnUpdated();
}
@ -136,23 +183,19 @@ namespace RGB.NET.Core
/// <inheritdoc />
public void Dispose()
{
List<IRGBDevice> devices;
lock (_devices)
foreach (IRGBDevice device in _devices)
try { device.Dispose(); }
catch { /* We do what we can */}
devices = new List<IRGBDevice>(_devices);
lock (_deviceProvider)
foreach (IRGBDeviceProvider deviceProvider in _deviceProvider)
try { deviceProvider.Dispose(); }
catch { /* We do what we can */}
foreach (IRGBDevice device in devices)
try { Detach(device); }
catch { /* We do what we can */}
foreach (IUpdateTrigger updateTrigger in _updateTriggers)
try { updateTrigger.Dispose(); }
catch { /* We do what we can */}
_ledGroups.Clear();
_devices = null;
_deviceProvider = null;
}
/// <summary>
@ -162,15 +205,15 @@ namespace RGB.NET.Core
private void Render(ILedGroup ledGroup)
{
IList<Led> leds = ledGroup.GetLeds().ToList();
IBrush brush = ledGroup.Brush;
IBrush? brush = ledGroup.Brush;
if ((brush == null) || !brush.IsEnabled) return;
switch (brush.BrushCalculationMode)
{
case BrushCalculationMode.Relative:
Rectangle brushRectangle = new Rectangle(leds.Select(led => led.AbsoluteLedRectangle));
Point offset = new Point(-brushRectangle.Location.X, -brushRectangle.Location.Y);
Rectangle brushRectangle = new(leds.Select(led => led.AbsoluteLedRectangle));
Point offset = new(-brushRectangle.Location.X, -brushRectangle.Location.Y);
brushRectangle = brushRectangle.SetLocation(new Point(0, 0));
brush.PerformRender(brushRectangle, leds.Select(led => new BrushRenderTarget(led, led.AbsoluteLedRectangle.Translate(offset))));
break;
@ -195,14 +238,12 @@ namespace RGB.NET.Core
/// <returns><c>true</c> if the <see cref="ILedGroup"/> could be attached; otherwise, <c>false</c>.</returns>
public bool AttachLedGroup(ILedGroup ledGroup)
{
if (ledGroup == null) return false;
lock (_ledGroups)
{
if (_ledGroups.Contains(ledGroup)) return false;
_ledGroups.AddLast(ledGroup);
ledGroup.OnAttach();
ledGroup.OnAttach(this);
return true;
}
@ -215,25 +256,86 @@ namespace RGB.NET.Core
/// <returns><c>true</c> if the <see cref="ILedGroup"/> could be detached; otherwise, <c>false</c>.</returns>
public bool DetachLedGroup(ILedGroup ledGroup)
{
if (ledGroup == null) return false;
lock (_ledGroups)
{
LinkedListNode<ILedGroup> node = _ledGroups.Find(ledGroup);
LinkedListNode<ILedGroup>? node = _ledGroups.Find(ledGroup);
if (node == null) return false;
_ledGroups.Remove(node);
node.Value.OnDetach();
node.Value.OnDetach(this);
return true;
}
}
public void Attach(IEnumerable<IRGBDevice> devices)
{
lock (_devices)
{
foreach (IRGBDevice device in devices)
Attach(device);
}
}
public void Attach(IRGBDevice device)
{
lock (_devices)
{
if (_devices.Contains(device)) throw new RGBSurfaceException($"The device '{device.DeviceInfo.Manufacturer} {device.DeviceInfo.Model}' is already attached.");
device.Surface = this;
_devices.Add(device);
}
}
public void Detach(IEnumerable<IRGBDevice> devices)
{
lock (_devices)
{
foreach (IRGBDevice device in devices)
Detach(device);
}
}
public void Detach(IRGBDevice device)
{
lock (_devices)
{
if (!_devices.Contains(device)) throw new RGBSurfaceException($"The device '{device.DeviceInfo.Manufacturer} {device.DeviceInfo.Model}' isn't attached.");
device.Surface = null;
_devices.Remove(device);
}
}
/// <summary>
/// Automatically aligns all devices to prevent overlaps.
/// </summary>
public void AlignDevices()
{
double posX = 0;
foreach (IRGBDevice device in Devices)
{
device.Location += new Point(posX, 0);
posX += device.ActualSize.Width + 1;
}
}
// ReSharper restore UnusedMember.Global
private void DeviceOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
UpdateSurfaceRectangle();
SurfaceLayoutChanged?.Invoke(new SurfaceLayoutChangedEventArgs((sender is IRGBDevice device) ? new[] { device } : Array.Empty<IRGBDevice>(), false, true));
}
private void UpdateSurfaceRectangle()
{
lock (_devices)
{
Rectangle devicesRectangle = new Rectangle(_devices.Select(d => d.DeviceRectangle));
Rectangle devicesRectangle = new(_devices.Select(d => d.DeviceRectangle));
SurfaceRectangle = SurfaceRectangle.SetSize(new Size(devicesRectangle.Location.X + devicesRectangle.Size.Width, devicesRectangle.Location.Y + devicesRectangle.Size.Height));
}
}
@ -247,7 +349,7 @@ namespace RGB.NET.Core
where T : class
{
lock (_devices)
return new ReadOnlyCollection<T>(_devices.Select(x => x as T).Where(x => x != null).ToList());
return new ReadOnlyCollection<T>(_devices.Where(x => x is T).Cast<T>().ToList());
}
/// <summary>
@ -284,6 +386,45 @@ namespace RGB.NET.Core
updateTrigger.Update -= Update;
}
/// <summary>
/// Handles the needed event-calls for an exception.
/// </summary>
/// <param name="ex">The exception previously thrown.</param>
private void OnException(Exception ex)
{
try
{
Exception?.Invoke(new ExceptionEventArgs(ex));
}
catch { /* Well ... that's not my fault */ }
}
/// <summary>
/// Handles the needed event-calls before updating.
/// </summary>
private void OnUpdating(IUpdateTrigger? trigger, CustomUpdateData customData)
{
try
{
double deltaTime = _deltaTimeCounter.Elapsed.TotalSeconds;
_deltaTimeCounter.Restart();
Updating?.Invoke(new UpdatingEventArgs(deltaTime, trigger, customData));
}
catch { /* Well ... that's not my fault */ }
}
/// <summary>
/// Handles the needed event-calls after an update.
/// </summary>
private void OnUpdated()
{
try
{
Updated?.Invoke(new UpdatedEventArgs());
}
catch { /* Well ... that's not my fault */ }
}
#endregion
}
}

View File

@ -1,106 +0,0 @@
using System;
namespace RGB.NET.Core
{
public partial class RGBSurface
{
#region EventHandler
/// <summary>
/// Represents the event-handler of the <see cref="Exception"/>-event.
/// </summary>
/// <param name="args">The arguments provided by the event.</param>
public delegate void ExceptionEventHandler(ExceptionEventArgs args);
/// <summary>
/// Represents the event-handler of the <see cref="Updating"/>-event.
/// </summary>
/// <param name="args">The arguments provided by the event.</param>
public delegate void UpdatingEventHandler(UpdatingEventArgs args);
/// <summary>
/// Represents the event-handler of the <see cref="Updated"/>-event.
/// </summary>
/// <param name="args">The arguments provided by the event.</param>
public delegate void UpdatedEventHandler(UpdatedEventArgs args);
/// <summary>
/// Represents the event-handler of the <see cref="SurfaceLayoutChanged"/>-event.
/// </summary>
/// <param name="args"></param>
public delegate void SurfaceLayoutChangedEventHandler(SurfaceLayoutChangedEventArgs args);
#endregion
#region Events
// ReSharper disable EventNeverSubscribedTo.Global
/// <summary>
/// Occurs when a catched exception is thrown inside the <see cref="RGBSurface"/>.
/// </summary>
public event ExceptionEventHandler Exception;
/// <summary>
/// Occurs when the <see cref="RGBSurface"/> starts updating.
/// </summary>
public event UpdatingEventHandler Updating;
/// <summary>
/// Occurs when the <see cref="RGBSurface"/> update is done.
/// </summary>
public event UpdatedEventHandler Updated;
/// <summary>
/// Occurs when the layout of this <see cref="RGBSurface"/> changed.
/// </summary>
public event SurfaceLayoutChangedEventHandler SurfaceLayoutChanged;
// ReSharper restore EventNeverSubscribedTo.Global
#endregion
#region Methods
/// <summary>
/// Handles the needed event-calls for an exception.
/// </summary>
/// <param name="ex">The exception previously thrown.</param>
private void OnException(Exception ex)
{
try
{
Exception?.Invoke(new ExceptionEventArgs(ex));
}
catch { /* Well ... that's not my fault */ }
}
/// <summary>
/// Handles the needed event-calls before updating.
/// </summary>
private void OnUpdating(IUpdateTrigger trigger, CustomUpdateData customData)
{
try
{
double deltaTime = _deltaTimeCounter.Elapsed.TotalSeconds;
_deltaTimeCounter.Restart();
Updating?.Invoke(new UpdatingEventArgs(deltaTime, trigger, customData));
}
catch { /* Well ... that's not my fault */ }
}
/// <summary>
/// Handles the needed event-calls after an update.
/// </summary>
private void OnUpdated()
{
try
{
Updated?.Invoke(new UpdatedEventArgs());
}
catch { /* Well ... that's not my fault */ }
}
#endregion
}
}

View File

@ -1,83 +0,0 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace RGB.NET.Core
{
public partial class RGBSurface
{
#region Methods
// ReSharper disable UnusedMember.Global
/// <summary>
/// Loads all devices the given by the <see cref="IRGBDeviceProvider"/> provided by the give <see cref="IRGBDeviceProviderLoader"/>.
/// </summary>
/// <param name="deviceProviderLoader">The <see cref="IRGBDeviceProviderLoader"/> which provides the <see cref="IRGBDeviceProvider"/> to load the devices from.</param>
/// <param name="loadFilter">Specifies which types of devices to load.</param>
/// <param name="exclusiveAccessIfPossible">Specifies whether the application should request exclusive access of possible or not.</param>
/// <param name="throwExceptions">Specifies whether exception during the initialization sequence should be thrown or not.</param>
public void LoadDevices(IRGBDeviceProviderLoader deviceProviderLoader, RGBDeviceType loadFilter = RGBDeviceType.All,
bool exclusiveAccessIfPossible = false, bool throwExceptions = false)
=> LoadDevices(deviceProviderLoader.GetDeviceProvider(), loadFilter, exclusiveAccessIfPossible, throwExceptions);
/// <summary>
/// Loads all devices the given <see cref="IRGBDeviceProvider"/> is able to provide.
/// </summary>
/// <param name="deviceProvider">The <see cref="IRGBDeviceProvider"/> to load the devices from.</param>
/// <param name="loadFilter">Specifies which types of devices to load.</param>
/// <param name="exclusiveAccessIfPossible">Specifies whether the application should request exclusive access of possible or not.</param>
/// <param name="throwExceptions">Specifies whether exception during the initialization sequence should be thrown or not.</param>
public void LoadDevices(IRGBDeviceProvider deviceProvider, RGBDeviceType loadFilter = RGBDeviceType.All, bool exclusiveAccessIfPossible = false, bool throwExceptions = false)
{
lock (_deviceProvider)
{
if (_deviceProvider.Contains(deviceProvider) || _deviceProvider.Any(x => x.GetType() == deviceProvider.GetType())) return;
List<IRGBDevice> addedDevices = new List<IRGBDevice>();
if (deviceProvider.IsInitialized || deviceProvider.Initialize(loadFilter, exclusiveAccessIfPossible, throwExceptions))
{
_deviceProvider.Add(deviceProvider);
lock (_devices)
foreach (IRGBDevice device in deviceProvider.Devices)
{
if (_devices.Contains(device)) continue;
addedDevices.Add(device);
device.PropertyChanged += DeviceOnPropertyChanged;
_devices.Add(device);
}
}
if (addedDevices.Any())
{
UpdateSurfaceRectangle();
SurfaceLayoutChanged?.Invoke(new SurfaceLayoutChangedEventArgs(addedDevices, true, false));
}
}
}
/// <summary>
/// Automatically aligns all devices to prevent overlaps.
/// </summary>
public void AlignDevices()
{
double posX = 0;
foreach (IRGBDevice device in Devices)
{
device.Location += new Point(posX, 0);
posX += device.ActualSize.Width + 1;
}
}
// ReSharper restore UnusedMember.Global
private void DeviceOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
UpdateSurfaceRectangle();
SurfaceLayoutChanged?.Invoke(new SurfaceLayoutChangedEventArgs(new[] { sender as IRGBDevice }, false, true));
}
#endregion
}
}

View File

@ -10,9 +10,9 @@ namespace RGB.NET.Core
#region Events
/// <inheritdoc />
public event EventHandler<CustomUpdateData> Starting;
public event EventHandler<CustomUpdateData>? Starting;
/// <inheritdoc />
public event EventHandler<CustomUpdateData> Update;
public event EventHandler<CustomUpdateData>? Update;
#endregion
@ -22,13 +22,13 @@ namespace RGB.NET.Core
/// Invokes the <see cref="Starting"/>-event.
/// </summary>
/// <param name="updateData">Optional custom-data passed to the subscribers of the <see cref="Starting"/>.event.</param>
protected virtual void OnStartup(CustomUpdateData updateData = null) => Starting?.Invoke(this, updateData);
protected virtual void OnStartup(CustomUpdateData? updateData = null) => Starting?.Invoke(this, updateData ?? new CustomUpdateData());
/// <summary>
/// Invokes the <see cref="Update"/>-event.
/// </summary>
/// <param name="updateData">Optional custom-data passed to the subscribers of the <see cref="Update"/>.event.</param>
protected virtual void OnUpdate(CustomUpdateData updateData = null) => Update?.Invoke(this, updateData);
protected virtual void OnUpdate(CustomUpdateData? updateData = null) => Update?.Invoke(this, updateData ?? new CustomUpdateData());
/// <inheritdoc />
public abstract void Dispose();

View File

@ -9,7 +9,7 @@ namespace RGB.NET.Core
{
#region Properties & Fields
private Dictionary<string, object> _data = new Dictionary<string, object>();
private Dictionary<string, object?> _data = new();
#endregion
@ -20,10 +20,10 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="key">The key of the value.</param>
/// <returns>The value represented by the given key.</returns>
public object this[string key]
public object? this[string key]
{
get => _data.TryGetValue(key?.ToUpperInvariant() ?? string.Empty, out object data) ? data : default;
set => _data[key?.ToUpperInvariant() ?? string.Empty] = value;
get => _data.TryGetValue(key.ToUpperInvariant(), out object? data) ? data : default;
set => _data[key.ToUpperInvariant()] = value;
}
#endregion

View File

@ -53,12 +53,12 @@ namespace RGB.NET.Core
}
}
protected AutoResetEvent HasDataEvent = new AutoResetEvent(false);
protected AutoResetEvent HasDataEvent { get; set; } = new(false);
protected bool IsRunning;
protected Task UpdateTask;
protected CancellationTokenSource UpdateTokenSource;
protected CancellationToken UpdateToken;
protected bool IsRunning { get; set; }
protected Task? UpdateTask { get; set; }
protected CancellationTokenSource? UpdateTokenSource { get; set; }
protected CancellationToken UpdateToken { get; set; }
#endregion
@ -106,15 +106,18 @@ namespace RGB.NET.Core
IsRunning = false;
UpdateTokenSource.Cancel();
await UpdateTask;
UpdateTask.Dispose();
UpdateTokenSource?.Cancel();
if (UpdateTask != null)
await UpdateTask;
UpdateTask?.Dispose();
UpdateTask = null;
}
protected virtual void UpdateLoop()
{
OnStartup();
while (!UpdateToken.IsCancellationRequested)
{
if (HasDataEvent.WaitOne(Timeout))

View File

@ -10,12 +10,13 @@ namespace RGB.NET.Core
/// <typeparam name="TIdentifier">The type of the key used to identify some data.</typeparam>
/// <typeparam name="TData">The type of the data.</typeparam>
public abstract class UpdateQueue<TIdentifier, TData> : IDisposable
where TIdentifier : notnull
{
#region Properties & Fields
private readonly object _dataLock = new object();
private readonly object _dataLock = new();
private readonly IDeviceUpdateTrigger _updateTrigger;
private Dictionary<TIdentifier, TData> _currentDataSet;
private Dictionary<TIdentifier, TData>? _currentDataSet;
#endregion
@ -42,16 +43,18 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="sender">The <see cref="IUpdateTrigger"/> causing this update.</param>
/// <param name="customData"><see cref="CustomUpdateData"/> provided by the trigger.</param>
protected virtual void OnUpdate(object sender, CustomUpdateData customData)
protected virtual void OnUpdate(object? sender, CustomUpdateData customData)
{
Dictionary<TIdentifier, TData> dataSet;
lock (_dataLock)
{
if (_currentDataSet == null) return;
dataSet = _currentDataSet;
_currentDataSet = null;
}
if ((dataSet != null) && (dataSet.Count != 0))
if (dataSet.Count != 0)
Update(dataSet);
}
@ -60,7 +63,7 @@ namespace RGB.NET.Core
/// </summary>
/// <param name="sender">The starting <see cref="IUpdateTrigger"/>.</param>
/// <param name="customData"><see cref="CustomUpdateData"/> provided by the trigger.</param>
protected virtual void OnStartup(object sender, CustomUpdateData customData) { }
protected virtual void OnStartup(object? sender, CustomUpdateData customData) { }
/// <summary>
/// Performs the update this queue is responsible for.
@ -75,7 +78,7 @@ namespace RGB.NET.Core
// ReSharper disable once MemberCanBeProtected.Global
public virtual void SetData(Dictionary<TIdentifier, TData> dataSet)
{
if ((dataSet == null) || (dataSet.Count == 0)) return;
if (dataSet.Count == 0) return;
lock (_dataLock)
{
@ -83,8 +86,8 @@ namespace RGB.NET.Core
_currentDataSet = dataSet;
else
{
foreach (KeyValuePair<TIdentifier, TData> command in dataSet)
_currentDataSet[command.Key] = command.Value;
foreach ((TIdentifier key, TData value) in dataSet)
_currentDataSet[key] = value;
}
}
@ -132,7 +135,7 @@ namespace RGB.NET.Core
/// Calls <see cref="UpdateQueue{TIdentifier,TData}.SetData"/> for a data set created out of the provided list of <see cref="Led"/>.
/// </summary>
/// <param name="leds"></param>
public void SetData(IEnumerable<Led> leds) => SetData(leds?.ToDictionary(x => x.CustomData ?? x.Id, x => x.Color));
public void SetData(IEnumerable<Led> leds) => SetData(leds.ToDictionary(x => x.CustomData ?? x.Id, x => x.Color));
#endregion
}

View File

@ -10,11 +10,11 @@ namespace RGB.NET.Core
/// <summary>
/// Occurs when the trigger is starting up.
/// </summary>
event EventHandler<CustomUpdateData> Starting;
event EventHandler<CustomUpdateData>? Starting;
/// <summary>
/// Occurs when the trigger wants to cause an update.
/// </summary>
event EventHandler<CustomUpdateData> Update;
event EventHandler<CustomUpdateData>? Update;
}
}

View File

@ -14,12 +14,11 @@ namespace RGB.NET.Core
{
#region Properties & Fields
private object _lock = new object();
private object _lock = new();
private CancellationTokenSource _updateTokenSource;
private CancellationToken _updateToken;
private Task _updateTask;
private Stopwatch _sleepCounter;
protected Task? UpdateTask { get; set; }
protected CancellationTokenSource? UpdateTokenSource { get; set; }
protected CancellationToken UpdateToken { get; set; }
private double _updateFrequency = 1.0 / 30.0;
/// <summary>
@ -46,8 +45,6 @@ namespace RGB.NET.Core
/// <param name="autostart">A value indicating if the trigger should automatically <see cref="Start"/> right after construction.</param>
public TimerUpdateTrigger(bool autostart = true)
{
_sleepCounter = new Stopwatch();
if (autostart)
Start();
}
@ -63,11 +60,11 @@ namespace RGB.NET.Core
{
lock (_lock)
{
if (_updateTask == null)
if (UpdateTask == null)
{
_updateTokenSource?.Dispose();
_updateTokenSource = new CancellationTokenSource();
_updateTask = Task.Factory.StartNew(UpdateLoop, (_updateToken = _updateTokenSource.Token), TaskCreationOptions.LongRunning, TaskScheduler.Default);
UpdateTokenSource?.Dispose();
UpdateTokenSource = new CancellationTokenSource();
UpdateTask = Task.Factory.StartNew(UpdateLoop, (UpdateToken = UpdateTokenSource.Token), TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
}
}
@ -79,30 +76,35 @@ namespace RGB.NET.Core
{
lock (_lock)
{
if (_updateTask != null)
if (UpdateTask != null)
{
_updateTokenSource.Cancel();
UpdateTokenSource?.Cancel();
// ReSharper disable once MethodSupportsCancellation
_updateTask.Wait();
_updateTask.Dispose();
_updateTask = null;
UpdateTask.Wait();
UpdateTask.Dispose();
UpdateTask = null;
}
}
}
private void UpdateLoop()
{
while (!_updateToken.IsCancellationRequested)
OnStartup();
while (!UpdateToken.IsCancellationRequested)
{
_sleepCounter.Restart();
long preUpdateTicks = Stopwatch.GetTimestamp();
OnUpdate();
_sleepCounter.Stop();
LastUpdateTime = _sleepCounter.Elapsed.TotalSeconds;
int sleep = (int)((UpdateFrequency * 1000.0) - _sleepCounter.ElapsedMilliseconds);
if (sleep > 0)
Thread.Sleep(sleep);
if (UpdateFrequency > 0)
{
double lastUpdateTime = ((Stopwatch.GetTimestamp() - preUpdateTicks) / 10000.0);
LastUpdateTime = lastUpdateTime;
int sleep = (int)((UpdateFrequency * 1000.0) - lastUpdateTime);
if (sleep > 0)
Thread.Sleep(sleep);
}
}
}

View File

@ -74,6 +74,14 @@ namespace RGB.NET.Decorators.Brush
#endregion
#region Constructors
public FlashDecorator(RGBSurface surface, bool updateIfDisabled = false)
: base(surface, updateIfDisabled)
{ }
#endregion
#region Methods
/// <inheritdoc />

View File

@ -45,7 +45,8 @@ namespace RGB.NET.Decorators.Gradient
/// <see cref="T:RGB.NET.Brushes.Gradients.RainbowGradient" />: 1 unit = 1 degree.</param>
/// <param name="direction">The direction the <see cref="T:RGB.NET.Brushes.Gradients.IGradient" /> is moved.
/// True leads to an offset-increment (normaly moving to the right), false to an offset-decrement (normaly moving to the left).</param>
public MoveGradientDecorator(double speed = 180.0, bool direction = true)
public MoveGradientDecorator(RGBSurface surface, double speed = 180.0, bool direction = true)
: base(surface)
{
this.Speed = speed;
this.Direction = direction;

View File

@ -4,7 +4,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using AuraServiceLib;
using RGB.NET.Core;
@ -18,7 +18,7 @@ namespace RGB.NET.Devices.Asus
{
#region Properties & Fields
private static AsusDeviceProvider _instance;
private static AsusDeviceProvider? _instance;
/// <summary>
/// Gets the singleton <see cref="AsusDeviceProvider"/> instance.
/// </summary>
@ -31,26 +31,14 @@ namespace RGB.NET.Devices.Asus
public bool IsInitialized { get; private set; }
/// <inheritdoc />
/// <summary>
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess { get; private set; }
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary>
/// Gets or sets a function to get the culture for a specific device.
/// </summary>
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
public Func<CultureInfo> GetCulture { get; set; } = CultureHelper.GetCurrentCulture;
public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for asus devices.
/// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; }
public DeviceUpdateTrigger UpdateTrigger { get; }
private IAuraSdk2 _sdk;
private IAuraSdk2? _sdk;
#endregion
@ -69,17 +57,17 @@ namespace RGB.NET.Devices.Asus
}
#endregion
#region Methods
/// <inheritdoc />
public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool exclusiveAccessIfPossible = false, bool throwExceptions = false)
public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool throwExceptions = false)
{
IsInitialized = false;
try
{
UpdateTrigger?.Stop();
UpdateTrigger.Stop();
// ReSharper disable once SuspiciousTypeConversion.Global
_sdk = (IAuraSdk2)new AuraSdk();
@ -116,7 +104,7 @@ namespace RGB.NET.Devices.Asus
case AsusDeviceType.KEYBOARD_RGB:
case AsusDeviceType.NB_KB_RGB:
case AsusDeviceType.NB_KB_4ZONE_RGB:
rgbDevice = new AsusKeyboardRGBDevice(new AsusKeyboardRGBDeviceInfo(device, CultureInfo.CurrentCulture));
rgbDevice = new AsusKeyboardRGBDevice(new AsusKeyboardRGBDeviceInfo(device, AsusPhysicalKeyboardLayout.Default));
break;
case AsusDeviceType.MOUSE_RGB:
@ -141,7 +129,7 @@ namespace RGB.NET.Devices.Asus
}
}
UpdateTrigger?.Start();
UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true;
@ -155,19 +143,17 @@ namespace RGB.NET.Devices.Asus
return true;
}
/// <inheritdoc />
public void ResetDevices()
{
_sdk?.ReleaseControl(0);
_sdk?.SwitchMode();
}
/// <inheritdoc />
public void Dispose()
{
try { UpdateTrigger?.Dispose(); }
try { UpdateTrigger.Dispose(); }
catch { /* at least we tried */ }
foreach (IRGBDevice device in Devices)
try { device.Dispose(); }
catch { /* at least we tried */ }
Devices = Enumerable.Empty<IRGBDevice>();
try { _sdk?.ReleaseControl(0); }
catch { /* at least we tried */ }

View File

@ -1,24 +0,0 @@
using RGB.NET.Core;
namespace RGB.NET.Devices.Asus
{
/// <summary>
/// Represents a device provider loaded used to dynamically load asus devices into an application.
/// </summary>
public class AsusDeviceProviderLoader : IRGBDeviceProviderLoader
{
#region Properties & Fields
/// <inheritdoc />
public bool RequiresInitialization => false;
#endregion
#region Methods
/// <inheritdoc />
public IRGBDeviceProvider GetDeviceProvider() => AsusDeviceProvider.Instance;
#endregion
}
}

View File

@ -26,18 +26,13 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc />
protected override void InitializeLayout()
{
//TODO DarthAffe 07.10.2017: Look for a good default layout
int ledCount = DeviceInfo.Device.Lights.Count;
for (int i = 0; i < ledCount; i++)
InitializeLed(LedId.DRAM1 + i, new Rectangle(i * 10, 0, 10, 10));
//TODO DarthAffe 21.10.2017: We don't know the model, how to save layouts and images?
//TODO DarthAffe 07.10.2017: We don't know the model, how to save layouts and images?
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Asus\Drams", $"{DeviceInfo.Model.Replace(" ", string.Empty).ToUpper()}.xml"), null);
AddLed(LedId.DRAM1 + i, new Point(i * 10, 0), new Size(10, 10));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => (int)ledId - (int)LedId.DRAM1;
protected override object? GetLedCustomData(LedId ledId) => (int)ledId - (int)LedId.DRAM1;
#endregion
}

View File

@ -1,15 +0,0 @@
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace RGB.NET.Devices.Asus
{
/// <summary>
/// Contains list of available logical layouts for asus keyboards.
/// </summary>
public enum AsusLogicalKeyboardLayout
{
TODO
};
}

View File

@ -10,6 +10,6 @@ namespace RGB.NET.Devices.Asus
/// </summary>
public enum AsusPhysicalKeyboardLayout
{
TODO
Default
}
}

View File

@ -24,7 +24,7 @@ namespace RGB.NET.Devices.Asus
/// Gets or sets the update queue performing updates for this device.
/// </summary>
// ReSharper disable once MemberCanBePrivate.Global
protected AsusUpdateQueue UpdateQueue { get; set; }
protected AsusUpdateQueue? UpdateQueue { get; set; }
#endregion
@ -52,7 +52,7 @@ namespace RGB.NET.Devices.Asus
if (Size == Size.Invalid)
{
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
}
@ -66,8 +66,8 @@ namespace RGB.NET.Devices.Asus
protected abstract void InitializeLayout();
/// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <inheritdoc />
public override void Dispose()
{

View File

@ -1,5 +1,4 @@
using System;
using AuraServiceLib;
using AuraServiceLib;
using RGB.NET.Core;
namespace RGB.NET.Devices.Asus
@ -24,12 +23,8 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc />
public string Model { get; }
/// <inheritdoc />
public Uri Image { get; set; }
public object? LayoutMetadata { get; set; }
/// <inheritdoc />
public RGBDeviceLighting Lighting => RGBDeviceLighting.Key;
public IAuraSyncDevice Device { get; }
#endregion
@ -43,7 +38,7 @@ namespace RGB.NET.Devices.Asus
/// <param name="device">The <see cref="IAuraSyncDevice"/> backing this RGB.NET device.</param>
/// <param name="manufacturer">The manufacturer-name of the <see cref="IRGBDevice"/>.</param>
/// <param name="model">The model-name of the <see cref="IRGBDevice"/>.</param>
internal AsusRGBDeviceInfo(RGBDeviceType deviceType, IAuraSyncDevice device, string model = null, string manufacturer = "Asus")
internal AsusRGBDeviceInfo(RGBDeviceType deviceType, IAuraSyncDevice device, string? model = null, string manufacturer = "Asus")
{
this.DeviceType = deviceType;
this.Device = device;

View File

@ -36,14 +36,11 @@ namespace RGB.NET.Devices.Asus
{
int ledCount = DeviceInfo.Device.Lights.Count;
for (int i = 0; i < ledCount; i++)
InitializeLed(_baseLedId + i, new Rectangle(i * 10, 0, 10, 10));
//TODO DarthAffe 19.05.2019: Add a way to define a layout for this kind of devies
AddLed(_baseLedId + i, new Point(i * 10, 0), new Size(10, 10));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => (int)ledId - (int)_baseLedId;
protected override object? GetLedCustomData(LedId ledId) => (int)ledId - (int)_baseLedId;
#endregion
}
}

View File

@ -15,7 +15,7 @@ namespace RGB.NET.Devices.Asus
/// <summary>
/// The device to be updated.
/// </summary>
protected IAuraSyncDevice Device { get; private set; }
protected IAuraSyncDevice? Device { get; private set; }
#endregion
@ -45,15 +45,16 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc />
protected override void Update(Dictionary<object, Color> dataSet)
{
if (Device == null) return;
try
{
if ((Device.Type == (uint)AsusDeviceType.KEYBOARD_RGB) || (Device.Type == (uint)AsusDeviceType.NB_KB_RGB))
{
foreach (KeyValuePair<object, Color> data in dataSet)
foreach ((object key, Color value) in dataSet)
{
AsusLedId index = (AsusLedId)data.Key;
IAuraSyncKeyboard keyboard = (IAuraSyncKeyboard)Device;
if (keyboard != null)
AsusLedId index = (AsusLedId)key;
if (Device is IAuraSyncKeyboard keyboard)
{
IAuraRgbLight light = index switch
{
@ -72,7 +73,7 @@ namespace RGB.NET.Devices.Asus
_ => light
};
(_, byte r, byte g, byte b) = data.Value.GetRGBBytes();
(_, byte r, byte g, byte b) = value.GetRGBBytes();
light.Red = r;
light.Green = g;
light.Blue = b;
@ -81,12 +82,12 @@ namespace RGB.NET.Devices.Asus
}
else
{
foreach (KeyValuePair<object, Color> data in dataSet)
foreach ((object key, Color value) in dataSet)
{
int index = (int)data.Key;
int index = (int)key;
IAuraRgbLight light = Device.Lights[index];
(_, byte r, byte g, byte b) = data.Value.GetRGBBytes();
(_, byte r, byte g, byte b) = value.GetRGBBytes();
light.Red = r;
light.Green = g;
light.Blue = b;

View File

@ -26,17 +26,13 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc />
protected override void InitializeLayout()
{
//TODO DarthAffe 07.10.2017: Look for a good default layout
int ledCount = DeviceInfo.Device.Lights.Count;
for (int i = 0; i < ledCount; i++)
InitializeLed(LedId.GraphicsCard1 + i, new Rectangle(i * 10, 0, 10, 10));
//TODO DarthAffe 07.10.2017: We don't know the model, how to save layouts and images?
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Asus\GraphicsCards", $"{DeviceInfo.Model.Replace(" ", string.Empty).ToUpper()}.xml"), null);
AddLed(LedId.GraphicsCard1 + i, new Point(i * 10, 0), new Size(10, 10));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => (int)ledId - (int)LedId.GraphicsCard1;
protected override object? GetLedCustomData(LedId ledId) => (int)ledId - (int)LedId.GraphicsCard1;
#endregion
}

View File

@ -26,17 +26,13 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc />
protected override void InitializeLayout()
{
//TODO DarthAffe 07.10.2017: Look for a good default layout
int ledCount = DeviceInfo.Device.Lights.Count;
for (int i = 0; i < ledCount; i++)
InitializeLed(LedId.Headset1 + i, new Rectangle(i * 40, 0, 40, 8));
//TODO DarthAffe 07.10.2017: We don't know the model, how to save layouts and images?
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Asus\Headsets", $"{DeviceInfo.Model.Replace(" ", string.Empty).ToUpper()}.xml"), null);
AddLed(LedId.Headset1 + i, new Point(i * 40, 0), new Size(40, 8));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => (int)ledId - (int)LedId.Headset1;
protected override object? GetLedCustomData(LedId ledId) => (int)ledId - (int)LedId.Headset1;
#endregion
}

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Asus
{
internal static class AsusKeyboardLedMapping
{
public static readonly Dictionary<LedId, AsusLedId> MAPPING = new Dictionary<LedId, AsusLedId>
{
public static readonly Dictionary<LedId, AsusLedId> MAPPING = new()
{
{ LedId.Keyboard_Escape, AsusLedId.KEY_ESCAPE },
{ LedId.Keyboard_F1, AsusLedId.KEY_F1 },
{ LedId.Keyboard_F2, AsusLedId.KEY_F2 },

View File

@ -35,26 +35,23 @@ namespace RGB.NET.Devices.Asus
{
int pos = 0;
foreach (IAuraRgbKey key in ((IAuraSyncKeyboard)DeviceInfo.Device).Keys)
InitializeLed(reversedMapping[(AsusLedId)key.Code], new Point(pos++ * 19, 0), new Size(19, 19));
AddLed(reversedMapping[(AsusLedId)key.Code], new Point(pos++ * 19, 0), new Size(19, 19));
//UK Layout
InitializeLed(reversedMapping[AsusLedId.KEY_OEM_102], new Point(pos++ * 19, 0), new Size(19, 19));
AddLed(reversedMapping[AsusLedId.KEY_OEM_102], new Point(pos++ * 19, 0), new Size(19, 19));
InitializeLed(reversedMapping[AsusLedId.UNDOCUMENTED_1], new Point(pos * 19, 0), new Size(19, 19));
AddLed(reversedMapping[AsusLedId.UNDOCUMENTED_1], new Point(pos * 19, 0), new Size(19, 19));
}
else
{
int ledCount = DeviceInfo.Device.Lights.Count;
for (int i = 0; i < ledCount; i++)
InitializeLed(LedId.Keyboard_Custom1 + i, new Point(i * 19, 0), new Size(19, 19));
AddLed(LedId.Keyboard_Custom1 + i, new Point(i * 19, 0), new Size(19, 19));
}
string model = DeviceInfo.Model.Replace(" ", string.Empty).ToUpper();
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, $@"Layouts\Asus\Keyboards\{model}", $"{DeviceInfo.PhysicalLayout.ToString().ToUpper()}.xml"), DeviceInfo.LogicalLayout.ToString());
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId)
protected override object? GetLedCustomData(LedId ledId)
{
if (DeviceInfo.Device.Type == (uint)AsusDeviceType.NB_KB_4ZONE_RGB)
return ledId - LedId.Keyboard_Custom1;

View File

@ -1,5 +1,4 @@
using System.Globalization;
using AuraServiceLib;
using AuraServiceLib;
using RGB.NET.Core;
namespace RGB.NET.Devices.Asus
@ -15,12 +14,7 @@ namespace RGB.NET.Devices.Asus
/// <summary>
/// Gets the physical layout of the keyboard.
/// </summary>
public AsusPhysicalKeyboardLayout PhysicalLayout { get; private set; }
/// <summary>
/// Gets the logical layout of the keyboard.
/// </summary>
public AsusLogicalKeyboardLayout LogicalLayout { get; private set; }
public AsusPhysicalKeyboardLayout PhysicalLayout { get; }
#endregion
@ -31,27 +25,10 @@ namespace RGB.NET.Devices.Asus
/// Internal constructor of managed <see cref="T:RGB.NET.Devices.Asus.AsusKeyboardRGBDeviceInfo" />.
/// </summary>
/// <param name="device">The <see cref="IAuraSyncDevice"/> backing this RGB.NET device.</param>
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> of the layout this keyboard is using.</param>
internal AsusKeyboardRGBDeviceInfo(IAuraSyncDevice device, CultureInfo culture)
internal AsusKeyboardRGBDeviceInfo(IAuraSyncDevice device, AsusPhysicalKeyboardLayout layout)
: base(RGBDeviceType.Keyboard, device, device.Name)
{
SetLayouts(culture.KeyboardLayoutId);
}
#endregion
#region Methods
private void SetLayouts(int keyboardLayoutId)
{
switch (keyboardLayoutId)
{
//TODO DarthAffe 07.10.2017: Implement
default:
PhysicalLayout = AsusPhysicalKeyboardLayout.TODO;
LogicalLayout = AsusLogicalKeyboardLayout.TODO;
break;
}
this.PhysicalLayout = layout;
}
#endregion

View File

@ -26,18 +26,14 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc />
protected override void InitializeLayout()
{
//TODO DarthAffe 07.10.2017: Look for a good default layout
int ledCount = DeviceInfo.Device.Lights.Count;
for (int i = 0; i < ledCount; i++)
InitializeLed(LedId.Mainboard1 + i, new Rectangle(i * 40, 0, 40, 8));
//TODO DarthAffe 07.10.2017: We don't know the model, how to save layouts and images?
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Asus\Mainboards", $"{DeviceInfo.Model.Replace(" ", string.Empty).ToUpper()}.xml"), null);
AddLed(LedId.Mainboard1 + i, new Point(i * 40, 0), new Size(40, 8));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => (int)ledId - (int)LedId.Mainboard1;
protected override object? GetLedCustomData(LedId ledId) => (int)ledId - (int)LedId.Mainboard1;
#endregion
}
}

View File

@ -26,16 +26,13 @@ namespace RGB.NET.Devices.Asus
/// <inheritdoc />
protected override void InitializeLayout()
{
//TODO DarthAffe 07.10.2017: Look for a good default layout
int ledCount = DeviceInfo.Device.Lights.Count;
for (int i = 0; i < ledCount; i++)
InitializeLed(LedId.Mouse1 + i, new Rectangle(i * 10, 0, 10, 10));
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Asus\Mouses", $"{DeviceInfo.Model.Replace(" ", string.Empty).ToUpper()}.xml"), null);
AddLed(LedId.Mouse1 + i, new Point(i * 10, 0), new Size(10, 10));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => (int)ledId - (int)LedId.Mouse1;
protected override object? GetLedCustomData(LedId ledId) => (int)ledId - (int)LedId.Mouse1;
#endregion
}

View File

@ -4,7 +4,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using RGB.NET.Core;
using RGB.NET.Devices.CoolerMaster.Helper;
using RGB.NET.Devices.CoolerMaster.Native;
@ -19,7 +19,7 @@ namespace RGB.NET.Devices.CoolerMaster
{
#region Properties & Fields
private static CoolerMasterDeviceProvider _instance;
private static CoolerMasterDeviceProvider? _instance;
/// <summary>
/// Gets the singleton <see cref="CoolerMasterDeviceProvider"/> instance.
/// </summary>
@ -29,13 +29,13 @@ namespace RGB.NET.Devices.CoolerMaster
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used.
/// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { "x86/CMSDK.dll" };
public static List<string> PossibleX86NativePaths { get; } = new() { "x86/CMSDK.dll" };
/// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used.
/// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { "x64/CMSDK.dll" };
public static List<string> PossibleX64NativePaths { get; } = new() { "x64/CMSDK.dll" };
/// <inheritdoc />
/// <summary>
@ -43,30 +43,13 @@ namespace RGB.NET.Devices.CoolerMaster
/// </summary>
public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _CoolerMasterSDK.LoadedArchitecture;
/// <inheritdoc />
/// <summary>
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess { get; private set; }
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
/// <summary>
/// Gets or sets a function to get the culture for a specific device.
/// </summary>
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
public Func<CultureInfo> GetCulture { get; set; } = CultureHelper.GetCurrentCulture;
public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for cooler master devices.
/// </summary>
public DeviceUpdateTrigger UpdateTrigger { get; private set; }
public DeviceUpdateTrigger UpdateTrigger { get; }
#endregion
@ -89,13 +72,13 @@ namespace RGB.NET.Devices.CoolerMaster
#region Methods
/// <inheritdoc />
public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool exclusiveAccessIfPossible = false, bool throwExceptions = false)
public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool throwExceptions = false)
{
IsInitialized = false;
try
{
UpdateTrigger?.Stop();
UpdateTrigger.Stop();
_CoolerMasterSDK.Reload();
if (_CoolerMasterSDK.GetSDKVersion() <= 0) return false;
@ -118,7 +101,7 @@ namespace RGB.NET.Devices.CoolerMaster
{
case RGBDeviceType.Keyboard:
CoolerMasterPhysicalKeyboardLayout physicalLayout = _CoolerMasterSDK.GetDeviceLayout(index);
device = new CoolerMasterKeyboardRGBDevice(new CoolerMasterKeyboardRGBDeviceInfo(index, physicalLayout, GetCulture()));
device = new CoolerMasterKeyboardRGBDevice(new CoolerMasterKeyboardRGBDeviceInfo(index, physicalLayout));
break;
case RGBDeviceType.Mouse:
@ -142,7 +125,7 @@ namespace RGB.NET.Devices.CoolerMaster
catch { if (throwExceptions) throw; }
}
UpdateTrigger?.Start();
UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true;
@ -157,38 +140,16 @@ namespace RGB.NET.Devices.CoolerMaster
return true;
}
/// <inheritdoc />
public void ResetDevices()
{
if (IsInitialized)
foreach (IRGBDevice device in Devices)
{
try
{
CoolerMasterRGBDeviceInfo deviceInfo = (CoolerMasterRGBDeviceInfo)device.DeviceInfo;
_CoolerMasterSDK.EnableLedControl(false, deviceInfo.DeviceIndex);
_CoolerMasterSDK.EnableLedControl(true, deviceInfo.DeviceIndex);
}
catch {/* shit happens */}
}
}
/// <inheritdoc />
public void Dispose()
{
try { UpdateTrigger?.Dispose(); }
try { UpdateTrigger.Dispose(); }
catch { /* at least we tried */ }
if (IsInitialized)
foreach (IRGBDevice device in Devices)
{
try
{
CoolerMasterRGBDeviceInfo deviceInfo = (CoolerMasterRGBDeviceInfo)device.DeviceInfo;
_CoolerMasterSDK.EnableLedControl(false, deviceInfo.DeviceIndex);
}
catch {/* shit happens */}
}
foreach (IRGBDevice device in Devices)
try { device.Dispose(); }
catch { /* at least we tried */ }
Devices = Enumerable.Empty<IRGBDevice>();
// DarthAffe 03.03.2020: Should be done but isn't possible due to an weird winodws-hook inside the sdk which corrupts the stack when unloading the dll
//try { _CoolerMasterSDK.UnloadCMSDK(); }

View File

@ -1,24 +0,0 @@
using RGB.NET.Core;
namespace RGB.NET.Devices.CoolerMaster
{
/// <summary>
/// Represents a device provider loaded used to dynamically load cooler-master devices into an application.
/// </summary>
public class CoolerMasterDeviceProviderLoader : IRGBDeviceProviderLoader
{
#region Properties & Fields
/// <inheritdoc />
public bool RequiresInitialization => false;
#endregion
#region Methods
/// <inheritdoc />
public IRGBDeviceProvider GetDeviceProvider() => CoolerMasterDeviceProvider.Instance;
#endregion
}
}

View File

@ -1,15 +0,0 @@
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace RGB.NET.Devices.CoolerMaster
{
/// <summary>
/// Contains list of available logical layouts for cooler master keyboards.
/// </summary>
public enum CoolerMasterLogicalKeyboardLayout
{
DE
};
}

View File

@ -26,7 +26,7 @@ namespace RGB.NET.Devices.CoolerMaster
/// Gets or sets the update queue performing updates for this device.
/// </summary>
// ReSharper disable once MemberCanBePrivate.Global
protected CoolerMasterUpdateQueue UpdateQueue { get; set; }
protected CoolerMasterUpdateQueue? UpdateQueue { get; set; }
#endregion
@ -55,7 +55,7 @@ namespace RGB.NET.Devices.CoolerMaster
if (Size == Size.Invalid)
{
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
}
@ -68,7 +68,7 @@ namespace RGB.NET.Devices.CoolerMaster
protected abstract void InitializeLayout();
/// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate) => UpdateQueue?.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
/// <inheritdoc cref="IDisposable.Dispose" />
/// <inheritdoc cref="AbstractRGBDevice{TDeviceInfo}.Dispose" />

View File

@ -1,5 +1,4 @@
using System;
using RGB.NET.Core;
using RGB.NET.Core;
using RGB.NET.Devices.CoolerMaster.Helper;
namespace RGB.NET.Devices.CoolerMaster
@ -24,12 +23,8 @@ namespace RGB.NET.Devices.CoolerMaster
/// <inheritdoc />
public string Model { get; }
/// <inheritdoc />
public Uri Image { get; set; }
public object? LayoutMetadata { get; set; }
/// <inheritdoc />
public RGBDeviceLighting Lighting => RGBDeviceLighting.Key;
/// <summary>
/// Gets the <see cref="CoolerMasterDevicesIndexes"/> of the <see cref="CoolerMasterRGBDevice{TDeviceInfo}"/>.
/// </summary>
@ -49,7 +44,7 @@ namespace RGB.NET.Devices.CoolerMaster
this.DeviceType = deviceType;
this.DeviceIndex = deviceIndex;
Model = deviceIndex.GetDescription();
Model = deviceIndex.GetDescription() ?? "Unknown";
DeviceName = $"{Manufacturer} {Model}";
}

View File

@ -14,38 +14,29 @@ namespace RGB.NET.Devices.CoolerMaster.Helper
/// Gets the value of the <see cref="DescriptionAttribute"/>.
/// </summary>
/// <param name="source">The enum value to get the description from.</param>
/// <typeparam name="T">The generic enum-type</typeparam>
/// <returns>The value of the <see cref="DescriptionAttribute"/> or the <see cref="Enum.ToString()" /> result of the source.</returns>
internal static string GetDescription<T>(this T source)
where T : struct
{
return source.GetAttribute<DescriptionAttribute, T>()?.Description ?? source.ToString();
}
internal static string? GetDescription(this Enum source)
=> source.GetAttribute<DescriptionAttribute>()?.Description ?? source.ToString();
/// <summary>
/// Gets the value of the <see cref="DeviceTypeAttribute"/>.
/// </summary>
/// <param name="source">The enum value to get the description from.</param>
/// <typeparam name="T">The generic enum-type</typeparam>
/// <returns>The value of the <see cref="DeviceTypeAttribute"/> or the <see cref="Enum.ToString()" /> result of the source.</returns>
internal static RGBDeviceType GetDeviceType<T>(this T source)
where T : struct
{
return source.GetAttribute<DeviceTypeAttribute, T>()?.DeviceType ?? RGBDeviceType.Unknown;
}
internal static RGBDeviceType GetDeviceType(this Enum source)
=> source.GetAttribute<DeviceTypeAttribute>()?.DeviceType ?? RGBDeviceType.Unknown;
/// <summary>
/// Gets the attribute of type T.
/// </summary>
/// <param name="source">The enum value to get the attribute from</param>
/// <typeparam name="T">The generic attribute type</typeparam>
/// <typeparam name="TEnum">The generic enum-type</typeparam>
/// <returns>The <see cref="Attribute"/>.</returns>
private static T GetAttribute<T, TEnum>(this TEnum source)
private static T? GetAttribute<T>(this Enum source)
where T : Attribute
where TEnum : struct
{
FieldInfo fi = source.GetType().GetField(source.ToString());
FieldInfo? fi = source.GetType().GetField(source.ToString());
if (fi == null) return null;
T[] attributes = (T[])fi.GetCustomAttributes(typeof(T), false);
return attributes.Length > 0 ? attributes[0] : null;
}

View File

@ -14,8 +14,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysL
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_US = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_US = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -131,8 +131,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,20) }
};
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_EU = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysL_EU = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -253,8 +253,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysM
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_US = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_US = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -354,8 +354,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,17) }
};
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_EU = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysM_EU = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -460,8 +460,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysS
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_US = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_US = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -556,8 +556,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_ArrowRight, (5,17) }
};
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_EU = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysS_EU = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -657,8 +657,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region MasterKeysMK750
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_US = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_US = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -801,8 +801,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_Custom22, (6,17) },
};
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_EU = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_EU = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -946,8 +946,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_Custom22, (6,17) }
};
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_JP = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> MasterKeysMK750_JP = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -1099,8 +1099,8 @@ namespace RGB.NET.Devices.CoolerMaster
#region CKxxx
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_US = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_US = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -1212,8 +1212,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,20) }
};
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_EU = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_EU = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -1326,8 +1326,8 @@ namespace RGB.NET.Devices.CoolerMaster
{ LedId.Keyboard_NumPeriodAndDelete, (5,20) }
};
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_JP = new Dictionary<LedId, (int row, int column)>
{
private static readonly Dictionary<LedId, (int row, int column)> CKxxx_JP = new()
{
{ LedId.Keyboard_Escape, (0,0) },
{ LedId.Keyboard_F1, (0,1) },
{ LedId.Keyboard_F2, (0,2) },
@ -1450,7 +1450,7 @@ namespace RGB.NET.Devices.CoolerMaster
/// Contains all the hardware-id mappings for CoolerMaster devices.
/// </summary>
public static readonly Dictionary<CoolerMasterDevicesIndexes, Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>> Mapping =
new Dictionary<CoolerMasterDevicesIndexes, Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>>
new()
{
{ CoolerMasterDevicesIndexes.MasterKeys_L, new Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>
{

View File

@ -27,22 +27,18 @@ namespace RGB.NET.Devices.CoolerMaster
/// <inheritdoc />
protected override void InitializeLayout()
{
if (!CoolerMasterKeyboardLedMappings.Mapping.TryGetValue(DeviceInfo.DeviceIndex, out Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>> deviceMappings))
if (!CoolerMasterKeyboardLedMappings.Mapping.TryGetValue(DeviceInfo.DeviceIndex, out Dictionary<CoolerMasterPhysicalKeyboardLayout, Dictionary<LedId, (int row, int column)>>? deviceMappings))
throw new RGBDeviceException($"Failed to find a CoolerMasterKeyboardLedMapping for device index {DeviceInfo.DeviceIndex}");
if (!deviceMappings.TryGetValue(DeviceInfo.PhysicalLayout, out Dictionary<LedId, (int row, int column)> mapping))
if (!deviceMappings.TryGetValue(DeviceInfo.PhysicalLayout, out Dictionary<LedId, (int row, int column)>? mapping))
throw new RGBDeviceException($"Failed to find a CoolerMasterKeyboardLedMapping for device index {DeviceInfo.DeviceIndex} with physical layout {DeviceInfo.PhysicalLayout}");
foreach (KeyValuePair<LedId, (int row, int column)> led in mapping)
InitializeLed(led.Key, new Rectangle(led.Value.column * 19, led.Value.row * 19, 19, 19));
string model = DeviceInfo.Model.Replace(" ", string.Empty).ToUpper();
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, $@"Layouts\CoolerMaster\Keyboards\{model}", $"{DeviceInfo.PhysicalLayout.ToString().ToUpper()}.xml"),
DeviceInfo.LogicalLayout.ToString());
foreach ((LedId ledId, (int row, int column)) in mapping)
AddLed(ledId, new Point(column * 19, row * 19), new Size(19, 19));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => CoolerMasterKeyboardLedMappings.Mapping[DeviceInfo.DeviceIndex][DeviceInfo.PhysicalLayout][ledId];
protected override object GetLedCustomData(LedId ledId) => CoolerMasterKeyboardLedMappings.Mapping[DeviceInfo.DeviceIndex][DeviceInfo.PhysicalLayout][ledId];
#endregion
}
}

View File

@ -1,5 +1,4 @@
using System.Globalization;
using RGB.NET.Core;
using RGB.NET.Core;
namespace RGB.NET.Devices.CoolerMaster
{
@ -16,11 +15,6 @@ namespace RGB.NET.Devices.CoolerMaster
/// </summary>
public CoolerMasterPhysicalKeyboardLayout PhysicalLayout { get; }
/// <summary>
/// Gets the <see cref="CoolerMasterLogicalKeyboardLayout"/> of the <see cref="CoolerMasterKeyboardRGBDevice"/>.
/// </summary>
public CoolerMasterLogicalKeyboardLayout LogicalLayout { get; private set; }
#endregion
#region Constructors
@ -31,24 +25,10 @@ namespace RGB.NET.Devices.CoolerMaster
/// </summary>
/// <param name="deviceIndex">The index of the <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterKeyboardRGBDevice" />.</param>
/// <param name="physicalKeyboardLayout">The <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterPhysicalKeyboardLayout" /> of the <see cref="T:RGB.NET.Devices.CoolerMaster.CoolerMasterKeyboardRGBDevice" />.</param>
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> of the layout this keyboard is using</param>
internal CoolerMasterKeyboardRGBDeviceInfo(CoolerMasterDevicesIndexes deviceIndex, CoolerMasterPhysicalKeyboardLayout physicalKeyboardLayout, CultureInfo culture)
internal CoolerMasterKeyboardRGBDeviceInfo(CoolerMasterDevicesIndexes deviceIndex, CoolerMasterPhysicalKeyboardLayout physicalKeyboardLayout)
: base(RGBDeviceType.Keyboard, deviceIndex)
{
this.PhysicalLayout = physicalKeyboardLayout;
SetLayouts(culture.KeyboardLayoutId);
}
private void SetLayouts(int keyboardLayoutId)
{
switch (keyboardLayoutId)
{
//TODO DarthAffe 02.04.2017: Check all available keyboards and there layout-ids
default:
LogicalLayout = CoolerMasterLogicalKeyboardLayout.DE;
break;
}
}
#endregion

View File

@ -15,7 +15,7 @@ namespace RGB.NET.Devices.CoolerMaster
/// </summary>
// ReSharper disable once InconsistentNaming
public static readonly Dictionary<CoolerMasterDevicesIndexes, Dictionary<LedId, (int row, int column)>> Mapping =
new Dictionary<CoolerMasterDevicesIndexes, Dictionary<LedId, (int row, int column)>>
new()
{
{ CoolerMasterDevicesIndexes.MasterMouse_L, new Dictionary<LedId, (int row, int column)>
{

View File

@ -30,15 +30,12 @@ namespace RGB.NET.Devices.CoolerMaster
Dictionary<LedId, (int row, int column)> mapping = CoolerMasterMouseLedMappings.Mapping[DeviceInfo.DeviceIndex];
foreach (KeyValuePair<LedId, (int row, int column)> led in mapping)
InitializeLed(led.Key, new Rectangle(led.Value.column * 19, led.Value.row * 19, 19, 19));
string model = DeviceInfo.Model.Replace(" ", string.Empty).ToUpper();
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\CoolerMaster\Mice", $"{model}.xml"), null);
AddLed(led.Key, new Point(led.Value.column * 19, led.Value.row * 19), new Size(19, 19));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => CoolerMasterMouseLedMappings.Mapping[DeviceInfo.DeviceIndex][ledId];
protected override object GetLedCustomData(LedId ledId) => CoolerMasterMouseLedMappings.Mapping[DeviceInfo.DeviceIndex][ledId];
#endregion
}
}

View File

@ -16,12 +16,7 @@ namespace RGB.NET.Devices.CoolerMaster.Native
#region Libary Management
private static IntPtr _dllHandle = IntPtr.Zero;
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
internal static string LoadedArchitecture { get; private set; }
/// <summary>
/// Reloads the SDK.
/// </summary>
@ -37,7 +32,7 @@ namespace RGB.NET.Devices.CoolerMaster.Native
// HACK: Load library at runtime to support both, x86 and x64 with one managed dll
List<string> possiblePathList = Environment.Is64BitProcess ? CoolerMasterDeviceProvider.PossibleX64NativePaths : CoolerMasterDeviceProvider.PossibleX86NativePaths;
string dllPath = possiblePathList.FirstOrDefault(File.Exists);
string? dllPath = possiblePathList.FirstOrDefault(File.Exists);
if (dllPath == null) throw new RGBDeviceException($"Can't find the CoolerMaster-SDK at one of the expected locations:\r\n '{string.Join("\r\n", possiblePathList.Select(Path.GetFullPath))}'");
_dllHandle = LoadLibrary(dllPath);
@ -76,14 +71,14 @@ namespace RGB.NET.Devices.CoolerMaster.Native
#region Pointers
private static GetSDKVersionPointer _getSDKVersionPointer;
private static SetControlDevicePointer _setControlDevicenPointer;
private static IsDevicePlugPointer _isDevicePlugPointer;
private static GetDeviceLayoutPointer _getDeviceLayoutPointer;
private static EnableLedControlPointer _enableLedControlPointer;
private static RefreshLedPointer _refreshLedPointer;
private static SetLedColorPointer _setLedColorPointer;
private static SetAllLedColorPointer _setAllLedColorPointer;
private static GetSDKVersionPointer? _getSDKVersionPointer;
private static SetControlDevicePointer? _setControlDevicenPointer;
private static IsDevicePlugPointer? _isDevicePlugPointer;
private static GetDeviceLayoutPointer? _getDeviceLayoutPointer;
private static EnableLedControlPointer? _enableLedControlPointer;
private static RefreshLedPointer? _refreshLedPointer;
private static SetLedColorPointer? _setLedColorPointer;
private static SetAllLedColorPointer? _setAllLedColorPointer;
#endregion
@ -125,49 +120,49 @@ namespace RGB.NET.Devices.CoolerMaster.Native
/// <summary>
/// CM-SDK: Get SDK Dll's Version.
/// </summary>
internal static int GetSDKVersion() => _getSDKVersionPointer();
internal static int GetSDKVersion() => (_getSDKVersionPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke();
/// <summary>
/// CM-SDK: set operating device
/// </summary>
internal static void SetControlDevice(CoolerMasterDevicesIndexes devicesIndexes)
=> _setControlDevicenPointer(devicesIndexes);
=> (_setControlDevicenPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(devicesIndexes);
/// <summary>
/// CM-SDK: verify if the deviced is plugged in
/// </summary>
internal static bool IsDevicePlugged(CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _isDevicePlugPointer(devIndex);
=> (_isDevicePlugPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(devIndex);
/// <summary>
/// CM-SDK: Obtain current device layout
/// </summary>
internal static CoolerMasterPhysicalKeyboardLayout GetDeviceLayout(CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _getDeviceLayoutPointer(devIndex);
=> (_getDeviceLayoutPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(devIndex);
/// <summary>
/// CM-SDK: set control over devices LED
/// </summary>
internal static bool EnableLedControl(bool value, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _enableLedControlPointer(value, devIndex);
=> (_enableLedControlPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(value, devIndex);
/// <summary>
/// CM-SDK: Print out the lights setting from Buffer to LED
/// </summary>
internal static bool RefreshLed(bool autoRefresh, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _refreshLedPointer(autoRefresh, devIndex);
=> (_refreshLedPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(autoRefresh, devIndex);
/// <summary>
/// CM-SDK: Set single Key LED color
/// </summary>
internal static bool SetLedColor(int row, int column, byte r, byte g, byte b, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _setLedColorPointer(row, column, r, g, b, devIndex);
=> (_setLedColorPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(row, column, r, g, b, devIndex);
/// <summary>
/// CM-SDK: Set Keyboard "every LED" color
/// </summary>
internal static bool SetAllLedColor(_CoolerMasterColorMatrix colorMatrix, CoolerMasterDevicesIndexes devIndex = CoolerMasterDevicesIndexes.Default)
=> _setAllLedColorPointer(colorMatrix, devIndex);
=> (_setAllLedColorPointer ?? throw new RGBDeviceException("The CoolerMaster-SDK is not initialized.")).Invoke(colorMatrix, devIndex);
// ReSharper restore EventExceptionNotDocumented

View File

@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using RGB.NET.Core;
using RGB.NET.Devices.Corsair.Native;
@ -18,7 +19,7 @@ namespace RGB.NET.Devices.Corsair
{
#region Properties & Fields
private static CorsairDeviceProvider _instance;
private static CorsairDeviceProvider? _instance;
/// <summary>
/// Gets the singleton <see cref="CorsairDeviceProvider"/> instance.
/// </summary>
@ -28,13 +29,13 @@ namespace RGB.NET.Devices.Corsair
/// Gets a modifiable list of paths used to find the native SDK-dlls for x86 applications.
/// The first match will be used.
/// </summary>
public static List<string> PossibleX86NativePaths { get; } = new List<string> { "x86/CUESDK.dll", "x86/CUESDK_2015.dll", "x86/CUESDK_2013.dll" };
public static List<string> PossibleX86NativePaths { get; } = new() { "x86/CUESDK.dll", "x86/CUESDK_2015.dll", "x86/CUESDK_2013.dll" };
/// <summary>
/// Gets a modifiable list of paths used to find the native SDK-dlls for x64 applications.
/// The first match will be used.
/// </summary>
public static List<string> PossibleX64NativePaths { get; } = new List<string> { "x64/CUESDK.dll", "x64/CUESDK_2015.dll", "x64/CUESDK_2013.dll" };
public static List<string> PossibleX64NativePaths { get; } = new() { "x64/CUESDK.dll", "x64/CUESDK_2015.dll", "x64/CUESDK_2013.dll" };
/// <inheritdoc />
/// <summary>
@ -42,21 +43,10 @@ namespace RGB.NET.Devices.Corsair
/// </summary>
public bool IsInitialized { get; private set; }
/// <summary>
/// Gets the loaded architecture (x64/x86).
/// </summary>
public string LoadedArchitecture => _CUESDK.LoadedArchitecture;
/// <summary>
/// Gets the protocol details for the current SDK-connection.
/// </summary>
public CorsairProtocolDetails ProtocolDetails { get; private set; }
/// <inheritdoc />
/// <summary>
/// Gets whether the application has exclusive access to the SDK or not.
/// </summary>
public bool HasExclusiveAccess { get; private set; }
public CorsairProtocolDetails? ProtocolDetails { get; private set; }
/// <summary>
/// Gets the last error documented by CUE.
@ -64,7 +54,7 @@ namespace RGB.NET.Devices.Corsair
public CorsairError LastError => _CUESDK.CorsairGetLastError();
/// <inheritdoc />
public IEnumerable<IRGBDevice> Devices { get; private set; }
public IEnumerable<IRGBDevice> Devices { get; private set; } = Enumerable.Empty<IRGBDevice>();
/// <summary>
/// The <see cref="DeviceUpdateTrigger"/> used to trigger the updates for corsair devices.
@ -94,13 +84,13 @@ namespace RGB.NET.Devices.Corsair
/// <inheritdoc />
/// <exception cref="RGBDeviceException">Thrown if the SDK is already initialized or if the SDK is not compatible to CUE.</exception>
/// <exception cref="CUEException">Thrown if the CUE-SDK provides an error.</exception>
public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool exclusiveAccessIfPossible = false, bool throwExceptions = false)
public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool throwExceptions = false)
{
IsInitialized = false;
try
{
UpdateTrigger?.Stop();
UpdateTrigger.Stop();
_CUESDK.Reload();
@ -115,42 +105,30 @@ namespace RGB.NET.Devices.Corsair
+ $"CUE-Version: {ProtocolDetails.ServerVersion} (Protocol {ProtocolDetails.ServerProtocolVersion})\r\n"
+ $"SDK-Version: {ProtocolDetails.SdkVersion} (Protocol {ProtocolDetails.SdkProtocolVersion})");
if (exclusiveAccessIfPossible)
{
if (!_CUESDK.CorsairRequestControl(CorsairAccessMode.ExclusiveLightingControl))
throw new CUEException(LastError);
HasExclusiveAccess = true;
}
else
HasExclusiveAccess = false;
// DarthAffe 07.07.2018: 127 is CUE, we want to directly compete with it as in older versions.
if (!_CUESDK.CorsairSetLayerPriority(127))
// DarthAffe 02.02.2021: 127 is iCUE
if (!_CUESDK.CorsairSetLayerPriority(128))
throw new CUEException(LastError);
Dictionary<string, int> modelCounter = new Dictionary<string, int>();
Dictionary<string, int> modelCounter = new();
IList<IRGBDevice> devices = new List<IRGBDevice>();
int deviceCount = _CUESDK.CorsairGetDeviceCount();
for (int i = 0; i < deviceCount; i++)
{
try
{
_CorsairDeviceInfo nativeDeviceInfo = (_CorsairDeviceInfo)Marshal.PtrToStructure(_CUESDK.CorsairGetDeviceInfo(i), typeof(_CorsairDeviceInfo));
CorsairRGBDeviceInfo info = new CorsairRGBDeviceInfo(i, RGBDeviceType.Unknown, nativeDeviceInfo, modelCounter);
_CorsairDeviceInfo nativeDeviceInfo = (_CorsairDeviceInfo)Marshal.PtrToStructure(_CUESDK.CorsairGetDeviceInfo(i), typeof(_CorsairDeviceInfo))!;
CorsairRGBDeviceInfo info = new(i, RGBDeviceType.Unknown, nativeDeviceInfo, modelCounter);
if (!info.CapsMask.HasFlag(CorsairDeviceCaps.Lighting))
continue; // Everything that doesn't support lighting control is useless
CorsairDeviceUpdateQueue deviceUpdateQueue = null;
CorsairDeviceUpdateQueue? deviceUpdateQueue = null;
foreach (ICorsairRGBDevice device in GetRGBDevice(info, i, nativeDeviceInfo, modelCounter))
{
if ((device == null) || !loadFilter.HasFlag(device.DeviceInfo.DeviceType)) continue;
if (deviceUpdateQueue == null)
deviceUpdateQueue = new CorsairDeviceUpdateQueue(UpdateTrigger, info.CorsairDeviceIndex);
deviceUpdateQueue ??= new CorsairDeviceUpdateQueue(UpdateTrigger, info.CorsairDeviceIndex);
device.Initialize(deviceUpdateQueue);
AddSpecialParts(device);
error = LastError;
if (error != CorsairError.Success)
@ -162,7 +140,7 @@ namespace RGB.NET.Devices.Corsair
catch { if (throwExceptions) throw; }
}
UpdateTrigger?.Start();
UpdateTrigger.Start();
Devices = new ReadOnlyCollection<IRGBDevice>(devices);
IsInitialized = true;
@ -208,7 +186,7 @@ namespace RGB.NET.Devices.Corsair
case CorsairDeviceType.Cooler:
case CorsairDeviceType.CommanderPro:
case CorsairDeviceType.LightningNodePro:
_CorsairChannelsInfo channelsInfo = nativeDeviceInfo.channels;
_CorsairChannelsInfo? channelsInfo = nativeDeviceInfo.channels;
if (channelsInfo != null)
{
IntPtr channelInfoPtr = channelsInfo.channels;
@ -218,14 +196,14 @@ namespace RGB.NET.Devices.Corsair
CorsairLedId referenceLed = GetChannelReferenceId(info.CorsairDeviceType, channel);
if (referenceLed == CorsairLedId.Invalid) continue;
_CorsairChannelInfo channelInfo = (_CorsairChannelInfo)Marshal.PtrToStructure(channelInfoPtr, typeof(_CorsairChannelInfo));
_CorsairChannelInfo channelInfo = (_CorsairChannelInfo)Marshal.PtrToStructure(channelInfoPtr, typeof(_CorsairChannelInfo))!;
int channelDeviceInfoStructSize = Marshal.SizeOf(typeof(_CorsairChannelDeviceInfo));
IntPtr channelDeviceInfoPtr = channelInfo.devices;
for (int device = 0; device < channelInfo.devicesCount; device++)
{
_CorsairChannelDeviceInfo channelDeviceInfo = (_CorsairChannelDeviceInfo)Marshal.PtrToStructure(channelDeviceInfoPtr, typeof(_CorsairChannelDeviceInfo));
_CorsairChannelDeviceInfo channelDeviceInfo = (_CorsairChannelDeviceInfo)Marshal.PtrToStructure(channelDeviceInfoPtr, typeof(_CorsairChannelDeviceInfo))!;
yield return new CorsairCustomRGBDevice(new CorsairCustomRGBDeviceInfo(info, nativeDeviceInfo, channelDeviceInfo, referenceLed, modelCounter));
referenceLed += channelDeviceInfo.deviceLedCount;
@ -252,50 +230,34 @@ namespace RGB.NET.Devices.Corsair
{
if (deviceType == CorsairDeviceType.Cooler)
return CorsairLedId.CustomLiquidCoolerChannel1Led1;
else
return channel switch
{
switch (channel)
{
case 0: return CorsairLedId.CustomDeviceChannel1Led1;
case 1: return CorsairLedId.CustomDeviceChannel2Led1;
case 2: return CorsairLedId.CustomDeviceChannel3Led1;
}
}
return CorsairLedId.Invalid;
}
private void AddSpecialParts(ICorsairRGBDevice device)
{
if (device.DeviceInfo.Model.Equals("K95 RGB Platinum", StringComparison.OrdinalIgnoreCase))
device.AddSpecialDevicePart(new LightbarSpecialPart(device));
}
/// <inheritdoc />
public void ResetDevices()
{
if (IsInitialized)
try
{
_CUESDK.Reload();
}
catch {/* shit happens */}
0 => CorsairLedId.CustomDeviceChannel1Led1,
1 => CorsairLedId.CustomDeviceChannel2Led1,
2 => CorsairLedId.CustomDeviceChannel3Led1,
_ => CorsairLedId.Invalid
};
}
private void Reset()
{
ProtocolDetails = null;
HasExclusiveAccess = false;
Devices = null;
Devices = Enumerable.Empty<IRGBDevice>();
IsInitialized = false;
}
/// <inheritdoc />
public void Dispose()
{
try { UpdateTrigger?.Dispose(); }
try { UpdateTrigger.Dispose(); }
catch { /* at least we tried */ }
foreach (IRGBDevice device in Devices)
try { device.Dispose(); }
catch { /* at least we tried */ }
Devices = Enumerable.Empty<IRGBDevice>();
try { _CUESDK.UnloadCUESDK(); }
catch { /* at least we tried */ }
}

View File

@ -1,24 +0,0 @@
using RGB.NET.Core;
namespace RGB.NET.Devices.Corsair
{
/// <summary>
/// Represents a device provider loaded used to dynamically load corsair devices into an application.
/// </summary>
public class CorsairDeviceProviderLoader : IRGBDeviceProviderLoader
{
#region Properties & Fields
/// <inheritdoc />
public bool RequiresInitialization => false;
#endregion
#region Methods
/// <inheritdoc />
public IRGBDeviceProvider GetDeviceProvider() => CorsairDeviceProvider.Instance;
#endregion
}
}

View File

@ -14,7 +14,7 @@ namespace RGB.NET.Devices.Corsair
{
#region Properties & Fields
private readonly Dictionary<LedId, CorsairLedId> _idMapping = new Dictionary<LedId, CorsairLedId>();
private readonly Dictionary<LedId, CorsairLedId> _idMapping = new();
#endregion
@ -42,15 +42,11 @@ namespace RGB.NET.Devices.Corsair
{
LedId ledId = referenceId + i;
_idMapping.Add(ledId, DeviceInfo.ReferenceCorsairLed + i);
InitializeLed(ledId, new Rectangle(i * 10, 0, 10, 10));
AddLed(ledId, new Point(i * 10, 0), new Size(10, 10));
}
string model = DeviceInfo.Model.Replace(" ", string.Empty).ToUpper();
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Corsair\Customs", $"{model}.xml"), null);
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => _idMapping.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
protected override object GetLedCustomData(LedId ledId) => _idMapping.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
protected virtual LedId GetReferenceLed(RGBDeviceType deviceType)
{

View File

@ -40,11 +40,11 @@ namespace RGB.NET.Devices.Corsair
{
int structSize = Marshal.SizeOf(typeof(_CorsairLedColor));
IntPtr ptr = Marshal.AllocHGlobal(structSize * dataSet.Count);
IntPtr addPtr = new IntPtr(ptr.ToInt64());
IntPtr addPtr = new(ptr.ToInt64());
foreach (KeyValuePair<object, Color> data in dataSet)
{
_CorsairLedColor color = new _CorsairLedColor
{
_CorsairLedColor color = new()
{
ledId = (int)data.Key,
r = data.Value.GetR(),
g = data.Value.GetG(),

View File

@ -18,12 +18,12 @@ namespace RGB.NET.Devices.Corsair
/// String containing version of SDK(like "1.0.0.1").
/// Always contains valid value even if there was no CUE found.
/// </summary>
public string SdkVersion { get; }
public string? SdkVersion { get; }
/// <summary>
/// String containing version of CUE(like "1.0.0.1") or NULL if CUE was not found.
/// </summary>
public string ServerVersion { get; }
public string? ServerVersion { get; }
/// <summary>
/// Integer that specifies version of protocol that is implemented by current SDK.

View File

@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using RGB.NET.Core;
using RGB.NET.Devices.Corsair.Native;
namespace RGB.NET.Devices.Corsair
{
@ -27,13 +24,13 @@ namespace RGB.NET.Devices.Corsair
/// Gets a dictionary containing all <see cref="Led"/> of the <see cref="CorsairRGBDevice{TDeviceInfo}"/>.
/// </summary>
// ReSharper disable once MemberCanBePrivate.Global
protected Dictionary<CorsairLedId, Led> InternalLedMapping { get; } = new Dictionary<CorsairLedId, Led>();
protected Dictionary<CorsairLedId, Led> InternalLedMapping { get; } = new();
/// <summary>
/// Gets or sets the update queue performing updates for this device.
/// </summary>
// ReSharper disable once MemberCanBePrivate.Global
protected CorsairDeviceUpdateQueue DeviceUpdateQueue { get; set; }
protected CorsairDeviceUpdateQueue? DeviceUpdateQueue { get; set; }
#endregion
@ -45,7 +42,7 @@ namespace RGB.NET.Devices.Corsair
/// <param name="ledId">The <see cref="CorsairLedId"/> of the <see cref="Led"/> to get.</param>
/// <returns>The <see cref="Led"/> with the specified <see cref="CorsairLedId"/> or null if no <see cref="Led"/> is found.</returns>
// ReSharper disable once MemberCanBePrivate.Global
public Led this[CorsairLedId ledId] => InternalLedMapping.TryGetValue(ledId, out Led led) ? led : null;
public Led? this[CorsairLedId ledId] => InternalLedMapping.TryGetValue(ledId, out Led? led) ? led : null;
#endregion
@ -75,14 +72,13 @@ namespace RGB.NET.Devices.Corsair
foreach (Led led in LedMapping.Values)
{
CorsairLedId ledId = (CorsairLedId)led.CustomData;
if (ledId != CorsairLedId.Invalid)
if (led.CustomData is CorsairLedId ledId && (ledId != CorsairLedId.Invalid))
InternalLedMapping.Add(ledId, led);
}
if (Size == Size.Invalid)
{
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
Rectangle ledRectangle = new(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
}
}
@ -94,7 +90,7 @@ namespace RGB.NET.Devices.Corsair
/// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate)
=> DeviceUpdateQueue.SetData(ledsToUpdate.Where(x => (x.Color.A > 0) && (x.CustomData is CorsairLedId ledId && (ledId != CorsairLedId.Invalid))));
=> DeviceUpdateQueue?.SetData(ledsToUpdate.Where(x => (x.Color.A > 0) && (x.CustomData is CorsairLedId ledId && (ledId != CorsairLedId.Invalid))));
/// <inheritdoc />
public override void Dispose()

View File

@ -37,11 +37,7 @@ namespace RGB.NET.Devices.Corsair
/// <inheritdoc />
public string Model { get; }
/// <inheritdoc />
public Uri Image { get; set; }
/// <inheritdoc />
public RGBDeviceLighting Lighting => RGBDeviceLighting.Key;
public object? LayoutMetadata { get; set; }
/// <summary>
/// Gets a flag that describes device capabilities. (<see cref="CorsairDeviceCaps" />)
@ -64,7 +60,7 @@ namespace RGB.NET.Devices.Corsair
this.CorsairDeviceIndex = deviceIndex;
this.DeviceType = deviceType;
this.CorsairDeviceType = nativeInfo.type;
this.Model = nativeInfo.model == IntPtr.Zero ? null : Regex.Replace(Marshal.PtrToStringAnsi(nativeInfo.model) ?? string.Empty, " ?DEMO", string.Empty, RegexOptions.IgnoreCase);
this.Model = nativeInfo.model == IntPtr.Zero ? string.Empty : Regex.Replace(Marshal.PtrToStringAnsi(nativeInfo.model) ?? string.Empty, " ?DEMO", string.Empty, RegexOptions.IgnoreCase);
this.CapsMask = (CorsairDeviceCaps)nativeInfo.capsMask;
DeviceName = GetUniqueModelName(modelCounter);
@ -95,9 +91,9 @@ namespace RGB.NET.Devices.Corsair
private string GetUniqueModelName(Dictionary<string, int> modelCounter)
{
if (modelCounter.TryGetValue(Model, out int counter))
if (modelCounter.TryGetValue(Model, out int _))
{
counter = ++modelCounter[Model];
int counter = ++modelCounter[Model];
return $"{Manufacturer} {Model} {counter}";
}
else

View File

@ -29,14 +29,11 @@ namespace RGB.NET.Devices.Corsair
/// <inheritdoc />
protected override void InitializeLayout()
{
InitializeLed(LedId.Headset1, new Rectangle(0, 0, 10, 10));
InitializeLed(LedId.Headset2, new Rectangle(10, 0, 10, 10));
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Corsair\Headsets", $"{DeviceInfo.Model.Replace(" ", string.Empty).ToUpper()}.xml"), null);
AddLed(LedId.Headset1, new Point(0, 0), new Size(10, 10));
AddLed(LedId.Headset2, new Point(10, 0), new Size(10, 10));
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => HeadsetIdMapping.DEFAULT.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
protected override object GetLedCustomData(LedId ledId) => HeadsetIdMapping.DEFAULT.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
#endregion
}

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{
internal static class HeadsetIdMapping
{
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId>
{
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{
{ LedId.Headset1, CorsairLedId.LeftLogo },
{ LedId.Headset2, CorsairLedId.RightLogo },
};

View File

@ -34,28 +34,33 @@ namespace RGB.NET.Devices.Corsair
/// <inheritdoc />
protected override void InitializeLayout()
{
_CorsairLedPositions nativeLedPositions = (_CorsairLedPositions)Marshal.PtrToStructure(_CUESDK.CorsairGetLedPositionsByDeviceIndex(DeviceInfo.CorsairDeviceIndex), typeof(_CorsairLedPositions));
_CorsairLedPositions? nativeLedPositions = (_CorsairLedPositions?)Marshal.PtrToStructure(_CUESDK.CorsairGetLedPositionsByDeviceIndex(DeviceInfo.CorsairDeviceIndex), typeof(_CorsairLedPositions));
if (nativeLedPositions == null) return;
int structSize = Marshal.SizeOf(typeof(_CorsairLedPosition));
IntPtr ptr = nativeLedPositions.pLedPosition;
List<_CorsairLedPosition> positions = new List<_CorsairLedPosition>();
List<_CorsairLedPosition> positions = new();
for (int i = 0; i < nativeLedPositions.numberOfLed; i++)
{
_CorsairLedPosition ledPosition = (_CorsairLedPosition)Marshal.PtrToStructure(ptr, typeof(_CorsairLedPosition));
_CorsairLedPosition? ledPosition = (_CorsairLedPosition?)Marshal.PtrToStructure(ptr, typeof(_CorsairLedPosition));
if (ledPosition == null) continue;
ptr = new IntPtr(ptr.ToInt64() + structSize);
positions.Add(ledPosition);
}
Dictionary<CorsairLedId, LedId> mapping = HeadsetStandIdMapping.DEFAULT.SwapKeyValue();
foreach (_CorsairLedPosition ledPosition in positions.OrderBy(p => p.LedId))
InitializeLed(mapping.TryGetValue(ledPosition.LedId, out LedId ledId) ? ledId : LedId.Invalid, ledPosition.ToRectangle());
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, @"Layouts\Corsair\HeadsetStands", $"{DeviceInfo.Model.Replace(" ", string.Empty).ToUpper()}.xml"), null);
{
LedId ledId = mapping.TryGetValue(ledPosition.LedId, out LedId id) ? id : LedId.Invalid;
Rectangle rectangle = ledPosition.ToRectangle();
AddLed(ledId, rectangle.Location, rectangle.Size);
}
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => HeadsetStandIdMapping.DEFAULT.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
protected override object GetLedCustomData(LedId ledId) => HeadsetStandIdMapping.DEFAULT.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
#endregion
}

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{
internal static class HeadsetStandIdMapping
{
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId>
{
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{
{ LedId.HeadsetStand1, CorsairLedId.HeadsetStandZone1 },
{ LedId.HeadsetStand2, CorsairLedId.HeadsetStandZone2 },
{ LedId.HeadsetStand3, CorsairLedId.HeadsetStandZone3 },

View File

@ -5,6 +5,9 @@ namespace RGB.NET.Devices.Corsair
{
internal static class DictionaryExtension
{
public static Dictionary<TValue, TKey> SwapKeyValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary) => dictionary.ToDictionary(x => x.Value, x => x.Key);
public static Dictionary<TValue, TKey> SwapKeyValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
where TKey : notnull
where TValue : notnull
=> dictionary.ToDictionary(x => x.Value, x => x.Key);
}
}

View File

@ -33,7 +33,8 @@ namespace RGB.NET.Devices.Corsair
/// <inheritdoc />
protected override void InitializeLayout()
{
_CorsairLedPositions nativeLedPositions = (_CorsairLedPositions)Marshal.PtrToStructure(_CUESDK.CorsairGetLedPositionsByDeviceIndex(DeviceInfo.CorsairDeviceIndex), typeof(_CorsairLedPositions));
_CorsairLedPositions? nativeLedPositions = (_CorsairLedPositions?)Marshal.PtrToStructure(_CUESDK.CorsairGetLedPositionsByDeviceIndex(DeviceInfo.CorsairDeviceIndex), typeof(_CorsairLedPositions));
if (nativeLedPositions == null) return;
int structSize = Marshal.SizeOf(typeof(_CorsairLedPosition));
IntPtr ptr = nativeLedPositions.pLedPosition;
@ -41,19 +42,18 @@ namespace RGB.NET.Devices.Corsair
Dictionary<CorsairLedId, LedId> mapping = KeyboardIdMapping.DEFAULT.SwapKeyValue();
for (int i = 0; i < nativeLedPositions.numberOfLed; i++)
{
_CorsairLedPosition ledPosition = (_CorsairLedPosition)Marshal.PtrToStructure(ptr, typeof(_CorsairLedPosition));
InitializeLed(mapping.TryGetValue(ledPosition.LedId, out LedId ledId) ? ledId : LedId.Invalid, ledPosition.ToRectangle());
_CorsairLedPosition? ledPosition = (_CorsairLedPosition?)Marshal.PtrToStructure(ptr, typeof(_CorsairLedPosition));
if (ledPosition == null) continue;
LedId ledId = mapping.TryGetValue(ledPosition.LedId, out LedId id) ? id : LedId.Invalid;
Rectangle rectangle = ledPosition.ToRectangle();
AddLed(ledId, rectangle.Location, rectangle.Size);
ptr = new IntPtr(ptr.ToInt64() + structSize);
}
string model = DeviceInfo.Model.Replace(" ", string.Empty).ToUpper();
ApplyLayoutFromFile(PathHelper.GetAbsolutePath(this, $@"Layouts\Corsair\Keyboards\{model}", $"{DeviceInfo.PhysicalLayout.ToString().ToUpper()}.xml"),
DeviceInfo.LogicalLayout.ToString());
}
/// <inheritdoc />
protected override object CreateLedCustomData(LedId ledId) => KeyboardIdMapping.DEFAULT.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
protected override object GetLedCustomData(LedId ledId) => KeyboardIdMapping.DEFAULT.TryGetValue(ledId, out CorsairLedId id) ? id : CorsairLedId.Invalid;
#endregion
}

View File

@ -5,8 +5,8 @@ namespace RGB.NET.Devices.Corsair
{
internal static class KeyboardIdMapping
{
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new Dictionary<LedId, CorsairLedId>
{
internal static readonly Dictionary<LedId, CorsairLedId> DEFAULT = new()
{
{ LedId.Invalid, CorsairLedId.Invalid },
{ LedId.Logo, CorsairLedId.Logo },
{ LedId.Keyboard_Escape, CorsairLedId.Escape },

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