using System.IO; using System.Text.Encodings.Web; using System.Text.Json; 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; /// WebView2-backed plugin host with bridge injection and lifecycle dispatch. 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 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 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); Control.CoreWebView2.Settings.AreDevToolsEnabled = options.AreDevToolsEnabled; Control.CoreWebView2.IsMuted = options.IsMuted; Control.CoreWebView2.WebMessageReceived += OnWebMessageReceived; Control.NavigationCompleted += OnNavigationCompleted; 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 { ["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() { if (Control.CoreWebView2 is not null) { Control.CoreWebView2.WebMessageReceived -= OnWebMessageReceived; } Control.NavigationCompleted -= OnNavigationCompleted; Control.Dispose(); await Task.CompletedTask; } 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 { ["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 EnsureInitialized() { if (!_initialized || Control.CoreWebView2 is null || _options is null) { throw new InvalidOperationException("WebView host has not been initialized."); } } }