Skip to content

Commit

Permalink
Added extension to save layouts
Browse files Browse the repository at this point in the history
  • Loading branch information
DarthAffe committed Oct 31, 2023
1 parent 188de3c commit be25279
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions RGB.NET.Layout/LayoutExtension.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using RGB.NET.Core;

namespace RGB.NET.Layout;
Expand Down Expand Up @@ -51,4 +53,48 @@ public static void ApplyTo(this IDeviceLayout layout, IRGBDevice device, bool cr
device.RemoveLed(led);
}
}

/// <summary>
/// Saves the specified layout to the given location.
/// </summary>
/// <param name="layout">The layout to save.</param>
/// <param name="targetFile">The location to save to.</param>
public static void Save(this IDeviceLayout layout, string targetFile)
{
using FileStream fs = new(targetFile, FileMode.Create);
layout.Save(fs);
}

/// <summary>
/// Saves the specified layout to the given stream.
/// </summary>
/// <param name="layout">The layout to save.</param>
/// <param name="stream">The stream to save to.</param>
public static void Save(this IDeviceLayout layout, Stream stream)
{
Type? customDataType = layout.CustomData?.GetType();
Type? customLedDataType = layout.Leds.FirstOrDefault(x => x.CustomData != null)?.GetType();

Type[] customTypes;
if ((customDataType != null) && (customLedDataType != null))
customTypes = new[] { customDataType, customLedDataType };
else if (customDataType != null)
customTypes = new[] { customDataType };
else if (customLedDataType != null)
customTypes = new[] { customLedDataType };
else
customTypes = Array.Empty<Type>();

if (layout is DeviceLayout deviceLayout)
{
deviceLayout.InternalCustomData = deviceLayout.CustomData;

foreach (ILedLayout led in deviceLayout.Leds)
if (led is LedLayout ledLayout)
ledLayout.InternalCustomData = ledLayout.CustomData;
}

XmlSerializer serializer = new(typeof(DeviceLayout), null, customTypes, null, null);
serializer.Serialize(stream, layout);
}
}

0 comments on commit be25279

Please sign in to comment.