using Moli.Desktop.Configuration; using Moli.Desktop.Diagnostics; using Moli.Desktop.Hotkeys; using Moli.Desktop.Interop; using Moli.Desktop.Layout; using Moli.Desktop.Llm; using Moli.Desktop.Plugins; namespace Moli.Desktop.Runtime; public sealed class DesktopRuntimeCoordinator : IDesktopRuntime { private readonly IConfigurationService _configuration; private readonly IPluginManager _plugins; private readonly ILayoutManager _layout; private readonly IWin32InteropService _interop; private readonly IDiagnosticsService _diagnostics; private readonly IRuntimeEventBus _events; private readonly IRuntimeSurfaceController _surfaces; private readonly DisplayChangeMonitor _displayMonitor; private readonly ILlmGatewayService _llmGateway; private readonly IHotkeyService _hotkeys; private readonly SemaphoreSlim _lock = new(1, 1); private AppSettingsDocument _settings = new(); private HotkeysDocument _hotkeyDocument = HotkeysDocument.CreateDefault(); private IReadOnlyList _pluginSnapshot = []; private WallpaperRuntimeState _wallpaper = new(); private bool _isEditMode; private bool _isGlobalLocked; private bool _isSafeInputMode; private readonly Dictionary _sessions = []; private int _hotkeyDispatching; public DesktopRuntimeCoordinator( IConfigurationService configuration, IPluginManager plugins, ILayoutManager layout, IWin32InteropService interop, IDiagnosticsService diagnostics, IRuntimeEventBus events, IRuntimeSurfaceController surfaces, DisplayChangeMonitor displayMonitor, ILlmGatewayService llmGateway, IHotkeyService hotkeys) { _configuration = configuration; _plugins = plugins; _layout = layout; _interop = interop; _diagnostics = diagnostics; _events = events; _surfaces = surfaces; _displayMonitor = displayMonitor; _llmGateway = llmGateway; _hotkeys = hotkeys; _hotkeys.HotkeyPressed += OnHotkeyPressedAsync; } public async Task> StartAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { _settings = await _configuration.LoadAppSettingsAsync(cancellationToken).ConfigureAwait(false); _isEditMode = _settings.Runtime.EditMode; _isSafeInputMode = _settings.Runtime.SafeInputMode; await _surfaces.ApplyEditModeAsync(_isEditMode, cancellationToken).ConfigureAwait(false); await _surfaces.ApplySafeInputModeAsync(_isSafeInputMode, cancellationToken).ConfigureAwait(false); await _layout.LoadAsync(cancellationToken).ConfigureAwait(false); ReconcileCurrentMonitors(); await _layout.SaveAsync(cancellationToken).ConfigureAwait(false); _pluginSnapshot = await _plugins.ScanAsync(cancellationToken).ConfigureAwait(false); foreach (var layout in _layout.GetAll().Where(layout => layout.IsVisible)) { await _surfaces.ApplyWidgetLayoutAsync(ToSurfaceLayout(layout), cancellationToken).ConfigureAwait(false); } _hotkeyDocument = await _configuration.LoadHotkeysAsync(cancellationToken).ConfigureAwait(false); await ApplyIdleInteractableOverlaysAsync(cancellationToken).ConfigureAwait(false); await _hotkeys.ReplaceBindingsAsync(_hotkeyDocument.Bindings, cancellationToken).ConfigureAwait(false); _displayMonitor.DisplayChanged += () => OnDisplayTopologyChangedAsync(); _displayMonitor.Start(); _diagnostics.Record(DiagnosticSeverity.Info, DiagnosticCodes.ApplicationStarted, "Desktop runtime started."); var state = BuildState(); await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false); return OperationResult.Success(state); } finally { _lock.Release(); } } public async Task ShutdownAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { _hotkeys.UnregisterAll(); await SaveRuntimeSettingsAsync(cancellationToken).ConfigureAwait(false); await _layout.SaveAsync(cancellationToken).ConfigureAwait(false); await _surfaces.ShutdownAsync(cancellationToken).ConfigureAwait(false); await _events.PublishAsync(new RuntimeEvent { Name = "app.shutdown", Payload = BuildState() }, cancellationToken).ConfigureAwait(false); return OperationResult.Success("Desktop runtime stopped."); } finally { _lock.Release(); } } public async Task GetStateAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { return BuildState(); } finally { _lock.Release(); } } public Task> SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default) => UpdateRuntimeFlagAsync( "app.editModeChanged", () => _isEditMode = enabled, () => _surfaces.ApplyEditModeAsync(enabled, cancellationToken), cancellationToken); public async Task> SetGlobalLockedAsync(bool enabled, CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { _isGlobalLocked = enabled; await ApplyAllWidgetLayoutsAsync(cancellationToken).ConfigureAwait(false); var state = BuildState(); await _events.PublishAsync(new RuntimeEvent { Name = "app.globalLockedChanged", Payload = state }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false); return OperationResult.Success(state); } finally { _lock.Release(); } } public Task> SetSafeInputModeAsync(bool enabled, CancellationToken cancellationToken = default) => UpdateRuntimeFlagAsync( "app.safeInputModeChanged", () => _isSafeInputMode = enabled, () => _surfaces.ApplySafeInputModeAsync(enabled, cancellationToken), cancellationToken); public async Task> ReloadPluginsAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { _pluginSnapshot = await _plugins.ScanAsync(cancellationToken).ConfigureAwait(false); await ApplyAllWidgetLayoutsAsync(cancellationToken).ConfigureAwait(false); var state = BuildState(); await _events.PublishAsync(new RuntimeEvent { Name = "plugin.reloaded", Payload = state.Plugins }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false); return OperationResult.Success(state); } finally { _lock.Release(); } } public async Task> EnableWallpaperAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { var wallpaperPlugin = _pluginSnapshot.FirstOrDefault(plugin => plugin.Type == PluginType.Wallpaper && plugin.State is PluginState.Enabled or PluginState.Loaded or PluginState.Running or PluginState.Paused); if (wallpaperPlugin is null) { return OperationResult.Failure("WallpaperPluginNotFound", "No enabled wallpaper plugin is available."); } _wallpaper = _wallpaper with { IsEnabled = true, IsPaused = false, PluginId = wallpaperPlugin.Id }; await _surfaces.EnableWallpaperAsync(_wallpaper, cancellationToken).ConfigureAwait(false); var state = BuildState(); await _events.PublishAsync(new RuntimeEvent { Name = "wallpaper.enabled", Payload = _wallpaper }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false); return OperationResult.Success(state); } finally { _lock.Release(); } } public async Task> DisableWallpaperAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { _wallpaper = _wallpaper with { IsEnabled = false, IsPaused = false }; await _surfaces.DisableWallpaperAsync(cancellationToken).ConfigureAwait(false); var state = BuildState(); await _events.PublishAsync(new RuntimeEvent { Name = "wallpaper.disabled", Payload = _wallpaper }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false); return OperationResult.Success(state); } finally { _lock.Release(); } } public async Task> UpdateWidgetLayoutAsync( WidgetInstanceId instanceId, WidgetLayoutPatch patch, CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (_isGlobalLocked && IsGeometryPatch(patch)) { return OperationResult.Failure("WidgetLayoutLocked", "Global lock is enabled."); } var result = _layout.Update(instanceId, patch); if (!result.Succeeded || result.Value is null) { return OperationResult.Failure(result.ErrorCode ?? "WidgetLayoutUpdateFailed", result.Message ?? "Widget layout update failed."); } if (patch.ClickThrough is not null) { await SyncSessionInteractableToLayoutClickThroughAsync(result.Value, cancellationToken).ConfigureAwait(false); } await _surfaces.ApplyWidgetLayoutAsync(ToSurfaceLayout(result.Value), cancellationToken).ConfigureAwait(false); await _layout.SaveAsync(cancellationToken).ConfigureAwait(false); var runtimeState = ToWidgetRuntimeState(result.Value); await _events.PublishAsync(new RuntimeEvent { Name = "widget.layoutChanged", Payload = runtimeState }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(BuildState(), cancellationToken).ConfigureAwait(false); return OperationResult.Success(runtimeState); } finally { _lock.Release(); } } public Task> SetWidgetInteractableAsync( WidgetInstanceId instanceId, bool enabled, CancellationToken cancellationToken = default) => MutateWidgetSessionAsync( instanceId, (_, overlay) => overlay with { Interactable = enabled }, "widget.interactableChanged", cancellationToken); public Task> ToggleWidgetInteractableAsync( WidgetInstanceId instanceId, CancellationToken cancellationToken = default) => MutateWidgetSessionAsync( instanceId, (_, overlay) => overlay with { Interactable = overlay.Interactable != true }, "widget.interactableChanged", cancellationToken); public Task>> SetPluginWidgetsInteractableAsync( PluginId pluginId, bool enabled, CancellationToken cancellationToken = default) => MutatePluginWidgetSessionsAsync( pluginId, (_, overlay) => overlay with { Interactable = enabled }, "widget.interactableChanged", cancellationToken); public Task>> TogglePluginWidgetsInteractableAsync( PluginId pluginId, CancellationToken cancellationToken = default) => MutatePluginWidgetSessionsAsync( pluginId, (_, overlay) => overlay with { Interactable = overlay.Interactable != true }, "widget.interactableChanged", cancellationToken); public Task> SetWidgetSessionVisibleAsync( WidgetInstanceId instanceId, bool visible, CancellationToken cancellationToken = default) => MutateWidgetSessionAsync( instanceId, (_, overlay) => overlay with { Visible = visible }, "widget.sessionVisibleChanged", cancellationToken); public Task> ToggleWidgetSessionVisibleAsync( WidgetInstanceId instanceId, CancellationToken cancellationToken = default) => MutateWidgetSessionAsync( instanceId, (layout, overlay) => overlay with { Visible = !WidgetSurfaceRules.ComputeVisible(overlay, layout.IsVisible) }, "widget.sessionVisibleChanged", cancellationToken); public Task>> TogglePluginWidgetsSessionVisibleAsync( PluginId pluginId, CancellationToken cancellationToken = default) => MutatePluginWidgetSessionsAsync( pluginId, (layout, overlay) => overlay with { Visible = !WidgetSurfaceRules.ComputeVisible(overlay, layout.IsVisible) }, "widget.sessionVisibleChanged", cancellationToken); public async Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { ReconcileCurrentMonitors(); await _layout.SaveAsync(cancellationToken).ConfigureAwait(false); await _surfaces.SyncAllLayoutsAsync(cancellationToken).ConfigureAwait(false); await _surfaces.SyncWallpaperMonitorsAsync(cancellationToken).ConfigureAwait(false); await _surfaces.ReattachDesktopLayersAsync(cancellationToken).ConfigureAwait(false); var state = BuildState(); await _events.PublishAsync(new RuntimeEvent { Name = "display.topologyChanged", Payload = state }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false); } finally { _lock.Release(); } } public async Task CancelPluginRequestsAsync(PluginId pluginId, CancellationToken cancellationToken = default) { await _llmGateway.CancelPluginRequestsAsync(pluginId.Value, cancellationToken).ConfigureAwait(false); } public async Task> GetHotkeyStatusesAsync(CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { return BuildHotkeyStatuses(); } finally { _lock.Release(); } } public async Task> SaveHotkeysAsync(HotkeysDocument document, CancellationToken cancellationToken = default) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { var validation = ValidateHotkeysDocument(document); if (!validation.Succeeded) { return OperationResult.Failure(validation.ErrorCode ?? "HotkeyInvalidDocument", validation.Message ?? "Hotkeys document is invalid."); } await _configuration.SaveHotkeysAsync(document, cancellationToken).ConfigureAwait(false); _hotkeyDocument = document; await ApplyIdleInteractableOverlaysAsync(cancellationToken).ConfigureAwait(false); await _hotkeys.ReplaceBindingsAsync(document.Bindings, cancellationToken).ConfigureAwait(false); await _events.PublishAsync(new RuntimeEvent { Name = "hotkeys.changed", Payload = BuildHotkeyStatuses() }, cancellationToken).ConfigureAwait(false); return OperationResult.Success(document); } finally { _lock.Release(); } } public async Task> RestoreDefaultHotkeysAsync(CancellationToken cancellationToken = default) { var restored = HotkeysValidator.RestoreBuiltins(_hotkeyDocument); return await SaveHotkeysAsync(restored, cancellationToken).ConfigureAwait(false); } public Task PauseHotkeyRegistrationAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); _hotkeys.Pause(); return Task.CompletedTask; } public Task ResumeHotkeyRegistrationAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); _hotkeys.Resume(); return Task.CompletedTask; } private async Task> UpdateRuntimeFlagAsync( string eventName, Action update, Func applySurfaces, CancellationToken cancellationToken) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { update(); await SaveRuntimeSettingsAsync(cancellationToken).ConfigureAwait(false); await applySurfaces().ConfigureAwait(false); var state = BuildState(); await _events.PublishAsync(new RuntimeEvent { Name = eventName, Payload = state }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false); return OperationResult.Success(state); } finally { _lock.Release(); } } private async Task> MutateWidgetSessionAsync( WidgetInstanceId instanceId, Func update, string eventName, CancellationToken cancellationToken) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { var layout = _layout.Get(instanceId); if (layout is null) { return OperationResult.Failure("WidgetNotFound", $"Widget '{instanceId.Value}' was not found."); } var overlay = update(layout, GetSession(instanceId)); _sessions[instanceId] = overlay; await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false); var runtimeState = ToWidgetRuntimeState(layout); await _events.PublishAsync(new RuntimeEvent { Name = eventName, Payload = runtimeState }, cancellationToken).ConfigureAwait(false); await PublishStatusAsync(BuildState(), cancellationToken).ConfigureAwait(false); return OperationResult.Success(runtimeState); } finally { _lock.Release(); } } private async Task>> MutatePluginWidgetSessionsAsync( PluginId pluginId, Func update, string eventName, CancellationToken cancellationToken) { await _lock.WaitAsync(cancellationToken).ConfigureAwait(false); try { var layouts = _layout.GetAll() .Where(layout => layout.PluginId.Equals(pluginId)) .ToArray(); if (layouts.Length == 0) { return OperationResult>.Failure( "WidgetInstanceNotFound", $"No widget instances found for plugin '{pluginId.Value}'."); } var states = new List(layouts.Length); foreach (var layout in layouts) { cancellationToken.ThrowIfCancellationRequested(); var overlay = update(layout, GetSession(layout.InstanceId)); _sessions[layout.InstanceId] = overlay; await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false); var runtimeState = ToWidgetRuntimeState(layout); states.Add(runtimeState); await _events.PublishAsync(new RuntimeEvent { Name = eventName, Payload = runtimeState }, cancellationToken).ConfigureAwait(false); } await PublishStatusAsync(BuildState(), cancellationToken).ConfigureAwait(false); return OperationResult>.Success(states); } finally { _lock.Release(); } } private WidgetSessionOverlay GetSession(WidgetInstanceId instanceId) => _sessions.TryGetValue(instanceId, out var overlay) ? overlay : WidgetSessionOverlay.Empty; private void ReconcileCurrentMonitors() { var monitors = _interop.GetMonitors(); _layout.ReconcileMonitors(monitors); } private async Task SaveRuntimeSettingsAsync(CancellationToken cancellationToken) { _settings = _settings with { Runtime = _settings.Runtime with { EditMode = _isEditMode, SafeInputMode = _isSafeInputMode } }; await _configuration.SaveAppSettingsAsync(_settings, cancellationToken).ConfigureAwait(false); } private async Task ApplyAllWidgetLayoutsAsync(CancellationToken cancellationToken) { foreach (var layout in _layout.GetAll()) { cancellationToken.ThrowIfCancellationRequested(); await _surfaces.ApplyWidgetLayoutAsync(ToSurfaceLayout(layout), cancellationToken).ConfigureAwait(false); } } private AppRuntimeState BuildState() { return new AppRuntimeState { IsEditMode = _isEditMode, IsGlobalLocked = _isGlobalLocked, IsSafeInputMode = _isSafeInputMode, Wallpaper = _wallpaper, Plugins = [.. _pluginSnapshot.Select(ToPluginRuntimeState)], Widgets = [.. _layout.GetAll().Select(ToWidgetRuntimeState)], Diagnostics = _diagnostics.Snapshot() }; } private async Task PublishStatusAsync(AppRuntimeState state, CancellationToken cancellationToken) { await _events.PublishAsync(new RuntimeEvent { Name = "app.statusChanged", Payload = state }, cancellationToken).ConfigureAwait(false); } private PluginRuntimeState ToPluginRuntimeState(PluginDescriptor plugin) => new() { Id = plugin.Id, Name = plugin.Manifest.Name, Type = plugin.Type, State = plugin.State, ErrorCode = plugin.ErrorCode, Entry = plugin.EntryUri.ToString() }; private WidgetRuntimeState ToWidgetRuntimeState(WidgetLayout layout) { var overlay = GetSession(layout.InstanceId); return new WidgetRuntimeState { InstanceId = layout.InstanceId, PluginId = layout.PluginId, Bounds = layout.Bounds, MonitorId = layout.MonitorId, IsVisible = WidgetSurfaceRules.ComputeVisible(overlay, layout.IsVisible), LayoutIsVisible = layout.IsVisible, IsLocked = _isGlobalLocked || layout.IsLocked, Opacity = layout.Opacity, ClickThrough = WidgetSurfaceRules.ComputeClickThrough(_isEditMode, _isSafeInputMode, overlay, layout.ClickThrough), LayoutClickThrough = layout.ClickThrough, IsInteractable = overlay.Interactable == true, HasSessionInteractable = overlay.HasInteractableOverride, DisplayLayer = layout.DisplayLayer }; } private WidgetLayout ToSurfaceLayout(WidgetLayout layout) => _isGlobalLocked ? layout with { IsLocked = true } : layout; private static bool IsGeometryPatch(WidgetLayoutPatch patch) => patch.Bounds is not null || patch.MonitorId is not null || patch.Scale is not null; private async Task OnHotkeyPressedAsync(HotkeyBinding binding) { if (Interlocked.CompareExchange(ref _hotkeyDispatching, 1, 0) != 0) { _diagnostics.Record( DiagnosticSeverity.Info, DiagnosticCodes.HotkeyDropped, "Dropped hotkey because a previous action is still running.", new Dictionary { ["id"] = binding.Id, ["keys"] = binding.Keys }); return; } try { await DispatchHotkeyActionAsync(binding).ConfigureAwait(false); } catch (Exception ex) { _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.Win32InteropFailed, "Hotkey dispatch failed.", new Dictionary { ["id"] = binding.Id, ["exception"] = ex.GetType().Name }); } finally { Interlocked.Exchange(ref _hotkeyDispatching, 0); } } private async Task DispatchHotkeyActionAsync(HotkeyBinding binding) { if (string.Equals(binding.Action, HotkeyActions.RuntimeToggleEditMode, StringComparison.OrdinalIgnoreCase)) { var state = await GetStateAsync().ConfigureAwait(false); await SetEditModeAsync(!state.IsEditMode).ConfigureAwait(false); return; } if (string.Equals(binding.Action, HotkeyActions.RuntimeToggleSafeInputMode, StringComparison.OrdinalIgnoreCase)) { var state = await GetStateAsync().ConfigureAwait(false); await SetSafeInputModeAsync(!state.IsSafeInputMode).ConfigureAwait(false); return; } if (string.Equals(binding.Action, HotkeyActions.WidgetToggleInteractable, StringComparison.OrdinalIgnoreCase)) { await DispatchWidgetHotkeyAsync( binding, ToggleWidgetInteractableAsync, TogglePluginWidgetsInteractableAsync).ConfigureAwait(false); return; } if (string.Equals(binding.Action, HotkeyActions.WidgetToggleVisible, StringComparison.OrdinalIgnoreCase)) { await DispatchWidgetHotkeyAsync( binding, ToggleWidgetSessionVisibleAsync, TogglePluginWidgetsSessionVisibleAsync).ConfigureAwait(false); return; } _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.HotkeyUnknownAction, $"Unknown hotkey action '{binding.Action}'.", new Dictionary { ["id"] = binding.Id, ["action"] = binding.Action }); } private async Task DispatchWidgetHotkeyAsync( HotkeyBinding binding, Func>> instanceAction, Func>>> pluginAction) { if (!string.IsNullOrWhiteSpace(binding.Target?.InstanceId)) { var instanceId = new WidgetInstanceId(binding.Target.InstanceId); var result = await instanceAction(instanceId, CancellationToken.None).ConfigureAwait(false); if (!result.Succeeded) { RecordInvalidTarget(binding, result.Message); } return; } if (!string.IsNullOrWhiteSpace(binding.Target?.PluginId)) { var pluginId = new PluginId(binding.Target.PluginId); if (!IsPluginAvailable(pluginId)) { RecordInvalidTarget(binding, $"Plugin '{pluginId.Value}' is not available."); return; } var result = await pluginAction(pluginId, CancellationToken.None).ConfigureAwait(false); if (!result.Succeeded) { RecordInvalidTarget(binding, result.Message); } return; } RecordInvalidTarget(binding, "Hotkey target is empty."); } private void RecordInvalidTarget(HotkeyBinding binding, string? message) { _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.HotkeyInvalidTarget, message ?? "Hotkey target is invalid.", new Dictionary { ["id"] = binding.Id, ["action"] = binding.Action, ["pluginId"] = binding.Target?.PluginId ?? "", ["instanceId"] = binding.Target?.InstanceId ?? "" }); } private async Task SyncSessionInteractableToLayoutClickThroughAsync( WidgetLayout layout, CancellationToken cancellationToken) { var overlay = GetSession(layout.InstanceId); if (!overlay.HasInteractableOverride) { return; } overlay = overlay with { Interactable = !layout.ClickThrough }; _sessions[layout.InstanceId] = overlay; await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false); } private async Task ApplyIdleInteractableOverlaysAsync(CancellationToken cancellationToken) { foreach (var binding in _hotkeyDocument.Bindings.Where(binding => binding.Enabled && string.Equals(binding.Action, HotkeyActions.WidgetToggleInteractable, StringComparison.OrdinalIgnoreCase))) { foreach (var layout in ResolveHotkeyTargets(binding.Target)) { cancellationToken.ThrowIfCancellationRequested(); var overlay = GetSession(layout.InstanceId); if (overlay.HasInteractableOverride) { continue; } overlay = overlay with { Interactable = false }; _sessions[layout.InstanceId] = overlay; await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false); } } } private IEnumerable ResolveHotkeyTargets(HotkeyTarget? target) { if (target is null || target.IsEmpty) { return []; } var layouts = _layout.GetAll(); if (!string.IsNullOrWhiteSpace(target.InstanceId)) { return layouts.Where(layout => layout.InstanceId.Value.Equals(target.InstanceId, StringComparison.OrdinalIgnoreCase)); } return layouts.Where(layout => layout.PluginId.Value.Equals(target.PluginId, StringComparison.OrdinalIgnoreCase)); } private IReadOnlyList BuildHotkeyStatuses() { var registrations = _hotkeys.Registrations.ToDictionary(item => item.BindingId, StringComparer.OrdinalIgnoreCase); var statuses = new List(_hotkeyDocument.Bindings.Count); foreach (var binding in _hotkeyDocument.Bindings) { var status = "registered"; string? detail = null; if (!binding.Enabled) { status = "disabled"; } else if (registrations.TryGetValue(binding.Id, out var registration)) { status = registration.State switch { HotkeyRegistrationState.Conflict => "conflict", HotkeyRegistrationState.Disabled => "disabled", HotkeyRegistrationState.Invalid => "conflict", _ => "registered" }; detail = registration.Detail; } if (status == "registered" && IsWidgetHotkey(binding.Action) && !HasValidTarget(binding.Target)) { status = "invalid-target"; } statuses.Add(new HotkeyBindingStatus { Binding = binding, Status = status, Detail = detail }); } return statuses; } private static bool IsWidgetHotkey(string action) => string.Equals(action, HotkeyActions.WidgetToggleInteractable, StringComparison.OrdinalIgnoreCase) || string.Equals(action, HotkeyActions.WidgetToggleVisible, StringComparison.OrdinalIgnoreCase); private bool HasValidTarget(HotkeyTarget? target) { if (target is null || target.IsEmpty) { return false; } if (!string.IsNullOrWhiteSpace(target.InstanceId)) { return _layout.Get(new WidgetInstanceId(target.InstanceId)) is not null; } var pluginId = new PluginId(target.PluginId!); return IsPluginAvailable(pluginId) && ResolveHotkeyTargets(target).Any(); } private bool IsPluginAvailable(PluginId pluginId) { var plugin = _pluginSnapshot.FirstOrDefault(item => item.Id.Equals(pluginId)); return plugin is not null && plugin.State is not PluginState.Disabled and not PluginState.Invalid and not PluginState.Removed and not PluginState.Error; } private static OperationResult ValidateHotkeysDocument(HotkeysDocument document) { var validation = HotkeysValidator.Validate(document); if (!validation.Succeeded) { return validation; } if (document.Bindings.All(binding => !string.Equals(binding.Id, HotkeysDocument.BuiltinPaletteToggleId, StringComparison.OrdinalIgnoreCase))) { return OperationResult.Failure("HotkeyBuiltinDeleteForbidden", "Built-in hotkeys cannot be deleted."); } return OperationResult.Success(); } }