using System.Windows;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using Moli.Desktop.WebView;
using Application = System.Windows.Application;
namespace Moli.Desktop.Windows;
/// Creates and updates real WPF desktop surfaces for runtime commands.
public sealed class RuntimeSurfaceController : IRuntimeSurfaceController
{
private readonly IPluginManager _plugins;
private readonly IWin32InteropService _interop;
private readonly IWebViewHostFactory _webViews;
private readonly DesktopPaths _paths;
private readonly IDiagnosticsService _diagnostics;
private readonly IServiceProvider _services;
private readonly IRuntimeEventBus _events;
private readonly Dictionary _widgets = [];
private readonly Dictionary _wallpapers = [];
private WallpaperRuntimeState _wallpaperState = new();
private bool _editMode;
private bool _safeInputMode;
private IDisposable? _eventSubscription;
private readonly Dictionary _sessions = [];
public RuntimeSurfaceController(
IPluginManager plugins,
IWin32InteropService interop,
IWebViewHostFactory webViews,
DesktopPaths paths,
IDiagnosticsService diagnostics,
IServiceProvider services,
IRuntimeEventBus events)
{
_plugins = plugins;
_interop = interop;
_webViews = webViews;
_paths = paths;
_diagnostics = diagnostics;
_services = services;
_events = events;
_eventSubscription = _events.Subscribe(HandleRuntimeEventAsync);
}
public Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
=> OnUiThreadAsync(async () =>
{
_editMode = enabled;
foreach (var widget in _widgets.Values)
{
cancellationToken.ThrowIfCancellationRequested();
await widget.SetEditModeAsync(enabled, cancellationToken).ConfigureAwait(true);
}
});
public Task ApplySafeInputModeAsync(bool enabled, CancellationToken cancellationToken = default)
=> OnUiThreadAsync(() =>
{
_safeInputMode = enabled;
foreach (var wallpaper in _wallpapers.Values)
{
wallpaper.ApplyState(_wallpaperState, _safeInputMode);
}
foreach (var widget in _widgets.Values)
{
widget.SetSafeInputMode(enabled);
}
return Task.CompletedTask;
});
public Task ApplyWidgetLayoutAsync(WidgetLayout layout, CancellationToken cancellationToken = default)
=> OnUiThreadAsync(async () =>
{
if (!_widgets.TryGetValue(layout.InstanceId, out var window))
{
var plugin = await _plugins.GetAsync(layout.PluginId, cancellationToken).ConfigureAwait(true);
if (plugin is null || plugin.State == PluginState.Invalid)
{
_diagnostics.Record(
DiagnosticSeverity.Warning,
"WidgetPluginNotFound",
"Widget plugin was not available for layout surface.",
new Dictionary { ["instanceId"] = layout.InstanceId.Value, ["pluginId"] = layout.PluginId.Value });
return;
}
window = new WidgetWindow(
plugin,
layout,
_webViews.Create(plugin),
_interop,
_paths,
_diagnostics,
CommitWidgetLayoutAsync);
_widgets[layout.InstanceId] = window;
window.Closed += (_, _) => _widgets.Remove(layout.InstanceId);
window.Show();
await window.LoadAsync(cancellationToken).ConfigureAwait(true);
}
var monitors = _interop.GetMonitors();
var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
if (monitor is not null)
{
window.SetMonitorInfo(monitor);
}
window.ApplyLayout(layout, _editMode, _safeInputMode, GetSession(layout.InstanceId));
});
public Task ApplyWidgetSessionOverlayAsync(WidgetLayout layout, WidgetSessionOverlay overlay, CancellationToken cancellationToken = default)
=> OnUiThreadAsync(async () =>
{
_sessions[layout.InstanceId] = overlay;
if (!_widgets.TryGetValue(layout.InstanceId, out var window))
{
return;
}
await window.ApplySessionOverlayAsync(overlay, _editMode, _safeInputMode, cancellationToken).ConfigureAwait(true);
});
public Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default)
=> OnUiThreadAsync(async () =>
{
if (wallpaper.PluginId is null)
{
return;
}
var plugin = await _plugins.GetAsync(wallpaper.PluginId.Value, cancellationToken).ConfigureAwait(true);
if (plugin is null)
{
_diagnostics.Record(
DiagnosticSeverity.Warning,
"WallpaperPluginNotFound",
"Wallpaper plugin was not available for surface creation.",
new Dictionary { ["pluginId"] = wallpaper.PluginId.Value.Value });
return;
}
foreach (var (_, existing) in _wallpapers)
{
existing.Close();
}
_wallpapers.Clear();
_wallpaperState = wallpaper;
var monitors = _interop.GetMonitors();
foreach (var monitor in monitors)
{
cancellationToken.ThrowIfCancellationRequested();
var wallpaperWindow = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
_wallpapers[monitor.Id] = wallpaperWindow;
wallpaperWindow.Closed += (_, _) => _wallpapers.Remove(monitor.Id);
wallpaperWindow.Show();
await wallpaperWindow.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
wallpaperWindow.ApplyState(wallpaper, _safeInputMode);
}
ReapplyDesktopWidgetLayers();
});
public Task DisableWallpaperAsync(CancellationToken cancellationToken = default)
=> OnUiThreadAsync(() =>
{
_wallpaperState = _wallpaperState with { IsEnabled = false };
foreach (var (_, wallpaper) in _wallpapers)
{
wallpaper.Close();
}
_wallpapers.Clear();
return Task.CompletedTask;
});
public Task ShutdownAsync(CancellationToken cancellationToken = default)
=> OnUiThreadAsync(() =>
{
foreach (var widget in _widgets.Values.ToArray())
{
widget.Close();
}
_widgets.Clear();
_sessions.Clear();
foreach (var (_, wallpaper) in _wallpapers)
{
wallpaper.Close();
}
_wallpapers.Clear();
_eventSubscription?.Dispose();
_eventSubscription = null;
return Task.CompletedTask;
});
public Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default)
=> OnUiThreadAsync(() =>
{
var monitors = _interop.GetMonitors();
foreach (var (id, window) in _widgets)
{
cancellationToken.ThrowIfCancellationRequested();
var layout = window.CurrentLayout;
var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
if (monitor is not null)
{
window.SetMonitorInfo(monitor);
}
window.ApplyLayout(layout, _editMode, _safeInputMode, GetSession(id));
}
return Task.CompletedTask;
});
public Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default)
=> OnUiThreadAsync(async () =>
{
if (_wallpaperState.PluginId is null || _wallpapers.Count == 0)
{
return;
}
var plugin = await _plugins.GetAsync(_wallpaperState.PluginId.Value, cancellationToken).ConfigureAwait(true);
if (plugin is null)
{
return;
}
var monitors = _interop.GetMonitors();
var currentIds = new HashSet(_wallpapers.Keys);
var newIds = new HashSet(monitors.Select(m => m.Id));
foreach (var removed in currentIds.Where(id => !newIds.Contains(id)))
{
if (_wallpapers.TryGetValue(removed, out var removedWindow))
{
removedWindow.Close();
_wallpapers.Remove(removed);
}
}
foreach (var monitor in monitors)
{
cancellationToken.ThrowIfCancellationRequested();
if (_wallpapers.TryGetValue(monitor.Id, out var existing))
{
existing.ApplyState(_wallpaperState, _safeInputMode);
}
else
{
var wallpaperWindow = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
_wallpapers[monitor.Id] = wallpaperWindow;
wallpaperWindow.Closed += (_, _) => _wallpapers.Remove(monitor.Id);
wallpaperWindow.Show();
await wallpaperWindow.LoadAsync(_wallpaperState, cancellationToken).ConfigureAwait(true);
wallpaperWindow.ApplyState(_wallpaperState, _safeInputMode);
}
}
});
public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default)
=> OnUiThreadAsync(() =>
{
var monitors = _interop.GetMonitors();
foreach (var (_, window) in _widgets.Where(kv => kv.Value.CurrentLayout.DisplayLayer == DisplayLayer.Desktop))
{
cancellationToken.ThrowIfCancellationRequested();
var layout = window.CurrentLayout;
var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
if (monitor is not null)
{
window.SetMonitorInfo(monitor);
}
window.ApplyLayout(layout, _editMode, _safeInputMode, GetSession(window.InstanceId));
}
foreach (var (monitorId, wallpaper) in _wallpapers)
{
cancellationToken.ThrowIfCancellationRequested();
var monitor = monitors.FirstOrDefault(m => m.Id == monitorId);
if (monitor is not null)
{
wallpaper.ApplyState(_wallpaperState, _safeInputMode);
}
}
return Task.CompletedTask;
});
private WidgetSessionOverlay GetSession(WidgetInstanceId instanceId)
=> _sessions.TryGetValue(instanceId, out var overlay) ? overlay : WidgetSessionOverlay.Empty;
private async Task CommitWidgetLayoutAsync(
WidgetInstanceId instanceId,
WidgetLayoutPatch patch,
CancellationToken cancellationToken)
{
var runtime = _services.GetRequiredService();
await runtime.UpdateWidgetLayoutAsync(instanceId, patch, cancellationToken).ConfigureAwait(true);
}
private void ReapplyDesktopWidgetLayers()
{
foreach (var widget in _widgets.Values.Where(widget => widget.CurrentLayout.DisplayLayer == DisplayLayer.Desktop))
{
widget.ApplyLayout(widget.CurrentLayout, _editMode, _safeInputMode, GetSession(widget.InstanceId));
}
}
private Task HandleRuntimeEventAsync(RuntimeEvent runtimeEvent)
{
if (!string.Equals(runtimeEvent.Name, "plugin.resizeRequested", StringComparison.OrdinalIgnoreCase) ||
runtimeEvent.Payload is null)
{
return Task.CompletedTask;
}
return OnUiThreadAsync(() =>
{
try
{
var json = JsonSerializer.Serialize(runtimeEvent.Payload, new JsonSerializerOptions(JsonSerializerDefaults.Web));
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
if (!root.TryGetProperty("hostId", out var hostIdElement))
{
return Task.CompletedTask;
}
var hostId = hostIdElement.GetString();
var widget = _widgets.Values.FirstOrDefault(item => string.Equals(item.HostId, hostId, StringComparison.OrdinalIgnoreCase));
if (widget is null ||
!root.TryGetProperty("params", out var parameters) ||
parameters.ValueKind != JsonValueKind.Object)
{
return Task.CompletedTask;
}
var width = TryReadPositiveDouble(parameters, "width");
var height = TryReadPositiveDouble(parameters, "height");
widget.ApplyRequestedSize(width, height);
}
catch (JsonException ex)
{
_diagnostics.Record(
DiagnosticSeverity.Warning,
"PluginResizeRequestInvalid",
"Plugin resize request payload could not be parsed.",
new Dictionary { ["exception"] = ex.GetType().Name });
}
return Task.CompletedTask;
});
}
private static double? TryReadPositiveDouble(JsonElement parameters, string propertyName)
{
if (!parameters.TryGetProperty(propertyName, out var value))
{
return null;
}
return value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) && number > 0
? number
: null;
}
private static async Task OnUiThreadAsync(Func action)
{
var dispatcher = Application.Current?.Dispatcher;
if (dispatcher is null || dispatcher.CheckAccess())
{
await action().ConfigureAwait(true);
return;
}
await await dispatcher.InvokeAsync(action).Task.ConfigureAwait(false);
}
}