基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-05 4df6165fa93c7caeea86385312415e312de4d11f
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
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;
 
/// <summary>Creates and updates real WPF desktop surfaces for runtime commands.</summary>
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<WidgetInstanceId, WidgetWindow> _widgets = [];
    private WallpaperWindow? _wallpaper;
    private WallpaperRuntimeState _wallpaperState = new();
    private bool _editMode;
    private bool _safeInputMode;
    private IDisposable? _eventSubscription;
 
    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;
            _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<string, string> { ["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);
            }
 
            window.ApplyLayout(layout, _editMode, _safeInputMode);
        });
 
    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<string, string> { ["pluginId"] = wallpaper.PluginId.Value.Value });
                return;
            }
 
            _wallpaper?.Close();
            _wallpaperState = wallpaper;
            var monitor = _interop.GetMonitors().FirstOrDefault(monitor => monitor.IsPrimary) ?? _interop.GetMonitors().First();
            _wallpaper = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
            _wallpaper.Closed += (_, _) => _wallpaper = null;
            _wallpaper.Show();
            await _wallpaper.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
            _wallpaper.ApplyState(wallpaper, _safeInputMode);
            ReapplyDesktopWidgetLayers();
        });
 
    public Task DisableWallpaperAsync(CancellationToken cancellationToken = default)
        => OnUiThreadAsync(() =>
        {
            _wallpaperState = _wallpaperState with { IsEnabled = false };
            _wallpaper?.Close();
            _wallpaper = null;
            return Task.CompletedTask;
        });
 
    public Task ShutdownAsync(CancellationToken cancellationToken = default)
        => OnUiThreadAsync(() =>
        {
            foreach (var widget in _widgets.Values.ToArray())
            {
                widget.Close();
            }
 
            _widgets.Clear();
            _wallpaper?.Close();
            _wallpaper = null;
            _eventSubscription?.Dispose();
            _eventSubscription = null;
            return Task.CompletedTask;
        });
 
    private async Task CommitWidgetLayoutAsync(
        WidgetInstanceId instanceId,
        WidgetLayoutPatch patch,
        CancellationToken cancellationToken)
    {
        var runtime = _services.GetRequiredService<IDesktopRuntime>();
        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);
        }
    }
 
    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<string, string> { ["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<Task> 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);
    }
}