using Moli.Desktop.Diagnostics;
|
using Moli.Desktop.Layout;
|
using Moli.Desktop.Plugins;
|
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
namespace Moli.Desktop.Runtime;
|
|
public sealed record WallpaperRuntimeState
|
{
|
public bool IsEnabled { get; init; }
|
public bool IsPaused { get; init; }
|
public bool IsMuted { get; init; }
|
public double Opacity { get; init; } = 1;
|
public bool ClickThrough { get; init; } = true;
|
public PluginId? PluginId { get; init; }
|
}
|
|
public sealed record AppRuntimeState
|
{
|
public bool IsEditMode { get; init; }
|
public bool IsGlobalLocked { get; init; }
|
public bool IsSafeInputMode { get; init; }
|
public WallpaperRuntimeState Wallpaper { get; init; } = new();
|
public IReadOnlyList<PluginRuntimeState> Plugins { get; init; } = [];
|
public IReadOnlyList<WidgetRuntimeState> Widgets { get; init; } = [];
|
public IReadOnlyList<DiagnosticEntry> Diagnostics { get; init; } = [];
|
}
|
|
public sealed record RuntimeEvent
|
{
|
public required string Name { get; init; }
|
public object? Payload { get; init; }
|
public DateTimeOffset Timestamp { get; init; } = DateTimeOffset.UtcNow;
|
}
|
|
public interface IRuntimeEventBus
|
{
|
IDisposable Subscribe(Func<RuntimeEvent, Task> handler);
|
Task PublishAsync(RuntimeEvent runtimeEvent, CancellationToken cancellationToken = default);
|
}
|
|
public sealed class RuntimeEventBus : IRuntimeEventBus
|
{
|
private readonly object _gate = new();
|
private readonly List<Func<RuntimeEvent, Task>> _handlers = [];
|
private readonly ILogger<RuntimeEventBus> _logger;
|
|
public RuntimeEventBus(ILogger<RuntimeEventBus>? logger = null)
|
{
|
_logger = logger ?? NullLogger<RuntimeEventBus>.Instance;
|
}
|
|
public IDisposable Subscribe(Func<RuntimeEvent, Task> handler)
|
{
|
lock (_gate)
|
{
|
_handlers.Add(handler);
|
}
|
|
return new Subscription(() =>
|
{
|
lock (_gate)
|
{
|
_handlers.Remove(handler);
|
}
|
});
|
}
|
|
public async Task PublishAsync(RuntimeEvent runtimeEvent, CancellationToken cancellationToken = default)
|
{
|
_logger.LogDebug("Runtime event published: {EventName}", runtimeEvent.Name);
|
Func<RuntimeEvent, Task>[] handlers;
|
lock (_gate)
|
{
|
handlers = [.. _handlers];
|
}
|
|
foreach (var handler in handlers)
|
{
|
cancellationToken.ThrowIfCancellationRequested();
|
await handler(runtimeEvent).ConfigureAwait(false);
|
}
|
}
|
|
private sealed class Subscription(Action dispose) : IDisposable
|
{
|
public void Dispose() => dispose();
|
}
|
}
|