The plugin is a NativeAOT executable that speaks the Stream Deck SDK v2 WebSocket protocol itself, reads snapshot.json and draws each key as SVG (D10). The installer finds Elgato Stream Deck or OpenDeck, stages the shipped plugin beside the installed one, stops a running host, swaps and rolls back on failure (D11). tools/publish.py publishes the app, CLI and plugin for win-x64 or linux-x64 into one folder. Refs #1
145 lines
8.0 KiB
C#
145 lines
8.0 KiB
C#
using System.Diagnostics;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using FinalToken.Core;
|
|
|
|
namespace FinalToken.StreamDeck;
|
|
|
|
public sealed record Registration(int Port, string Uuid, string Event)
|
|
{
|
|
public static Registration? Parse(string[] args)
|
|
{
|
|
var values = new Dictionary<string, string>();
|
|
for (var i = 0; i + 1 < args.Length; i += 2) values[args[i]] = args[i + 1];
|
|
return values.TryGetValue("-port", out var port) && int.TryParse(port, out var number) && number is > 0 and <= 65535 &&
|
|
values.TryGetValue("-pluginUUID", out var uuid) && uuid.Length > 0 &&
|
|
values.TryGetValue("-registerEvent", out var evt) && evt == "registerPlugin" && values.ContainsKey("-info") ? new(number, uuid, evt) : null;
|
|
}
|
|
}
|
|
public sealed record Command(string Event, string? Context = null, string? Uuid = null, string? Action = null, JsonElement? Payload = null);
|
|
public sealed record ImagePayload(string Image, int Target = 0);
|
|
public sealed record TitlePayload(string Title, int Target = 0);
|
|
public sealed record InspectorPayload(StatSettings Settings, WindowOption[] Windows);
|
|
public sealed record WindowOption(string Id, string Label);
|
|
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
|
|
[JsonSerializable(typeof(Command))]
|
|
[JsonSerializable(typeof(ImagePayload))]
|
|
[JsonSerializable(typeof(TitlePayload))]
|
|
[JsonSerializable(typeof(StatSettings))]
|
|
[JsonSerializable(typeof(InspectorPayload))]
|
|
public partial class PluginJsonContext : JsonSerializerContext;
|
|
|
|
public interface IPluginSocket
|
|
{
|
|
Task SendAsync(string json, CancellationToken cancellationToken);
|
|
Task<string?> ReceiveAsync(CancellationToken cancellationToken);
|
|
}
|
|
public sealed class PluginSocket(ClientWebSocket socket) : IPluginSocket
|
|
{
|
|
public async Task SendAsync(string json, CancellationToken cancellationToken) =>
|
|
await socket.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, cancellationToken);
|
|
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken)
|
|
{
|
|
var buffer = new byte[8192];
|
|
using var message = new MemoryStream();
|
|
while (true)
|
|
{
|
|
var result = await socket.ReceiveAsync(buffer.AsMemory(), cancellationToken);
|
|
if (result.MessageType == WebSocketMessageType.Close) return null;
|
|
if (result.MessageType != WebSocketMessageType.Text || message.Length + result.Count > 1_048_576)
|
|
throw new InvalidDataException("Invalid host frame.");
|
|
message.Write(buffer, 0, result.Count);
|
|
if (result.EndOfMessage) return Encoding.UTF8.GetString(message.ToArray());
|
|
}
|
|
}
|
|
}
|
|
|
|
public sealed class PluginSession(IPluginSocket socket, Func<string?, Task<bool>> launch)
|
|
{
|
|
public const string Action = "de.finalfactory.finaltoken.stat";
|
|
private readonly Dictionary<string, StatSettings> keys = [];
|
|
private readonly Dictionary<string, string> images = [];
|
|
private SnapshotReadResult read = new(null, true, null);
|
|
public Task RegisterAsync(Registration registration, CancellationToken ct = default) => Send(new(registration.Event, Uuid: registration.Uuid), ct);
|
|
public async Task UpdateAsync(SnapshotReadResult snapshot, DateTimeOffset now, CancellationToken ct = default)
|
|
{
|
|
read = StatRenderer.Validate(snapshot);
|
|
foreach (var (context, settings) in keys) await Draw(context, settings, now, ct);
|
|
}
|
|
public async Task HandleAsync(string json, DateTimeOffset now, CancellationToken ct = default)
|
|
{
|
|
try
|
|
{
|
|
using var doc = JsonDocument.Parse(json);
|
|
var root = doc.RootElement;
|
|
if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("event", out var evt) || evt.ValueKind != JsonValueKind.String) return;
|
|
if (evt.GetString() == "systemDidWakeUp") { images.Clear(); await UpdateAsync(read, now, ct); return; }
|
|
if (!root.TryGetProperty("context", out var ctx) || ctx.ValueKind != JsonValueKind.String || ctx.GetString() is not { Length: > 0 } context) return;
|
|
if (root.TryGetProperty("action", out var action) && action.GetString() != Action) return;
|
|
root.TryGetProperty("payload", out var payload);
|
|
switch (evt.GetString())
|
|
{
|
|
case "willDisappear": keys.Remove(context); images.Remove(context); break;
|
|
case "willAppear":
|
|
case "didReceiveSettings":
|
|
var settings = ReadSettings(payload);
|
|
if (settings is null) return;
|
|
keys[context] = settings;
|
|
await Draw(context, settings, now, ct);
|
|
break;
|
|
case "keyDown":
|
|
if (!await launch(read.Snapshot?.AppPath)) await Send(new("showAlert", context), ct);
|
|
break;
|
|
case "sendToPlugin":
|
|
if (payload.ValueKind == JsonValueKind.Object && payload.TryGetProperty("settings", out _))
|
|
{
|
|
var updated = ReadSettings(payload);
|
|
if (updated is null) return;
|
|
keys[context] = updated;
|
|
await Send(new("setSettings", context, Payload: JsonSerializer.SerializeToElement(updated, PluginJsonContext.Default.StatSettings)), ct);
|
|
await Draw(context, updated, now, ct);
|
|
}
|
|
await Inspector(context, ct);
|
|
break;
|
|
case "propertyInspectorDidAppear": await Inspector(context, ct); break;
|
|
}
|
|
}
|
|
catch (Exception e) when (e is JsonException or InvalidOperationException or ArgumentException) { }
|
|
}
|
|
private static StatSettings? ReadSettings(JsonElement payload)
|
|
{
|
|
if (payload.ValueKind != JsonValueKind.Object || !payload.TryGetProperty("settings", out var element)) return new();
|
|
var settings = element.Deserialize(PluginJsonContext.Default.StatSettings);
|
|
return settings is { IsValid: true } ? settings : null;
|
|
}
|
|
private Task Inspector(string context, CancellationToken ct)
|
|
{
|
|
var settings = keys.GetValueOrDefault(context) ?? new();
|
|
var windows = read.Snapshot?.Providers.FirstOrDefault(p => p.Provider.ToString() == settings.Provider)?.Windows
|
|
.Select(w => new WindowOption(w.Window.Id, w.Window.Label)).ToArray() ?? [];
|
|
return Send(new("sendToPropertyInspector", context, Action: Action,
|
|
Payload: JsonSerializer.SerializeToElement(new InspectorPayload(settings, windows), PluginJsonContext.Default.InspectorPayload)), ct);
|
|
}
|
|
private async Task Draw(string context, StatSettings settings, DateTimeOffset now, CancellationToken ct)
|
|
{
|
|
var svg = StatRenderer.Render(read, settings, now);
|
|
if (images.GetValueOrDefault(context) == svg) return;
|
|
await Send(new("setTitle", context, Payload: JsonSerializer.SerializeToElement(new TitlePayload(""), PluginJsonContext.Default.TitlePayload)), ct);
|
|
await Send(new("setImage", context, Payload: JsonSerializer.SerializeToElement(new ImagePayload("data:image/svg+xml;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(svg))), PluginJsonContext.Default.ImagePayload)), ct);
|
|
images[context] = svg;
|
|
}
|
|
private Task Send(Command command, CancellationToken ct) => socket.SendAsync(JsonSerializer.Serialize(command, PluginJsonContext.Default.Command), ct);
|
|
public static Task<bool> LaunchAppAsync(string? path) => Task.Run(() =>
|
|
{
|
|
try
|
|
{
|
|
if (path is null || !Path.IsPathFullyQualified(path) || !File.Exists(path)) return false;
|
|
using var process = Process.Start(new ProcessStartInfo(path) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(path)! });
|
|
return process is not null;
|
|
}
|
|
catch (Exception e) when (e is IOException or System.ComponentModel.Win32Exception or InvalidOperationException) { return false; }
|
|
});
|
|
}
|