基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 574a6a769115034f37bdecf3284545d74843816a
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
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Windows;
using System.Drawing;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
 
namespace Moli.Desktop.WebView;
 
/// <summary>WebView2-backed plugin host with bridge injection and lifecycle dispatch.</summary>
public sealed class WebViewHost : IWebViewHost
{
    private readonly PluginDescriptor _plugin;
    private readonly IDiagnosticsService _diagnostics;
    private readonly IRuntimeEventBus _events;
    private readonly PluginBridgeDispatcher _bridgeDispatcher;
    private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web)
    {
        Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
    };
    private PluginBridgeContext? _bridgeContext;
    private WebViewHostOptions? _options;
    private IDisposable? _audioSubscription;
    private IDisposable? _llmSubscription;
    private bool _initialized;
 
    public WebViewHost(
        PluginDescriptor plugin,
        IDiagnosticsService diagnostics,
        IRuntimeEventBus events,
        PluginBridgeDispatcher bridgeDispatcher)
    {
        _plugin = plugin;
        _diagnostics = diagnostics;
        _events = events;
        _bridgeDispatcher = bridgeDispatcher;
        Control = new WebView2();
    }
 
    public WebView2 Control { get; }
    public FrameworkElement View => Control;
    public string HostId { get; } = $"webview-{Guid.NewGuid():N}";
    public PluginId PluginId => _plugin.Id;
    public PluginType PluginType => _plugin.Type;
 
    public async Task InitializeAsync(WebViewHostOptions options, CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        _options = options;
        Directory.CreateDirectory(options.UserDataFolder);
        var environment = await CoreWebView2Environment.CreateAsync(null, options.UserDataFolder).ConfigureAwait(true);
        await Control.EnsureCoreWebView2Async(environment).ConfigureAwait(true);
        if (options.IsTransparent)
        {
            Control.DefaultBackgroundColor = Color.Transparent;
        }
 
        Control.CoreWebView2.Settings.AreDevToolsEnabled = options.AreDevToolsEnabled;
        Control.CoreWebView2.IsMuted = options.IsMuted;
        Control.CoreWebView2.WebMessageReceived += OnWebMessageReceived;
        Control.CoreWebView2.ScreenCaptureStarting += OnScreenCaptureStarting;
        Control.NavigationCompleted += OnNavigationCompleted;
        if (HasPermission("audio-capture"))
        {
            _audioSubscription = _events.Subscribe(DispatchAudioSpectrumAsync);
        }
 
        _llmSubscription = _events.Subscribe(DispatchLlmEventAsync);
 
        if (!string.IsNullOrWhiteSpace(options.InitialScript))
        {
            await Control.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(options.InitialScript).ConfigureAwait(true);
        }
 
        _initialized = true;
        _diagnostics.Record(
            DiagnosticSeverity.Info,
            DiagnosticCodes.WebViewHostInitialized,
            "WebView host initialized.",
            new Dictionary<string, string> { ["hostId"] = HostId, ["pluginId"] = PluginId.Value });
    }
 
    public async Task NavigateAsync(Uri entryUri, CancellationToken cancellationToken = default)
    {
        EnsureInitialized();
        cancellationToken.ThrowIfCancellationRequested();
        var uri = entryUri.IsFile ? entryUri.AbsoluteUri : entryUri.ToString();
        Control.CoreWebView2.Navigate(uri);
        await _events.PublishAsync(new RuntimeEvent
        {
            Name = "webview.navigationStarted",
            Payload = new { HostId, PluginId = PluginId.Value, Uri = uri }
        }, cancellationToken).ConfigureAwait(false);
    }
 
    public async Task InjectBridgeAsync(PluginBridgeContext context, CancellationToken cancellationToken = default)
    {
        EnsureInitialized();
        cancellationToken.ThrowIfCancellationRequested();
        _bridgeContext = context with { HostId = HostId };
        await Control.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(PluginBridgeScript.Build()).ConfigureAwait(true);
    }
 
    public async Task DispatchLifecycleEventAsync(string eventName, object? payload, CancellationToken cancellationToken = default)
    {
        EnsureInitialized();
        cancellationToken.ThrowIfCancellationRequested();
        var script = $"window.dispatchEvent(new CustomEvent({JsonSerializer.Serialize(eventName, _jsonOptions)}, {{ detail: {JsonSerializer.Serialize(payload, _jsonOptions)} }}));";
        await Control.ExecuteScriptAsync(script).ConfigureAwait(true);
        await _events.PublishAsync(new RuntimeEvent
        {
            Name = $"webview.lifecycle.{eventName}",
            Payload = new { HostId, PluginId = PluginId.Value, Payload = payload }
        }, cancellationToken).ConfigureAwait(false);
    }
 
    public Task ReloadAsync(CancellationToken cancellationToken = default)
    {
        EnsureInitialized();
        cancellationToken.ThrowIfCancellationRequested();
        Control.Reload();
        return Task.CompletedTask;
    }
 
    public async ValueTask DisposeAsync()
    {
        _audioSubscription?.Dispose();
        _audioSubscription = null;
        _llmSubscription?.Dispose();
        _llmSubscription = null;
 
        if (Control.CoreWebView2 is not null)
        {
            Control.CoreWebView2.WebMessageReceived -= OnWebMessageReceived;
            Control.CoreWebView2.ScreenCaptureStarting -= OnScreenCaptureStarting;
        }
 
        Control.NavigationCompleted -= OnNavigationCompleted;
        Control.Dispose();
        await Task.CompletedTask;
    }
 
    private Task DispatchAudioSpectrumAsync(RuntimeEvent runtimeEvent)
    {
        if (runtimeEvent.Name != "audio.spectrum" || runtimeEvent.Payload is null)
        {
            return Task.CompletedTask;
        }
 
        var detail = JsonSerializer.Serialize(runtimeEvent.Payload, _jsonOptions);
        var script = $"window.dispatchEvent(new CustomEvent(\"moli:audio-spectrum\", {{ detail: {detail} }}));";
        var dispatcher = Control.Dispatcher;
        if (dispatcher.CheckAccess())
        {
            return ExecuteScriptSafelyAsync(script);
        }
 
        return dispatcher.InvokeAsync(() => ExecuteScriptSafelyAsync(script)).Task.Unwrap();
    }
 
    private Task DispatchLlmEventAsync(RuntimeEvent runtimeEvent)
    {
        if (_bridgeContext is null || runtimeEvent.Payload is null || !runtimeEvent.Name.StartsWith("llm.", StringComparison.OrdinalIgnoreCase))
        {
            return Task.CompletedTask;
        }
 
        var payloadJson = JsonSerializer.Serialize(runtimeEvent.Payload, _jsonOptions);
        using var document = JsonDocument.Parse(payloadJson);
        var root = document.RootElement;
        if (!root.TryGetProperty("hostId", out var hostId) ||
            !string.Equals(hostId.GetString(), HostId, StringComparison.OrdinalIgnoreCase) ||
            !root.TryGetProperty("event", out var llmEvent))
        {
            return Task.CompletedTask;
        }
 
        var domEventName = runtimeEvent.Name switch
        {
            "llm.delta" => "moli:llm-delta",
            "llm.completed" => "moli:llm-completed",
            "llm.error" => "moli:llm-error",
            _ => "moli:llm-event"
        };
        var detail = llmEvent.GetRawText();
        var script = $"window.dispatchEvent(new CustomEvent(\"{domEventName}\", {{ detail: {detail} }}));";
        var dispatcher = Control.Dispatcher;
        if (dispatcher.CheckAccess())
        {
            return ExecuteScriptSafelyAsync(script);
        }
 
        return dispatcher.InvokeAsync(() => ExecuteScriptSafelyAsync(script)).Task.Unwrap();
    }
 
    private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
    {
        if (_bridgeContext is null)
        {
            return;
        }
 
        var response = await _bridgeDispatcher.DispatchAsync(e.WebMessageAsJson, _bridgeContext).ConfigureAwait(true);
        var detail = JsonSerializer.Serialize(response, _jsonOptions);
        await Control.ExecuteScriptAsync($"window.dispatchEvent(new CustomEvent(\"moliDesktopResponse\", {{ detail: {detail} }}));").ConfigureAwait(true);
    }
 
    private async void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
    {
        if (e.IsSuccess)
        {
            await _events.PublishAsync(new RuntimeEvent
            {
                Name = "webview.navigationCompleted",
                Payload = new { HostId, PluginId = PluginId.Value }
            }).ConfigureAwait(false);
            return;
        }
 
        _diagnostics.Record(
            DiagnosticSeverity.Error,
            DiagnosticCodes.WebViewNavigationFailed,
            "WebView navigation failed.",
            new Dictionary<string, string>
            {
                ["hostId"] = HostId,
                ["pluginId"] = PluginId.Value,
                ["status"] = e.WebErrorStatus.ToString()
            });
 
        await _events.PublishAsync(new RuntimeEvent
        {
            Name = "webview.navigationFailed",
            Payload = new { HostId, PluginId = PluginId.Value, Status = e.WebErrorStatus.ToString() }
        }).ConfigureAwait(false);
    }
 
    private void OnScreenCaptureStarting(object? sender, CoreWebView2ScreenCaptureStartingEventArgs e)
    {
        e.Cancel = true;
        e.Handled = true;
        _diagnostics.Record(
            DiagnosticSeverity.Info,
            "WebViewScreenCaptureBlocked",
            "WebView screen capture request was blocked.",
            new Dictionary<string, string> { ["hostId"] = HostId, ["pluginId"] = PluginId.Value });
    }
 
    private async Task ExecuteScriptSafelyAsync(string script)
    {
        if (!_initialized || Control.CoreWebView2 is null)
        {
            return;
        }
 
        try
        {
            await Control.ExecuteScriptAsync(script).ConfigureAwait(true);
        }
        catch (InvalidOperationException)
        {
        }
    }
 
    private bool HasPermission(string permission)
        => _plugin.Manifest.Permissions.Any(item => string.Equals(item, permission, StringComparison.OrdinalIgnoreCase));
 
    private void EnsureInitialized()
    {
        if (!_initialized || Control.CoreWebView2 is null || _options is null)
        {
            throw new InvalidOperationException("WebView host has not been initialized.");
        }
    }
}