From 574a6a769115034f37bdecf3284545d74843816a Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期三, 12 八月 2026 15:21:41 +0800
Subject: [PATCH] 添加显示器切换兼容处理

---
 src/Moli.Desktop/WebView/WebViewHost.cs |  106 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 106 insertions(+), 0 deletions(-)

diff --git a/src/Moli.Desktop/WebView/WebViewHost.cs b/src/Moli.Desktop/WebView/WebViewHost.cs
index 357eb59..dd39b80 100644
--- a/src/Moli.Desktop/WebView/WebViewHost.cs
+++ b/src/Moli.Desktop/WebView/WebViewHost.cs
@@ -1,6 +1,8 @@
 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;
@@ -22,6 +24,8 @@
     };
     private PluginBridgeContext? _bridgeContext;
     private WebViewHostOptions? _options;
+    private IDisposable? _audioSubscription;
+    private IDisposable? _llmSubscription;
     private bool _initialized;
 
     public WebViewHost(
@@ -38,6 +42,7 @@
     }
 
     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;
@@ -49,10 +54,22 @@
         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))
         {
@@ -111,14 +128,73 @@
 
     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)
@@ -163,6 +239,36 @@
         }).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)

--
Gitblit v1.9.1