基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-17 9b5711d3124622b1f1b18500d442c76492da877a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Moli.Desktop.Api;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Hotkeys;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using Microsoft.Win32;
using MessageBox = System.Windows.MessageBox;
using WpfButton = System.Windows.Controls.Button;
using WpfTextBox = System.Windows.Controls.TextBox;
using WpfComboBox = System.Windows.Controls.ComboBox;
using WpfCheckBox = System.Windows.Controls.CheckBox;
 
namespace Moli.Desktop.Management;
 
public partial class ManagementWindow : Window
{
    private readonly IDesktopRuntime _runtime;
    private readonly IDiagnosticsService _diagnostics;
    private readonly ILocalApiStatus _apiStatus;
    private readonly IPluginManager _plugins;
    private readonly DesktopPaths _paths;
    private readonly DispatcherTimer _timer;
    private AppRuntimeState? _state;
    private IReadOnlyList<HotkeyBindingStatus> _hotkeys = [];
    private string? _selectedWidgetForDisplayLayer;
    private bool _isRefreshing;
 
    public ManagementWindow(
        IDesktopRuntime runtime,
        IDiagnosticsService diagnostics,
        ILocalApiStatus apiStatus,
        IPluginManager plugins,
        DesktopPaths paths)
    {
        _runtime = runtime;
        _diagnostics = diagnostics;
        _apiStatus = apiStatus;
        _plugins = plugins;
        _paths = paths;
        InitializeComponent();
        DisplayLayerSelector.ItemsSource = Enum.GetValues<DisplayLayer>();
        WidgetSelector.SelectionChanged += WidgetSelector_SelectionChanged;
        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
        _timer.Tick += async (_, _) => await RefreshAsync();
        Loaded += async (_, _) =>
        {
            _timer.Start();
            await RefreshAsync();
        };
        Closed += (_, _) => _timer.Stop();
    }
 
