基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-02 690cf73d6100e93d6ae7ca95dededbad4e40eeed
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
using System.Windows;
using System.Windows.Threading;
using Moli.Desktop.Api;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using MessageBox = System.Windows.MessageBox;
 
namespace Moli.Desktop.Management;
 
public partial class ManagementWindow : Window
{
    private readonly IDesktopRuntime _runtime;
    private readonly IDiagnosticsService _diagnostics;
    private readonly ILocalApiStatus _apiStatus;
    private readonly DispatcherTimer _timer;
    private AppRuntimeState? _state;
 
    public ManagementWindow(
        IDesktopRuntime runtime,
        IDiagnosticsService diagnostics,
        ILocalApiStatus apiStatus)
    {
        _runtime = runtime;
        _diagnostics = diagnostics;
        _apiStatus = apiStatus;
        InitializeComponent();
        _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()
    {
        _state = await _runtime.GetStateAsync();
        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;
        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);
    }
 
    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 ToggleWidgetVisible_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget)
        {
            return;
        }
 
        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsVisible = !widget.IsVisible });
    }
 
    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 ResetLayout_Click(object sender, RoutedEventArgs e)
    {
        if (_state is null)
        {
            return;
        }
 
        foreach (var widget in _state.Widgets)
        {
            await _runtime.UpdateWidgetLayoutAsync(
                widget.InstanceId,
                new WidgetLayoutPatch
                {
                    IsVisible = true,
                    IsLocked = false,
                    Opacity = 1,
                    ClickThrough = true
                });
        }
 
        await RefreshAsync();
    }
 
    private WidgetRow? SelectedWidget() => WidgetSelector.SelectedItem as WidgetRow;
 
    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 sealed record WidgetRow(string InstanceId, string PluginId, string Bounds, string MonitorId, bool IsVisible, bool IsLocked, double Opacity, bool ClickThrough)
    {
        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.IsLocked,
                state.Opacity,
                state.ClickThrough);
    }
 
    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);
    }
}