    private async Task RefreshAsync()
    {
        _isRefreshing = true;
        try
        {
            _state = await _runtime.GetStateAsync();
            _hotkeys = await _runtime.GetHotkeyStatusesAsync();
            var api = _apiStatus.GetStatus();
            var diagnostics = _diagnostics.Snapshot().OrderByDescending(entry => entry.Timestamp).ToArray();
            var webViewStatus = diagnostics.FirstOrDefault(entry => entry.Code == DiagnosticCodes.WebViewHostInitialized) is null
                ? "未检测到初始化记录"
                : "已初始化";
 
            StatusSummaryText.Text = $"插件 {_state.Plugins.Count} 个,组件 {_state.Widgets.Count} 个,诊断 {diagnostics.Length} 条";
            RuntimeText.Text = $"运行时:编辑={_state.IsEditMode},安全输入={_state.IsSafeInputMode},全局锁定={_state.IsGlobalLocked}";
            ApiText.Text = api.IsListening ? $"API:127.0.0.1:{api.Port}" : $"API:未监听 {api.ErrorCode ?? ""}";
            WallpaperText.Text = $"壁纸:启用={_state.Wallpaper.IsEnabled},插件={_state.Wallpaper.PluginId?.Value ?? "无"}";
            WebViewText.Text = $"WebView2:{webViewStatus}";
            WallpaperDetailText.Text = $"启用:{_state.Wallpaper.IsEnabled}\n暂停:{_state.Wallpaper.IsPaused}\n静音:{_state.Wallpaper.IsMuted}\n透明度:{_state.Wallpaper.Opacity}\n点击穿透:{_state.Wallpaper.ClickThrough}";
            EditModeButton.Content = _state.IsEditMode ? "退出编辑" : "进入编辑";
            SafeInputButton.Content = _state.IsSafeInputMode ? "退出安全" : "安全输入";
            GlobalLockButton.Content = _state.IsGlobalLocked ? "解锁全部" : "锁定全部";
 
            var widgets = _state.Widgets.Select(WidgetRow.From).ToArray();
            var selected = (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId;
            WidgetSelector.ItemsSource = widgets;
            WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault();
            WidgetsGrid.ItemsSource = widgets;
            HotkeysGrid.ItemsSource = _hotkeys.Select(HotkeyRow.From).ToArray();
            SyncDisplayLayerSelector(force: _selectedWidgetForDisplayLayer != (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId);
            PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray();
            DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray();
            RecentDiagnosticsGrid.ItemsSource = diagnostics.Take(8).Select(DiagnosticRow.From).ToArray();
            ManifestErrorsText.Text = BuildManifestErrorText(_state);
            LoadTodayLog();
        }
        finally
        {
            _isRefreshing = false;
        }
    }
 
    private async void RefreshButton_Click(object sender, RoutedEventArgs e) => await RefreshAsync();
    private async void EnableWallpaper_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.EnableWallpaperAsync());
    private async void DisableWallpaper_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.DisableWallpaperAsync());
    private async void ToggleEditMode_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetEditModeAsync(!(_state?.IsEditMode ?? false)));
    private async void ToggleSafeInput_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetSafeInputModeAsync(!(_state?.IsSafeInputMode ?? false)));
    private async void ToggleGlobalLock_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetGlobalLockedAsync(!(_state?.IsGlobalLocked ?? false)));
    private async void ReloadPlugins_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.ReloadPluginsAsync());
    private async void ApplyDisplayLayer_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget || DisplayLayerSelector.SelectedItem is not DisplayLayer layer)
        {
            return;
        }
 
        if (layer == DisplayLayer.GlobalTop)
        {
            var choice = MessageBox.Show(
                this,
                "全局置顶会让该组件覆盖其他应用窗口。确认继续?",
                "全局置顶",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning);
            if (choice != MessageBoxResult.Yes)
            {
                return;
            }
        }
 
        await _runtime.CancelPluginRequestsAsync(new PluginId(widget.PluginId));
        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { DisplayLayer = layer });
    }
 
    private async void ToggleWidgetVisible_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget)
        {
            return;
        }
 
        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsVisible = !widget.LayoutIsVisible });
    }
 
    private async void ToggleWidgetLocked_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget)
        {
            return;
        }
 
        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsLocked = !widget.IsLocked });
    }
 
    private async void ToggleWidgetClickThrough_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget)
        {
            return;
        }
 
        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { ClickThrough = !widget.ClickThrough });
    }
 
    private async void ResetLayout_Click(object sender, RoutedEventArgs e)
        => await ResetRuntimeLayoutAsync(confirm: false);
 
    private async void RestoreDefaults_Click(object sender, RoutedEventArgs e)
        => await ResetRuntimeLayoutAsync(confirm: true);
 
    private async Task ResetRuntimeLayoutAsync(bool confirm)
    {
        if (_state is null)
        {
            return;
        }
 
        if (confirm)
        {
            var choice = MessageBox.Show(
                this,
                "确认恢复默认布局和交互配置?此操作会显示并解锁组件,恢复透明度、点击穿透和默认显示层级。",
                "恢复默认",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning);
            if (choice != MessageBoxResult.Yes)
            {
                return;
            }
        }
 
        foreach (var widget in _state.Widgets)
        {
            var clickThrough = true;
            var displayLayer = DisplayLayer.Desktop;
            try
            {
                var plugin = await _plugins.GetAsync(widget.PluginId);
                if (plugin is not null)
                {
                    clickThrough = plugin.Manifest.DefaultLayout.ClickThrough;
                    displayLayer = plugin.Manifest.DefaultLayout.DisplayLayer;
                }
            }
            catch
            {
            }
 
            await _runtime.UpdateWidgetLayoutAsync(
                widget.InstanceId,
                new WidgetLayoutPatch
                {
                    IsVisible = true,
                    IsLocked = false,
                    Opacity = 1,
                    ClickThrough = clickThrough,
                    DisplayLayer = displayLayer
                });
        }
 
        await RefreshAsync();
    }
 
    private async void EditWidgetLayout_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget)
        {
            return;
        }
 
        var dialog = new WidgetLayoutDialog(widget) { Owner = this };
        if (dialog.ShowDialog() == true)
        {
            await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { Bounds = dialog.Bounds });
        }
    }
 
    private void OpenLayoutJson_Click(object sender, RoutedEventArgs e)
        => OpenJson(Path.Combine(_paths.ConfigDirectory, "layout.json"));
 
    private void OpenPluginsJson_Click(object sender, RoutedEventArgs e)
        => OpenJson(Path.Combine(_paths.ConfigDirectory, "plugins.json"));
 
    private void OpenLogDirectory_Click(object sender, RoutedEventArgs e)
    {
        Directory.CreateDirectory(_paths.LogDirectory);
        Process.Start(new ProcessStartInfo("explorer.exe", $"\"{_paths.LogDirectory}\"") { UseShellExecute = true });
    }
 
    private void OpenPluginJson_Click(object sender, RoutedEventArgs e)
    {
        if ((PluginsGrid.SelectedItem as PluginRow) is not { } plugin)
        {
            return;
        }
 
        OpenJson(Path.Combine(_paths.PluginDirectory, plugin.Id, "plugin.json"));
    }
 
    private async void ChooseWallpaperFile_Click(object sender, RoutedEventArgs e)
    {
        var dialog = new Microsoft.Win32.OpenFileDialog
        {
            Title = "选择壁纸文件",
            Filter = "壁纸文件|*.html;*.htm;*.png;*.jpg;*.jpeg;*.gif;*.svg|HTML|*.html;*.htm|图片|*.png;*.jpg;*.jpeg;*.gif;*.svg|所有文件|*.*"
        };
        if (dialog.ShowDialog(this) != true)
        {
            return;
        }
 
        await InstallWallpaperFilePluginAsync(dialog.FileName);
        await ExecuteAsync(() => _runtime.ReloadPluginsAsync());
        await ExecuteAsync(() => _runtime.EnableWallpaperAsync());
    }
 
    private WidgetRow? SelectedWidget() => WidgetSelector.SelectedItem as WidgetRow;
 
    private void WidgetSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (!_isRefreshing)
        {
            SyncDisplayLayerSelector(force: true);
        }
    }
 
    private void SyncDisplayLayerSelector(bool force)
    {
        if (SelectedWidget() is not { } widget)
        {
            DisplayLayerSelector.SelectedItem = DisplayLayer.Desktop;
            _selectedWidgetForDisplayLayer = null;
            ClickThroughButton.Content = "点击穿透";
            WidgetSessionText.Text = "选择一个组件后可查看本次会话可交互和有效穿透。";
            return;
        }
 
        ClickThroughButton.Content = widget.ClickThrough ? "关闭穿透" : "开启穿透";
        WidgetSessionText.Text = $"本次会话可交互:{(widget.IsInteractable ? "是" : "否")};有效穿透:{(widget.ClickThrough ? "是" : "否")}。点击穿透会写入 layout.json,并同步本次会话覆盖,使窗口立刻可点或穿透。";
 
        if (!force)
        {
            return;
        }
 
        DisplayLayerSelector.SelectedItem = widget.DisplayLayer;
        _selectedWidgetForDisplayLayer = widget.InstanceId;
    }
 
    private void LoadTodayLog()
    {
        var logPath = Path.Combine(_paths.LogDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log");
        LogPathText.Text = logPath;
        if (!File.Exists(logPath))
        {
            LogTextBox.Text = "当天暂无日志。";
            return;
        }
 
        try
        {
            var text = File.ReadAllText(logPath, Encoding.UTF8);
            if (LogTextBox.Text == text)
            {
                return;
            }
 
            var wasNearBottom = LogTextBox.VerticalOffset >= LogTextBox.ExtentHeight - LogTextBox.ViewportHeight - 24;
            LogTextBox.Text = text;
            if (wasNearBottom)
            {
                LogTextBox.ScrollToEnd();
            }
        }
        catch (IOException)
        {
        }
        catch (UnauthorizedAccessException)
        {
        }
    }
 
    private async Task InstallWallpaperFilePluginAsync(string fileName)
    {
        Directory.CreateDirectory(_paths.PluginDirectory);
        var pluginDirectory = Path.Combine(_paths.PluginDirectory, "user.wallpaper-file");
        Directory.CreateDirectory(pluginDirectory);
 
        var extension = Path.GetExtension(fileName).ToLowerInvariant();
        var uri = new Uri(fileName).AbsoluteUri;
        var body = extension switch
        {
            ".html" or ".htm" => $"<iframe src=\"{Html(uri)}\"></iframe>",
            ".svg" => $"<object data=\"{Html(uri)}\" type=\"image/svg+xml\"></object>",
            _ => $"<img src=\"{Html(uri)}\" alt=\"wallpaper\" />"
        };
        var indexHtml = $$"""
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #05070a; }
    img, object, iframe { width: 100vw; height: 100vh; border: 0; object-fit: cover; display: block; }
  </style>
</head>
<body>
  {{body}}
</body>
</html>
""";
        await File.WriteAllTextAsync(Path.Combine(pluginDirectory, "index.html"), indexHtml, new UTF8Encoding(false));
        var manifest = new
        {
            id = "user.wallpaper-file",
            name = "用户选择壁纸",
            version = "1.0.0",
            type = "wallpaper",
            entry = "index.html",
            description = $"Loaded from {Path.GetFileName(fileName)}.",
            author = "Moli.Desktop",
            permissions = Array.Empty<string>(),
            defaultLayout = new { width = 1920, height = 1080, x = 0, y = 0, locked = true, clickThrough = true, opacity = 1, scale = 1, displayLayer = "desktop" },
            config = new { sourceFile = fileName, sourceType = extension.TrimStart('.') }
        };
        await File.WriteAllTextAsync(
            Path.Combine(pluginDirectory, "plugin.json"),
            JsonSerializer.Serialize(manifest, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }),
            new UTF8Encoding(false));
 
        await PreferWallpaperPluginAsync("user.wallpaper-file");
    }
 
    private async Task PreferWallpaperPluginAsync(string pluginId)
    {
        var path = Path.Combine(_paths.ConfigDirectory, "plugins.json");
        if (!File.Exists(path))
        {
            return;
        }
 
        var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
        {
            Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
        };
        using var stream = File.OpenRead(path);
        var registry = await JsonSerializer.DeserializeAsync<PluginRegistryDocument>(stream, options);
        if (registry is null)
        {
            return;
        }
 
        registry.Plugins.RemoveAll(item => item.Id.Value is "sample.wallpaper" or "user.wallpaper-file");
        registry.Plugins.Insert(0, new PluginRegistryItem { Id = new PluginId(pluginId), State = PluginState.Enabled, UpdatedAt = DateTimeOffset.UtcNow });
        registry.Plugins.Add(new PluginRegistryItem { Id = new PluginId("sample.wallpaper"), State = PluginState.Disabled, UpdatedAt = DateTimeOffset.UtcNow });
        await File.WriteAllTextAsync(path, JsonSerializer.Serialize(registry, new JsonSerializerOptions(options) { WriteIndented = true }), new UTF8Encoding(false));
    }
 
    private void OpenJson(string path)
    {
        if (!File.Exists(path))
        {
            MessageBox.Show(this, $"文件不存在:{path}", "打开配置", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }
 
        Process.Start(new ProcessStartInfo("notepad.exe", $"\"{path}\"") { UseShellExecute = true });
    }
 
    private async Task ExecuteAsync(Func<Task<OperationResult<AppRuntimeState>>> command)
    {
        var result = await command();
        if (!result.Succeeded)
        {
            MessageBox.Show(this, result.Message ?? "命令执行失败。", result.ErrorCode ?? "RuntimeCommandFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
 
        await RefreshAsync();
    }
 
    private async Task ExecuteWidgetAsync(string instanceId, WidgetLayoutPatch patch)
    {
        var result = await _runtime.UpdateWidgetLayoutAsync(new WidgetInstanceId(instanceId), patch);
        if (!result.Succeeded)
        {
            MessageBox.Show(this, result.Message ?? "组件命令执行失败。", result.ErrorCode ?? "WidgetCommandFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
 
        await RefreshAsync();
    }
 
    private static string BuildManifestErrorText(AppRuntimeState state)
    {
        var errors = state.Plugins
            .Where(plugin => !string.IsNullOrWhiteSpace(plugin.ErrorCode))
            .Select(plugin => $"{plugin.Id.Value}: {plugin.ErrorCode}")
            .ToArray();
        return errors.Length == 0 ? "未发现插件 manifest 错误。" : string.Join(Environment.NewLine, errors);
    }
 
    private static string Html(string value) => System.Net.WebUtility.HtmlEncode(value);
 
    private sealed record WidgetRow(
        string InstanceId,
        string PluginId,
        string Bounds,
        string MonitorId,
        bool IsVisible,
        bool LayoutIsVisible,
        bool IsLocked,
        double Opacity,
        bool ClickThrough,
        bool LayoutClickThrough,
        bool IsInteractable,
        DisplayLayer DisplayLayer)
    {
        public static WidgetRow From(WidgetRuntimeState state)
            => new(
                state.InstanceId.Value,
                state.PluginId.Value,
                $"{state.Bounds.X:0},{state.Bounds.Y:0} {state.Bounds.Width:0}x{state.Bounds.Height:0}",
                state.MonitorId.Value,
                state.IsVisible,
                state.LayoutIsVisible,
                state.IsLocked,
                state.Opacity,
                state.ClickThrough,
                state.LayoutClickThrough,
                state.IsInteractable,
                state.DisplayLayer);
    }
 
    private async void AddHotkey_Click(object sender, RoutedEventArgs e)
        => await EditHotkeyAsync(null);
 
    private async void EditHotkey_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedHotkey() is not { } row)
        {
            return;
        }
 
        await EditHotkeyAsync(row);
    }
 
    private async void DeleteHotkey_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedHotkey() is not { } row)
        {
            return;
        }
 
        if (string.Equals(row.Source, "builtin", StringComparison.OrdinalIgnoreCase))
        {
            MessageBox.Show(this, "内置快捷键不能删除,只能改键、禁用或恢复默认。", "快捷键", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }
 
        var document = CurrentHotkeysDocument();
        document.Bindings.RemoveAll(binding => string.Equals(binding.Id, row.Id, StringComparison.OrdinalIgnoreCase));
        await SaveHotkeysDocumentAsync(document);
    }
 
    private async void ToggleHotkeyEnabled_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedHotkey() is not { } row)
        {
            return;
        }
 
        var document = CurrentHotkeysDocument();
        var index = document.Bindings.FindIndex(binding => string.Equals(binding.Id, row.Id, StringComparison.OrdinalIgnoreCase));
        if (index < 0)
        {
            return;
        }
 
        document.Bindings[index] = document.Bindings[index] with { Enabled = !document.Bindings[index].Enabled };
        await SaveHotkeysDocumentAsync(document);
    }
 
    private async void RestoreDefaultHotkeys_Click(object sender, RoutedEventArgs e)
    {
        var result = await _runtime.RestoreDefaultHotkeysAsync();
        if (!result.Succeeded)
        {
            MessageBox.Show(this, result.Message ?? "恢复默认快捷键失败。", result.ErrorCode ?? "HotkeyRestoreFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
 
        await RefreshAsync();
    }
 
    private HotkeyRow? SelectedHotkey() => HotkeysGrid.SelectedItem as HotkeyRow;
 
    private HotkeysDocument CurrentHotkeysDocument()
        => new()
        {
            SchemaVersion = 1,
            Bindings = [.. _hotkeys.Select(item => item.Binding)]
        };
 
    private async Task EditHotkeyAsync(HotkeyRow? existing)
    {
        var plugins = _state?.Plugins.Select(plugin => plugin.Id.Value).Distinct().ToArray() ?? [];
        var instances = _state?.Widgets.Select(widget => (widget.PluginId.Value, widget.InstanceId.Value)).ToArray() ?? [];
        var dialog = new HotkeyEditorDialog(existing?.ToBinding(), plugins, instances, PauseRecordingAsync, ResumeRecordingAsync)
        {
            Owner = this
        };
        if (dialog.ShowDialog() != true || dialog.Result is null)
        {
            return;
        }
 
        var document = CurrentHotkeysDocument();
        var index = document.Bindings.FindIndex(binding => string.Equals(binding.Id, dialog.Result.Id, StringComparison.OrdinalIgnoreCase));
        if (index >= 0)
        {
            document.Bindings[index] = dialog.Result;
        }
        else
        {
            document.Bindings.Add(dialog.Result);
        }
 
        await SaveHotkeysDocumentAsync(document);
    }
 
    private async Task SaveHotkeysDocumentAsync(HotkeysDocument document)
    {
        var result = await _runtime.SaveHotkeysAsync(document);
        if (!result.Succeeded)
        {
            MessageBox.Show(this, result.Message ?? "保存快捷键失败。", result.ErrorCode ?? "HotkeySaveFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
 
        await RefreshAsync();
    }
 
    private Task PauseRecordingAsync() => _runtime.PauseHotkeyRegistrationAsync();
 
    private Task ResumeRecordingAsync() => _runtime.ResumeHotkeyRegistrationAsync();
 
    private sealed record HotkeyRow(string Id, string Keys, string Action, string Target, bool Enabled, string Source, string Status)
    {
        public static HotkeyRow From(HotkeyBindingStatus status)
            => new(
                status.Binding.Id,
                status.Binding.Keys,
                status.Binding.Action,
                FormatTarget(status.Binding.Target),
                status.Binding.Enabled,
                status.Binding.Source.ToString().ToLowerInvariant(),
                status.Status);
 
        public HotkeyBinding ToBinding()
        {
            var parts = Target.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            string? pluginId = null;
            string? instanceId = null;
            foreach (var part in parts)
            {
                if (part.StartsWith("plugin:", StringComparison.OrdinalIgnoreCase))
                {
                    pluginId = part["plugin:".Length..];
                }
                else if (part.StartsWith("instance:", StringComparison.OrdinalIgnoreCase))
                {
                    instanceId = part["instance:".Length..];
                }
            }
 
            return new HotkeyBinding
            {
                Id = Id,
                Keys = Keys,
                Action = Action,
                Target = string.IsNullOrWhiteSpace(pluginId) && string.IsNullOrWhiteSpace(instanceId)
                    ? null
                    : new HotkeyTarget { PluginId = pluginId, InstanceId = instanceId },
                Enabled = Enabled,
                Source = string.Equals(Source, "builtin", StringComparison.OrdinalIgnoreCase) ? HotkeySource.Builtin : HotkeySource.User
            };
        }
 
        private static string FormatTarget(HotkeyTarget? target)
        {
            if (target is null || target.IsEmpty)
            {
                return "";
            }
 
            var plugin = string.IsNullOrWhiteSpace(target.PluginId) ? "" : $"plugin:{target.PluginId}";
            var instance = string.IsNullOrWhiteSpace(target.InstanceId) ? "" : $"instance:{target.InstanceId}";
            return string.Join(" ", new[] { plugin, instance }.Where(item => item.Length > 0));
        }
    }
 
    private sealed record PluginRow(string Id, string Name, string Type, string State, string? ErrorCode, string Entry)
    {
        public static PluginRow From(PluginRuntimeState state)
            => new(state.Id.Value, state.Name, state.Type.ToString(), state.State.ToString(), state.ErrorCode, state.Entry ?? "");
    }
 
    private sealed record DiagnosticRow(DateTimeOffset Timestamp, string Severity, string Code, string Message)
    {
        public static DiagnosticRow From(DiagnosticEntry entry)
            => new(entry.Timestamp, entry.Severity.ToString(), entry.Code, entry.Message);
    }
 
    private sealed class HotkeyEditorDialog : Window
    {
        private readonly WpfTextBox _keys;
        private readonly WpfComboBox _action;
        private readonly WpfComboBox _plugin;
        private readonly WpfComboBox _instance;
        private readonly WpfCheckBox _enabled;
        private readonly HotkeyBinding? _existing;
        private readonly Func<Task> _pauseAsync;
        private readonly Func<Task> _resumeAsync;
        private readonly (string PluginId, string InstanceId)[] _instances;
        private bool _recording;
 
        public HotkeyEditorDialog(
            HotkeyBinding? existing,
            IReadOnlyList<string> plugins,
            IReadOnlyList<(string PluginId, string InstanceId)> instances,
            Func<Task> pauseAsync,
            Func<Task> resumeAsync)
        {
            _existing = existing;
            _pauseAsync = pauseAsync;
            _resumeAsync = resumeAsync;
            _instances = instances.ToArray();
            Title = existing is null ? "新增快捷键" : "编辑快捷键";
            Width = 420;
            Height = 360;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            ResizeMode = ResizeMode.NoResize;
 
            _keys = new WpfTextBox { Text = existing?.Keys ?? "Ctrl+Shift+K", Margin = new Thickness(0, 0, 0, 8) };
            _action = new WpfComboBox
            {
                ItemsSource = HotkeyActions.All.ToArray(),
                SelectedItem = existing?.Action ?? HotkeyActions.WidgetToggleInteractable,
                Margin = new Thickness(0, 0, 0, 8)
            };
            _plugin = new WpfComboBox
            {
                ItemsSource = plugins.ToArray(),
                SelectedItem = existing?.Target?.PluginId ?? plugins.FirstOrDefault(),
                Margin = new Thickness(0, 0, 0, 8)
            };
            _instance = new WpfComboBox { Margin = new Thickness(0, 0, 0, 8) };
            _enabled = new WpfCheckBox { Content = "启用", IsChecked = existing?.Enabled ?? true, Margin = new Thickness(0, 0, 0, 8) };
            _plugin.SelectionChanged += (_, _) => RefreshInstances();
            RefreshInstances();
            if (!string.IsNullOrWhiteSpace(existing?.Target?.InstanceId))
            {
                _instance.SelectedItem = existing!.Target!.InstanceId;
            }
 
            var grid = new Grid { Margin = new Thickness(16) };
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(88) });
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            for (var i = 0; i < 7; i++)
            {
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            }
 
            AddRow(grid, 0, "快捷键", _keys);
            var record = new WpfButton { Content = "录制", Width = 72, HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Margin = new Thickness(0, 0, 0, 8) };
            record.Click += async (_, _) => await ToggleRecordingAsync(record);
            Grid.SetRow(record, 1);
            Grid.SetColumn(record, 1);
            grid.Children.Add(record);
            AddRow(grid, 2, "动作", _action);
            AddRow(grid, 3, "插件", _plugin);
            AddRow(grid, 4, "实例", _instance);
            Grid.SetRow(_enabled, 5);
            Grid.SetColumn(_enabled, 1);
            grid.Children.Add(_enabled);
 
            var buttons = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, Margin = new Thickness(0, 12, 0, 0) };
            var ok = new WpfButton { Content = "确定", Width = 72, Margin = new Thickness(0, 0, 8, 0) };
            var cancel = new WpfButton { Content = "取消", Width = 72 };
            ok.Click += async (_, _) =>
            {
                await StopRecordingAsync(record);
                if (TryBuild())
                {
                    DialogResult = true;
                }
            };
            cancel.Click += async (_, _) =>
            {
                await StopRecordingAsync(record);
                DialogResult = false;
            };
            buttons.Children.Add(ok);
            buttons.Children.Add(cancel);
            Grid.SetRow(buttons, 6);
            Grid.SetColumnSpan(buttons, 2);
            grid.Children.Add(buttons);
            Content = grid;
            PreviewKeyDown += OnPreviewKeyDown;
            Closed += async (_, _) => await StopRecordingAsync(record);
        }
 
        public HotkeyBinding? Result { get; private set; }
 
        private void RefreshInstances()
        {
            var pluginId = _plugin.SelectedItem as string;
            var items = new List<string> { "" };
            items.AddRange(_instances.Where(item => string.Equals(item.PluginId, pluginId, StringComparison.OrdinalIgnoreCase)).Select(item => item.InstanceId));
            _instance.ItemsSource = items;
            _instance.SelectedIndex = 0;
        }
 
        private async Task ToggleRecordingAsync(WpfButton button)
        {
            if (_recording)
            {
                await StopRecordingAsync(button);
                return;
            }
 
            _recording = true;
            button.Content = "停止";
            _keys.Text = "请按下组合键…";
            await _pauseAsync();
        }
 
        private async Task StopRecordingAsync(WpfButton button)
        {
            if (!_recording)
            {
                return;
            }
 
            _recording = false;
            button.Content = "录制";
            await _resumeAsync();
        }
 
        private void OnPreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (!_recording)
            {
                return;
            }
 
            e.Handled = true;
            var key = e.Key == System.Windows.Input.Key.System ? e.SystemKey : e.Key;
            if (key is System.Windows.Input.Key.LeftCtrl or System.Windows.Input.Key.RightCtrl
                or System.Windows.Input.Key.LeftShift or System.Windows.Input.Key.RightShift
                or System.Windows.Input.Key.LeftAlt or System.Windows.Input.Key.RightAlt
                or System.Windows.Input.Key.LWin or System.Windows.Input.Key.RWin)
            {
                return;
            }
 
            var modifiers = new List<string>();
            if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Control) != 0)
            {
                modifiers.Add("Ctrl");
            }
 
            if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Alt) != 0)
            {
                modifiers.Add("Alt");
            }
 
            if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Shift) != 0)
            {
                modifiers.Add("Shift");
            }
 
            if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Windows) != 0)
            {
                modifiers.Add("Win");
            }
 
            if (modifiers.Count == 0)
            {
                _keys.Text = "需要包含 Ctrl/Shift/Alt";
                return;
            }
 
            modifiers.Add(key.ToString());
            var chord = string.Join("+", modifiers);
            if (!HotkeyChord.TryParse(chord, out var parsed, out _))
            {
                _keys.Text = "组合键无效";
                return;
            }
 
            _keys.Text = parsed.Canonical;
        }
 
        private bool TryBuild()
        {
            if (!HotkeyChord.TryParse(_keys.Text, out var chord, out var errorCode))
            {
                MessageBox.Show(this, "请输入有效组合键,不能只按修饰键。", errorCode ?? "HotkeyInvalidKeys", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
 
            var action = _action.SelectedItem as string ?? HotkeyActions.WidgetToggleInteractable;
            var pluginId = _plugin.SelectedItem as string;
            var instanceId = _instance.SelectedItem as string;
            Result = new HotkeyBinding
            {
                Id = _existing?.Id ?? $"user-{Guid.NewGuid():N}"[..16],
                Keys = chord.Canonical,
                Action = action,
                Target = HotkeyActions.All.Contains(action) && (action.StartsWith("widget.", StringComparison.OrdinalIgnoreCase))
                    ? new HotkeyTarget { PluginId = pluginId, InstanceId = string.IsNullOrWhiteSpace(instanceId) ? null : instanceId }
                    : null,
                Enabled = _enabled.IsChecked == true,
                Source = _existing?.Source ?? HotkeySource.User
            };
            return true;
        }
 
        private static void AddRow(Grid grid, int row, string label, UIElement field)
        {
            var text = new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 8, 8) };
            Grid.SetRow(text, row);
            Grid.SetColumn(text, 0);
            Grid.SetRow(field, row);
            Grid.SetColumn(field, 1);
            grid.Children.Add(text);
            grid.Children.Add(field);
        }
    }
 
    private sealed class WidgetLayoutDialog : Window
    {
        private readonly WpfTextBox _x;
        private readonly WpfTextBox _y;
        private readonly WpfTextBox _width;
        private readonly WpfTextBox _height;
 
        public WidgetLayoutDialog(WidgetRow widget)
        {
            Title = "编辑位置/大小";
            Width = 320;
            Height = 230;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            ResizeMode = ResizeMode.NoResize;
            var parts = widget.Bounds.Replace("x", " ").Replace(",", " ").Split(' ', StringSplitOptions.RemoveEmptyEntries);
            _x = Box(parts.ElementAtOrDefault(0) ?? "0");
            _y = Box(parts.ElementAtOrDefault(1) ?? "0");
            _width = Box(parts.ElementAtOrDefault(2) ?? "320");
            _height = Box(parts.ElementAtOrDefault(3) ?? "160");
 
            var grid = new Grid { Margin = new Thickness(16) };
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(72) });
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            for (var i = 0; i < 5; i++)
            {
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            }
 
            AddRow(grid, 0, "X", _x);
            AddRow(grid, 1, "Y", _y);
            AddRow(grid, 2, "宽度", _width);
            AddRow(grid, 3, "高度", _height);
            var buttons = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, Margin = new Thickness(0, 12, 0, 0) };
            var ok = new WpfButton { Content = "确定", Width = 72, Margin = new Thickness(0, 0, 8, 0) };
            var cancel = new WpfButton { Content = "取消", Width = 72 };
            ok.Click += (_, _) =>
            {
                if (TryBuildBounds())
                {
                    DialogResult = true;
                }
            };
            cancel.Click += (_, _) => DialogResult = false;
            buttons.Children.Add(ok);
            buttons.Children.Add(cancel);
            Grid.SetRow(buttons, 4);
            Grid.SetColumnSpan(buttons, 2);
            grid.Children.Add(buttons);
            Content = grid;
        }
 
        public RectD Bounds { get; private set; }
 
        private bool TryBuildBounds()
        {
            if (double.TryParse(_x.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var x)
                && double.TryParse(_y.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var y)
                && double.TryParse(_width.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var width)
                && double.TryParse(_height.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var height))
            {
                Bounds = new RectD(x, y, width, height);
                return true;
            }
 
            MessageBox.Show(this, "请输入有效数字。", "编辑位置/大小", MessageBoxButton.OK, MessageBoxImage.Warning);
            return false;
        }
 
        private static WpfTextBox Box(string text) => new() { Text = text, Margin = new Thickness(0, 0, 0, 8) };
 
        private static void AddRow(Grid grid, int row, string label, WpfTextBox textBox)
        {
            var text = new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 8, 8) };
            Grid.SetRow(text, row);
            Grid.SetColumn(text, 0);
            Grid.SetRow(textBox, row);
            Grid.SetColumn(textBox, 1);
            grid.Children.Add(text);
            grid.Children.Add(textBox);
        }
    }
}