From ae7304f4ee418d517275c2ad3ead1e9ef1888510 Mon Sep 17 00:00:00 2001
From: Moli <13026959681@163.com>
Date: 星期六, 02 五月 2026 16:28:05 +0800
Subject: [PATCH] T07, T08
---
src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs | 48 ++
src/Moli.Desktop/WebView/IWebViewHost.cs | 16
src/Moli.Desktop/WebView/WebViewHostFactory.cs | 27 +
src/Moli.Desktop/WebView/WebViewHostOptions.cs | 10
samples/plugins/sample.webview-test/plugin.json | 22 +
src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs | 96 ++++
samples/plugins/sample.webview-test/index.html | 47 ++
src/Moli.Desktop/Interop/Win32InteropService.cs | 172 ++++++++
src/Moli.Desktop/Diagnostics/DiagnosticModels.cs | 5
src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs | 39 +
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs | 99 ++++
src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs | 143 +++++++
src/Moli.Desktop/WebView/WebViewHost.cs | 173 ++++++++
src/Moli.Desktop/WebView/IWebViewHostFactory.cs | 9
src/Moli.Desktop/WebView/PluginBridgeScript.cs | 40 ++
src/Moli.Desktop/Host/DesktopHostBuilder.cs | 7
src/Moli.Desktop/Interop/NativeMethods.cs | 115 +++++
src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs | 23 +
src/Moli.Desktop/Interop/DesktopLayerMode.cs | 8
src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs | 11
src/Moli.Desktop/Interop/IWin32InteropService.cs | 17
src/Moli.Desktop/WebView/PluginBridgeContext.cs | 21 +
22 files changed, 1,148 insertions(+), 0 deletions(-)
diff --git a/samples/plugins/sample.webview-test/index.html b/samples/plugins/sample.webview-test/index.html
new file mode 100644
index 0000000..a606231
--- /dev/null
+++ b/samples/plugins/sample.webview-test/index.html
@@ -0,0 +1,47 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>WebView Bridge Test</title>
+ <style>
+ html, body {
+ margin: 0;
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ color: #f4f7fb;
+ font: 14px/1.4 "Segoe UI", sans-serif;
+ }
+
+ body {
+ display: grid;
+ place-items: center;
+ background: rgba(24, 31, 42, 0.78);
+ }
+
+ main {
+ padding: 16px;
+ }
+ </style>
+</head>
+<body>
+ <main>
+ <strong id="status">Initializing bridge...</strong>
+ <div id="details"></div>
+ </main>
+ <script>
+ (async () => {
+ const status = document.getElementById("status");
+ const details = document.getElementById("details");
+ try {
+ const runtime = await window.moliDesktop.getRuntimeInfo();
+ status.textContent = "Bridge ready";
+ details.textContent = `${runtime.pluginId} / ${runtime.hostId}`;
+ } catch (error) {
+ status.textContent = "Bridge failed";
+ details.textContent = error && error.message ? error.message : String(error);
+ }
+ })();
+ </script>
+</body>
+</html>
diff --git a/samples/plugins/sample.webview-test/plugin.json b/samples/plugins/sample.webview-test/plugin.json
new file mode 100644
index 0000000..faa1fc1
--- /dev/null
+++ b/samples/plugins/sample.webview-test/plugin.json
@@ -0,0 +1,22 @@
+{
+ "id": "sample.webview-test",
+ "name": "WebView Bridge Test",
+ "version": "1.0.0",
+ "type": "widget",
+ "entry": "index.html",
+ "description": "Local HTML test plugin for WebView host bridge validation.",
+ "author": "Moli.Desktop",
+ "defaultLayout": {
+ "x": 120,
+ "y": 120,
+ "width": 360,
+ "height": 180,
+ "locked": false,
+ "clickThrough": false,
+ "opacity": 1.0,
+ "scale": 1.0
+ },
+ "config": {
+ "label": "bridge-ready"
+ }
+}
diff --git a/src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs b/src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs
new file mode 100644
index 0000000..069ee4c
--- /dev/null
+++ b/src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs
@@ -0,0 +1,39 @@
+using System.Windows;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Interop;
+
+namespace Moli.Desktop.Tests.Interop;
+
+public sealed class FakeWin32InteropService : IWin32InteropService
+{
+ public bool ClickThroughEnabled { get; private set; }
+ public bool ToolWindowEnabled { get; private set; }
+ public bool NoActivateEnabled { get; private set; }
+ public byte Opacity { get; private set; } = 255;
+ public DesktopLayerMode? LayerMode { get; private set; }
+
+ public IntPtr GetWindowHandle(Window window) => new(42);
+
+ public void SetClickThrough(IntPtr hwnd, bool enabled) => ClickThroughEnabled = enabled;
+
+ public void SetToolWindow(IntPtr hwnd, bool enabled) => ToolWindowEnabled = enabled;
+
+ public void SetNoActivate(IntPtr hwnd, bool enabled) => NoActivateEnabled = enabled;
+
+ public void SetLayered(IntPtr hwnd, bool enabled, byte opacity) => Opacity = enabled ? opacity : (byte)255;
+
+ public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor) => LayerMode = mode;
+
+ public void SetBottomMost(IntPtr hwnd) => LayerMode = DesktopLayerMode.BottomMost;
+
+ public IReadOnlyList<MonitorInfo> GetMonitors() =>
+ [
+ new MonitorInfo
+ {
+ Id = new Moli.Desktop.Layout.MonitorId("primary"),
+ Bounds = new Moli.Desktop.Layout.RectD(0, 0, 1920, 1080),
+ WorkArea = new Moli.Desktop.Layout.RectD(0, 0, 1920, 1040),
+ IsPrimary = true
+ }
+ ];
+}
diff --git a/src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs b/src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs
new file mode 100644
index 0000000..d4006ce
--- /dev/null
+++ b/src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs
@@ -0,0 +1,23 @@
+namespace Moli.Desktop.Tests.Interop;
+
+public class Win32InteropContractTests
+{
+ [Fact]
+ public void FakeInterop_CapturesWindowBehaviorForWindowTests()
+ {
+ var interop = new FakeWin32InteropService();
+ var hwnd = new IntPtr(42);
+
+ interop.SetClickThrough(hwnd, true);
+ interop.SetToolWindow(hwnd, true);
+ interop.SetNoActivate(hwnd, true);
+ interop.SetLayered(hwnd, true, 128);
+ interop.SetBottomMost(hwnd);
+
+ Assert.True(interop.ClickThroughEnabled);
+ Assert.True(interop.ToolWindowEnabled);
+ Assert.True(interop.NoActivateEnabled);
+ Assert.Equal(128, interop.Opacity);
+ Assert.Single(interop.GetMonitors());
+ }
+}
diff --git a/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs b/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
new file mode 100644
index 0000000..cc879a3
--- /dev/null
+++ b/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
@@ -0,0 +1,99 @@
+using System.Text.Json;
+using Microsoft.Extensions.Logging.Abstractions;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Host;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+using Moli.Desktop.WebView;
+
+namespace Moli.Desktop.Tests.WebView;
+
+public class PluginBridgeDispatcherTests
+{
+ [Fact]
+ public async Task DispatchAsync_ReturnsRuntimeInfoForBridgeRequest()
+ {
+ var dispatcher = CreateDispatcher(out _, out _);
+ var context = CreateContext();
+
+ var response = await dispatcher.DispatchAsync("""{"id":"1","method":"getRuntimeInfo"}""", context);
+
+ Assert.True(response.Success);
+ var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
+ Assert.Contains("sample.clock", json);
+ Assert.Contains(context.HostId, json);
+ }
+
+ [Fact]
+ public async Task DispatchAsync_PublishesResizeRequestEvent()
+ {
+ var dispatcher = CreateDispatcher(out _, out var events);
+ RuntimeEvent? captured = null;
+ using var subscription = events.Subscribe(runtimeEvent =>
+ {
+ captured = runtimeEvent;
+ return Task.CompletedTask;
+ });
+
+ var response = await dispatcher.DispatchAsync(
+ """{"id":"2","method":"requestResize","params":{"width":320,"height":160}}""",
+ CreateContext());
+
+ Assert.True(response.Success);
+ Assert.NotNull(captured);
+ Assert.Equal("plugin.resizeRequested", captured.Name);
+ }
+
+ [Fact]
+ public async Task DispatchAsync_RejectsInvalidSetConfigPayload()
+ {
+ var dispatcher = CreateDispatcher(out _, out _);
+
+ var response = await dispatcher.DispatchAsync("""{"id":"3","method":"setConfig","params":true}""", CreateContext());
+
+ Assert.False(response.Success);
+ Assert.Equal("BridgePayloadInvalid", response.Error?.Code);
+ }
+
+ [Fact]
+ public void BridgeScript_ExposesExpectedPluginMethods()
+ {
+ var script = PluginBridgeScript.Build();
+
+ Assert.Contains("getRuntimeInfo", script);
+ Assert.Contains("requestResize", script);
+ Assert.Contains("moliDesktopResponse", script);
+ }
+
+ private static PluginBridgeDispatcher CreateDispatcher(out DiagnosticsService diagnostics, out RuntimeEventBus events)
+ {
+ var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
+ var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
+ diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
+ events = new RuntimeEventBus();
+ return new PluginBridgeDispatcher(diagnostics, events);
+ }
+
+ private static PluginBridgeContext CreateContext()
+ {
+ return new PluginBridgeContext
+ {
+ HostId = "host-1",
+ Manifest = new PluginManifest
+ {
+ Id = "sample.clock",
+ Name = "Clock",
+ Version = "1.0.0",
+ Type = PluginType.Widget,
+ Entry = "index.html"
+ },
+ RuntimeInfo = new PluginRuntimeBridgeInfo
+ {
+ PluginId = "sample.clock",
+ PluginType = PluginType.Widget,
+ HostId = "host-1"
+ },
+ Config = JsonDocument.Parse("""{"label":"clock"}""").RootElement.Clone()
+ };
+ }
+}
diff --git a/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs b/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
index aafab78..a41e1e3 100644
--- a/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
+++ b/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
@@ -26,6 +26,11 @@
public const string PluginManifestInvalid = "PluginManifestInvalid";
public const string PluginEntryMissing = "PluginEntryMissing";
public const string WebViewNavigationFailed = "WebViewNavigationFailed";
+ public const string WebViewHostInitialized = "WebViewHostInitialized";
+ public const string WebViewBridgeMessageInvalid = "WebViewBridgeMessageInvalid";
+ public const string DesktopLayerStrategySelected = "DesktopLayerStrategySelected";
+ public const string DesktopLayerAttachFailed = "DesktopLayerAttachFailed";
+ public const string Win32InteropFailed = "Win32InteropFailed";
}
public interface IDiagnosticsService
diff --git a/src/Moli.Desktop/Host/DesktopHostBuilder.cs b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
index 0cf3da3..d0ea42c 100644
--- a/src/Moli.Desktop/Host/DesktopHostBuilder.cs
+++ b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -3,9 +3,11 @@
using Microsoft.Extensions.Logging;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
+using Moli.Desktop.WebView;
namespace Moli.Desktop.Host;
@@ -30,6 +32,11 @@
services.AddSingleton<PluginStateMachine>();
services.AddSingleton<IPluginManager, PluginManager>();
services.AddSingleton<ILayoutManager, LayoutManager>();
+ services.AddSingleton<IDesktopLayerStrategy, WorkerWDesktopLayerStrategy>();
+ services.AddSingleton<IDesktopLayerStrategy, BottomDesktopLayerStrategy>();
+ services.AddSingleton<IWin32InteropService, Win32InteropService>();
+ services.AddSingleton<PluginBridgeDispatcher>();
+ services.AddSingleton<IWebViewHostFactory, WebViewHostFactory>();
services.AddSingleton<MainWindow>();
});
}
diff --git a/src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs b/src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs
new file mode 100644
index 0000000..837c476
--- /dev/null
+++ b/src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs
@@ -0,0 +1,48 @@
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+
+namespace Moli.Desktop.Interop;
+
+/// <summary>Fallback strategy that keeps the wallpaper window at the bottom of normal Z-order.</summary>
+public sealed class BottomDesktopLayerStrategy : IDesktopLayerStrategy
+{
+ private readonly IDiagnosticsService _diagnostics;
+
+ public BottomDesktopLayerStrategy(IDiagnosticsService diagnostics)
+ {
+ _diagnostics = diagnostics;
+ }
+
+ public string Name => "BottomDesktopLayer";
+
+ public bool IsSupported() => true;
+
+ public bool TryAttachWallpaperWindow(IntPtr hwnd, MonitorInfo monitor, out string? error)
+ {
+ error = null;
+ if (!NativeMethods.SetWindowPos(
+ hwnd,
+ NativeMethods.HwndBottom,
+ (int)monitor.Bounds.X,
+ (int)monitor.Bounds.Y,
+ (int)monitor.Bounds.Width,
+ (int)monitor.Bounds.Height,
+ NativeMethods.SwpNoActivate | NativeMethods.SwpShowWindow))
+ {
+ error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.DesktopLayerAttachFailed,
+ "Failed to place window at bottom desktop layer.",
+ new Dictionary<string, string> { ["reason"] = error });
+ return false;
+ }
+
+ _diagnostics.Record(
+ DiagnosticSeverity.Info,
+ DiagnosticCodes.DesktopLayerStrategySelected,
+ "Desktop layer strategy selected.",
+ new Dictionary<string, string> { ["strategy"] = Name });
+ return true;
+ }
+}
diff --git a/src/Moli.Desktop/Interop/DesktopLayerMode.cs b/src/Moli.Desktop/Interop/DesktopLayerMode.cs
new file mode 100644
index 0000000..479e6c4
--- /dev/null
+++ b/src/Moli.Desktop/Interop/DesktopLayerMode.cs
@@ -0,0 +1,8 @@
+namespace Moli.Desktop.Interop;
+
+/// <summary>Desired desktop layer placement for rendered desktop windows.</summary>
+public enum DesktopLayerMode
+{
+ WorkerW,
+ BottomMost
+}
diff --git a/src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs b/src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs
new file mode 100644
index 0000000..d2ce85b
--- /dev/null
+++ b/src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs
@@ -0,0 +1,11 @@
+using Moli.Desktop.Configuration;
+
+namespace Moli.Desktop.Interop;
+
+/// <summary>Places a wallpaper window into a desktop-compatible layer.</summary>
+public interface IDesktopLayerStrategy
+{
+ string Name { get; }
+ bool IsSupported();
+ bool TryAttachWallpaperWindow(IntPtr hwnd, MonitorInfo monitor, out string? error);
+}
diff --git a/src/Moli.Desktop/Interop/IWin32InteropService.cs b/src/Moli.Desktop/Interop/IWin32InteropService.cs
new file mode 100644
index 0000000..3660f32
--- /dev/null
+++ b/src/Moli.Desktop/Interop/IWin32InteropService.cs
@@ -0,0 +1,17 @@
+using System.Windows;
+using Moli.Desktop.Configuration;
+
+namespace Moli.Desktop.Interop;
+
+/// <summary>Facade over Win32 window behavior used by desktop surfaces.</summary>
+public interface IWin32InteropService
+{
+ IntPtr GetWindowHandle(Window window);
+ void SetClickThrough(IntPtr hwnd, bool enabled);
+ void SetToolWindow(IntPtr hwnd, bool enabled);
+ void SetNoActivate(IntPtr hwnd, bool enabled);
+ void SetLayered(IntPtr hwnd, bool enabled, byte opacity);
+ void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor);
+ void SetBottomMost(IntPtr hwnd);
+ IReadOnlyList<MonitorInfo> GetMonitors();
+}
diff --git a/src/Moli.Desktop/Interop/NativeMethods.cs b/src/Moli.Desktop/Interop/NativeMethods.cs
new file mode 100644
index 0000000..2922088
--- /dev/null
+++ b/src/Moli.Desktop/Interop/NativeMethods.cs
@@ -0,0 +1,115 @@
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace Moli.Desktop.Interop;
+
+internal static class NativeMethods
+{
+ internal const int GwlExStyle = -20;
+ internal const int WsExTransparent = 0x00000020;
+ internal const int WsExLayered = 0x00080000;
+ internal const int WsExToolWindow = 0x00000080;
+ internal const int WsExNoActivate = 0x08000000;
+ internal const int LwaAlpha = 0x00000002;
+ internal const uint SwpNoSize = 0x0001;
+ internal const uint SwpNoMove = 0x0002;
+ internal const uint SwpNoZOrder = 0x0004;
+ internal const uint SwpNoActivate = 0x0010;
+ internal const uint SwpShowWindow = 0x0040;
+ internal const uint SmtoNormal = 0x0000;
+ internal static readonly IntPtr HwndBottom = new(1);
+
+ internal delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
+ internal delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData);
+
+ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW", SetLastError = true)]
+ internal static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);
+
+ [DllImport("user32.dll", EntryPoint = "GetWindowLongW", SetLastError = true)]
+ internal static extern int GetWindowLong32(IntPtr hWnd, int nIndex);
+
+ [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW", SetLastError = true)]
+ internal static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
+
+ [DllImport("user32.dll", EntryPoint = "SetWindowLongW", SetLastError = true)]
+ internal static extern int SetWindowLong32(IntPtr hWnd, int nIndex, int dwNewLong);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
+
+ [DllImport("user32.dll", EntryPoint = "FindWindowW", CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern IntPtr FindWindow(string lpClassName, string? lpWindowName);
+
+ [DllImport("user32.dll", EntryPoint = "FindWindowExW", CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string? lpszWindow);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, uint flags, uint timeout, out IntPtr result);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
+
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);
+
+ internal static IntPtr GetWindowLongPtr(IntPtr hwnd, int index)
+ {
+ return IntPtr.Size == 8
+ ? GetWindowLongPtr64(hwnd, index)
+ : new IntPtr(GetWindowLong32(hwnd, index));
+ }
+
+ internal static IntPtr SetWindowLongPtr(IntPtr hwnd, int index, IntPtr value)
+ {
+ return IntPtr.Size == 8
+ ? SetWindowLongPtr64(hwnd, index, value)
+ : new IntPtr(SetWindowLong32(hwnd, index, value.ToInt32()));
+ }
+
+ internal static int GetLastError() => Marshal.GetLastWin32Error();
+
+ internal static void ThrowLastWin32Error(string operation)
+ {
+ var error = GetLastError();
+ if (error != 0)
+ {
+ throw new Win32Exception(error, $"{operation} failed.");
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct Rect
+ {
+ public int Left;
+ public int Top;
+ public int Right;
+ public int Bottom;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ internal struct MonitorInfoEx
+ {
+ public int Size;
+ public Rect Monitor;
+ public Rect WorkArea;
+ [MarshalAs(UnmanagedType.Bool)]
+ public bool Flags;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
+ public string DeviceName;
+ }
+}
diff --git a/src/Moli.Desktop/Interop/Win32InteropService.cs b/src/Moli.Desktop/Interop/Win32InteropService.cs
new file mode 100644
index 0000000..ad6a2af
--- /dev/null
+++ b/src/Moli.Desktop/Interop/Win32InteropService.cs
@@ -0,0 +1,172 @@
+using System.Windows;
+using System.Windows.Interop;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Layout;
+
+namespace Moli.Desktop.Interop;
+
+/// <summary>Default Win32 facade for window styles, desktop placement, and monitor discovery.</summary>
+public sealed class Win32InteropService : IWin32InteropService
+{
+ private readonly IReadOnlyList<IDesktopLayerStrategy> _strategies;
+ private readonly IDiagnosticsService _diagnostics;
+
+ public Win32InteropService(IEnumerable<IDesktopLayerStrategy> strategies, IDiagnosticsService diagnostics)
+ {
+ _strategies = [.. strategies];
+ _diagnostics = diagnostics;
+ }
+
+ public IntPtr GetWindowHandle(Window window) => new WindowInteropHelper(window).Handle;
+
+ public void SetClickThrough(IntPtr hwnd, bool enabled)
+ {
+ SetStyleFlag(hwnd, NativeMethods.WsExLayered | NativeMethods.WsExTransparent, enabled, "SetClickThrough");
+ }
+
+ public void SetToolWindow(IntPtr hwnd, bool enabled)
+ {
+ SetStyleFlag(hwnd, NativeMethods.WsExToolWindow, enabled, "SetToolWindow");
+ }
+
+ public void SetNoActivate(IntPtr hwnd, bool enabled)
+ {
+ SetStyleFlag(hwnd, NativeMethods.WsExNoActivate, enabled, "SetNoActivate");
+ }
+
+ public void SetLayered(IntPtr hwnd, bool enabled, byte opacity)
+ {
+ SetStyleFlag(hwnd, NativeMethods.WsExLayered, enabled, "SetLayered");
+ if (enabled && !NativeMethods.SetLayeredWindowAttributes(hwnd, 0, opacity, NativeMethods.LwaAlpha))
+ {
+ RecordWin32Failure("SetLayeredWindowAttributes", hwnd);
+ }
+ }
+
+ public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor)
+ {
+ var candidates = mode == DesktopLayerMode.WorkerW
+ ? _strategies.OrderBy(strategy => strategy is WorkerWDesktopLayerStrategy ? 0 : 1)
+ : _strategies.OrderBy(strategy => strategy is BottomDesktopLayerStrategy ? 0 : 1);
+
+ foreach (var strategy in candidates)
+ {
+ if (!strategy.IsSupported())
+ {
+ continue;
+ }
+
+ if (strategy.TryAttachWallpaperWindow(hwnd, monitor, out var error))
+ {
+ return;
+ }
+
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.DesktopLayerAttachFailed,
+ "Desktop layer strategy failed.",
+ new Dictionary<string, string>
+ {
+ ["strategy"] = strategy.Name,
+ ["reason"] = error ?? "Unknown"
+ });
+ }
+ }
+
+ public void SetBottomMost(IntPtr hwnd)
+ {
+ if (!NativeMethods.SetWindowPos(
+ hwnd,
+ NativeMethods.HwndBottom,
+ 0,
+ 0,
+ 0,
+ 0,
+ NativeMethods.SwpNoMove | NativeMethods.SwpNoSize | NativeMethods.SwpNoActivate))
+ {
+ RecordWin32Failure("SetBottomMost", hwnd);
+ }
+ }
+
+ public IReadOnlyList<MonitorInfo> GetMonitors()
+ {
+ var monitors = new List<MonitorInfo>();
+ NativeMethods.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (
+ IntPtr hMonitor,
+ IntPtr hdcMonitor,
+ ref NativeMethods.Rect monitorRect,
+ IntPtr data) =>
+ {
+ var native = new NativeMethods.MonitorInfoEx
+ {
+ Size = System.Runtime.InteropServices.Marshal.SizeOf<NativeMethods.MonitorInfoEx>(),
+ DeviceName = string.Empty
+ };
+
+ if (!NativeMethods.GetMonitorInfo(hMonitor, ref native))
+ {
+ return true;
+ }
+
+ var id = string.IsNullOrWhiteSpace(native.DeviceName)
+ ? $"monitor-{monitors.Count + 1}"
+ : native.DeviceName;
+ monitors.Add(new MonitorInfo
+ {
+ Id = new MonitorId(native.Flags ? "primary" : id),
+ Bounds = ToRectD(native.Monitor),
+ WorkArea = ToRectD(native.WorkArea),
+ IsPrimary = native.Flags,
+ Scale = 1
+ });
+ return true;
+ }, IntPtr.Zero);
+
+ return monitors.Count > 0
+ ? monitors
+ : [new MonitorInfo
+ {
+ Id = new MonitorId("primary"),
+ Bounds = new RectD(0, 0, SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight),
+ WorkArea = new RectD(0, 0, SystemParameters.WorkArea.Width, SystemParameters.WorkArea.Height),
+ IsPrimary = true
+ }];
+ }
+
+ private void SetStyleFlag(IntPtr hwnd, int flag, bool enabled, string operation)
+ {
+ var current = NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlExStyle).ToInt64();
+ var styleFlag = unchecked((uint)flag);
+ var currentStyle = unchecked((uint)current);
+ var updated = enabled ? currentStyle | styleFlag : currentStyle & ~styleFlag;
+ NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlExStyle, new IntPtr(updated));
+ var error = NativeMethods.GetLastError();
+ if (error != 0)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.Win32InteropFailed,
+ $"{operation} failed.",
+ new Dictionary<string, string> { ["hwnd"] = hwnd.ToString("X"), ["error"] = error.ToString() });
+ }
+ }
+
+ private void RecordWin32Failure(string operation, IntPtr hwnd)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.Win32InteropFailed,
+ $"{operation} failed.",
+ new Dictionary<string, string>
+ {
+ ["hwnd"] = hwnd.ToString("X"),
+ ["error"] = NativeMethods.GetLastError().ToString()
+ });
+ }
+
+ private static RectD ToRectD(NativeMethods.Rect rect)
+ {
+ return new RectD(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
+ }
+}
diff --git a/src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs b/src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs
new file mode 100644
index 0000000..21de1f7
--- /dev/null
+++ b/src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs
@@ -0,0 +1,96 @@
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+
+namespace Moli.Desktop.Interop;
+
+/// <summary>Attempts to attach wallpaper windows behind desktop icons through Explorer's WorkerW layer.</summary>
+public sealed class WorkerWDesktopLayerStrategy : IDesktopLayerStrategy
+{
+ private readonly IDiagnosticsService _diagnostics;
+
+ public WorkerWDesktopLayerStrategy(IDiagnosticsService diagnostics)
+ {
+ _diagnostics = diagnostics;
+ }
+
+ public string Name => "WorkerW";
+
+ public bool IsSupported() => NativeMethods.FindWindow("Progman", null) != IntPtr.Zero;
+
+ public bool TryAttachWallpaperWindow(IntPtr hwnd, MonitorInfo monitor, out string? error)
+ {
+ error = null;
+ var workerW = FindWorkerW();
+ if (workerW == IntPtr.Zero)
+ {
+ error = "WorkerW window was not found.";
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.DesktopLayerAttachFailed,
+ "WorkerW desktop layer was not found.",
+ new Dictionary<string, string> { ["strategy"] = Name });
+ return false;
+ }
+
+ if (NativeMethods.SetParent(hwnd, workerW) == IntPtr.Zero)
+ {
+ var lastError = NativeMethods.GetLastError();
+ if (lastError != 0)
+ {
+ error = $"SetParent failed with {lastError}";
+ return false;
+ }
+ }
+
+ if (!NativeMethods.SetWindowPos(
+ hwnd,
+ IntPtr.Zero,
+ (int)monitor.Bounds.X,
+ (int)monitor.Bounds.Y,
+ (int)monitor.Bounds.Width,
+ (int)monitor.Bounds.Height,
+ NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpShowWindow))
+ {
+ error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
+ return false;
+ }
+
+ _diagnostics.Record(
+ DiagnosticSeverity.Info,
+ DiagnosticCodes.DesktopLayerStrategySelected,
+ "Desktop layer strategy selected.",
+ new Dictionary<string, string> { ["strategy"] = Name });
+ return true;
+ }
+
+ private static IntPtr FindWorkerW()
+ {
+ var progman = NativeMethods.FindWindow("Progman", null);
+ if (progman != IntPtr.Zero)
+ {
+ NativeMethods.SendMessageTimeout(
+ progman,
+ 0x052C,
+ IntPtr.Zero,
+ IntPtr.Zero,
+ NativeMethods.SmtoNormal,
+ 1000,
+ out _);
+ }
+
+ IntPtr workerW = IntPtr.Zero;
+ NativeMethods.EnumWindows((topHandle, _) =>
+ {
+ var shellView = NativeMethods.FindWindowEx(topHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
+ if (shellView == IntPtr.Zero)
+ {
+ return true;
+ }
+
+ workerW = NativeMethods.FindWindowEx(IntPtr.Zero, topHandle, "WorkerW", null);
+ return workerW == IntPtr.Zero;
+ }, IntPtr.Zero);
+
+ return workerW;
+ }
+}
diff --git a/src/Moli.Desktop/WebView/IWebViewHost.cs b/src/Moli.Desktop/WebView/IWebViewHost.cs
new file mode 100644
index 0000000..ff31e42
--- /dev/null
+++ b/src/Moli.Desktop/WebView/IWebViewHost.cs
@@ -0,0 +1,16 @@
+using Moli.Desktop.Plugins;
+
+namespace Moli.Desktop.WebView;
+
+/// <summary>Runtime wrapper around a WebView2 instance owned by one plugin surface.</summary>
+public interface IWebViewHost : IAsyncDisposable
+{
+ string HostId { get; }
+ PluginId PluginId { get; }
+ PluginType PluginType { get; }
+ Task InitializeAsync(WebViewHostOptions options, CancellationToken cancellationToken = default);
+ Task NavigateAsync(Uri entryUri, CancellationToken cancellationToken = default);
+ Task InjectBridgeAsync(PluginBridgeContext context, CancellationToken cancellationToken = default);
+ Task DispatchLifecycleEventAsync(string eventName, object? payload, CancellationToken cancellationToken = default);
+ Task ReloadAsync(CancellationToken cancellationToken = default);
+}
diff --git a/src/Moli.Desktop/WebView/IWebViewHostFactory.cs b/src/Moli.Desktop/WebView/IWebViewHostFactory.cs
new file mode 100644
index 0000000..70ee022
--- /dev/null
+++ b/src/Moli.Desktop/WebView/IWebViewHostFactory.cs
@@ -0,0 +1,9 @@
+using Moli.Desktop.Plugins;
+
+namespace Moli.Desktop.WebView;
+
+/// <summary>Creates plugin-scoped WebView hosts for wallpaper and widget windows.</summary>
+public interface IWebViewHostFactory
+{
+ IWebViewHost Create(PluginDescriptor plugin);
+}
diff --git a/src/Moli.Desktop/WebView/PluginBridgeContext.cs b/src/Moli.Desktop/WebView/PluginBridgeContext.cs
new file mode 100644
index 0000000..f734d30
--- /dev/null
+++ b/src/Moli.Desktop/WebView/PluginBridgeContext.cs
@@ -0,0 +1,21 @@
+using System.Text.Json;
+using Moli.Desktop.Plugins;
+
+namespace Moli.Desktop.WebView;
+
+public sealed record PluginBridgeContext
+{
+ public required string HostId { get; init; }
+ public required PluginManifest Manifest { get; init; }
+ public required PluginRuntimeBridgeInfo RuntimeInfo { get; init; }
+ public JsonElement Config { get; init; }
+}
+
+public sealed record PluginRuntimeBridgeInfo
+{
+ public required string PluginId { get; init; }
+ public required PluginType PluginType { get; init; }
+ public required string HostId { get; init; }
+ public bool IsEditMode { get; init; }
+ public bool IsVisible { get; init; } = true;
+}
diff --git a/src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs b/src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs
new file mode 100644
index 0000000..f1aa9bc
--- /dev/null
+++ b/src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs
@@ -0,0 +1,143 @@
+using System.Text.Json;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.WebView;
+
+/// <summary>Validates and handles JavaScript bridge messages from a plugin WebView.</summary>
+public sealed class PluginBridgeDispatcher
+{
+ public const int MaxConfigPatchBytes = 64 * 1024;
+ private static readonly HashSet<string> AllowedMethods =
+ [
+ "getManifest",
+ "getRuntimeInfo",
+ "getConfig",
+ "setConfig",
+ "notify",
+ "requestReload",
+ "requestShow",
+ "requestHide",
+ "requestResize"
+ ];
+
+ private readonly IDiagnosticsService _diagnostics;
+ private readonly IRuntimeEventBus _events;
+ private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
+
+ public PluginBridgeDispatcher(IDiagnosticsService diagnostics, IRuntimeEventBus events)
+ {
+ _diagnostics = diagnostics;
+ _events = events;
+ }
+
+ public async Task<PluginBridgeResponse> DispatchAsync(
+ string rawJson,
+ PluginBridgeContext context,
+ CancellationToken cancellationToken = default)
+ {
+ BridgeRequest? request;
+ try
+ {
+ request = JsonSerializer.Deserialize<BridgeRequest>(rawJson, _jsonOptions);
+ }
+ catch (JsonException ex)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.WebViewBridgeMessageInvalid,
+ "Plugin bridge message was not valid JSON.",
+ new Dictionary<string, string> { ["hostId"] = context.HostId, ["exception"] = ex.GetType().Name });
+ return PluginBridgeResponse.Failure(null, "BridgeMessageInvalid", "Bridge message was not valid JSON.");
+ }
+
+ if (request is null || string.IsNullOrWhiteSpace(request.Id) || string.IsNullOrWhiteSpace(request.Method))
+ {
+ return PluginBridgeResponse.Failure(request?.Id, "BridgeMessageInvalid", "Bridge message id and method are required.");
+ }
+
+ if (!AllowedMethods.Contains(request.Method))
+ {
+ return PluginBridgeResponse.Failure(request.Id, "BridgeMethodNotAllowed", $"Bridge method {request.Method} is not allowed.");
+ }
+
+ return request.Method switch
+ {
+ "getManifest" => PluginBridgeResponse.Ok(request.Id, context.Manifest),
+ "getRuntimeInfo" => PluginBridgeResponse.Ok(request.Id, context.RuntimeInfo),
+ "getConfig" => PluginBridgeResponse.Ok(request.Id, context.Config.ValueKind == JsonValueKind.Undefined ? null : context.Config),
+ "setConfig" => await HandleEventAsync(request, context, "plugin.configChanged", cancellationToken).ConfigureAwait(false),
+ "notify" => await HandleEventAsync(request, context, "plugin.notify", cancellationToken).ConfigureAwait(false),
+ "requestReload" => await HandleEventAsync(request, context, "plugin.reloadRequested", cancellationToken).ConfigureAwait(false),
+ "requestShow" => await HandleEventAsync(request, context, "plugin.showRequested", cancellationToken).ConfigureAwait(false),
+ "requestHide" => await HandleEventAsync(request, context, "plugin.hideRequested", cancellationToken).ConfigureAwait(false),
+ "requestResize" => await HandleEventAsync(request, context, "plugin.resizeRequested", cancellationToken).ConfigureAwait(false),
+ _ => PluginBridgeResponse.Failure(request.Id, "BridgeMethodNotAllowed", $"Bridge method {request.Method} is not allowed.")
+ };
+ }
+
+ private async Task<PluginBridgeResponse> HandleEventAsync(
+ BridgeRequest request,
+ PluginBridgeContext context,
+ string eventName,
+ CancellationToken cancellationToken)
+ {
+ if (request.Method == "setConfig")
+ {
+ if (request.Params.ValueKind is not JsonValueKind.Object)
+ {
+ return PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", "setConfig expects an object payload.");
+ }
+
+ if (JsonSerializer.SerializeToUtf8Bytes(request.Params, _jsonOptions).Length > MaxConfigPatchBytes)
+ {
+ return PluginBridgeResponse.Failure(request.Id, "BridgePayloadTooLarge", "setConfig payload is larger than 64 KB.");
+ }
+ }
+
+ await _events.PublishAsync(new RuntimeEvent
+ {
+ Name = eventName,
+ Payload = new
+ {
+ context.HostId,
+ context.RuntimeInfo.PluginId,
+ request.Method,
+ Params = request.Params.ValueKind == JsonValueKind.Undefined ? null : (object)request.Params
+ }
+ }, cancellationToken).ConfigureAwait(false);
+
+ return PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { accepted = true });
+ }
+
+ private sealed record BridgeRequest
+ {
+ public string? Id { get; init; }
+ public string? Method { get; init; }
+ public JsonElement Params { get; init; }
+ }
+}
+
+public sealed record PluginBridgeResponse
+{
+ public string? Id { get; init; }
+ public bool Success { get; init; }
+ public object? Result { get; init; }
+ public BridgeError? Error { get; init; }
+
+ public static PluginBridgeResponse Ok(string id, object? result) => new()
+ {
+ Id = id,
+ Success = true,
+ Result = result
+ };
+
+ public static PluginBridgeResponse Failure(string? id, string code, string message) => new()
+ {
+ Id = id,
+ Success = false,
+ Error = new BridgeError(code, message)
+ };
+}
+
+public sealed record BridgeError(string Code, string Message);
diff --git a/src/Moli.Desktop/WebView/PluginBridgeScript.cs b/src/Moli.Desktop/WebView/PluginBridgeScript.cs
new file mode 100644
index 0000000..ab12d06
--- /dev/null
+++ b/src/Moli.Desktop/WebView/PluginBridgeScript.cs
@@ -0,0 +1,40 @@
+namespace Moli.Desktop.WebView;
+
+/// <summary>Builds the JavaScript bridge injected before plugin documents run.</summary>
+public static class PluginBridgeScript
+{
+ public static string Build()
+ {
+ return """
+ (() => {
+ if (window.moliDesktop) return;
+ let nextId = 1;
+ const pending = new Map();
+ window.addEventListener("moliDesktopResponse", (event) => {
+ const response = event.detail || {};
+ const callbacks = pending.get(response.id);
+ if (!callbacks) return;
+ pending.delete(response.id);
+ if (response.success) callbacks.resolve(response.result);
+ else callbacks.reject(response.error || { code: "BridgeError", message: "Bridge request failed." });
+ });
+ const call = (method, params) => new Promise((resolve, reject) => {
+ const id = String(nextId++);
+ pending.set(id, { resolve, reject });
+ chrome.webview.postMessage({ id, method, params });
+ });
+ window.moliDesktop = Object.freeze({
+ getManifest: () => call("getManifest"),
+ getRuntimeInfo: () => call("getRuntimeInfo"),
+ getConfig: () => call("getConfig"),
+ setConfig: (patch) => call("setConfig", patch),
+ notify: (message) => call("notify", message),
+ requestReload: () => call("requestReload"),
+ requestShow: () => call("requestShow"),
+ requestHide: () => call("requestHide"),
+ requestResize: (size) => call("requestResize", size)
+ });
+ })();
+ """;
+ }
+}
diff --git a/src/Moli.Desktop/WebView/WebViewHost.cs b/src/Moli.Desktop/WebView/WebViewHost.cs
new file mode 100644
index 0000000..357eb59
--- /dev/null
+++ b/src/Moli.Desktop/WebView/WebViewHost.cs
@@ -0,0 +1,173 @@
+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;
+
+/// <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 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<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()
+ {
+ 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<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 EnsureInitialized()
+ {
+ if (!_initialized || Control.CoreWebView2 is null || _options is null)
+ {
+ throw new InvalidOperationException("WebView host has not been initialized.");
+ }
+ }
+}
diff --git a/src/Moli.Desktop/WebView/WebViewHostFactory.cs b/src/Moli.Desktop/WebView/WebViewHostFactory.cs
new file mode 100644
index 0000000..0e6da77
--- /dev/null
+++ b/src/Moli.Desktop/WebView/WebViewHostFactory.cs
@@ -0,0 +1,27 @@
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.WebView;
+
+public sealed class WebViewHostFactory : IWebViewHostFactory
+{
+ private readonly IDiagnosticsService _diagnostics;
+ private readonly IRuntimeEventBus _events;
+ private readonly PluginBridgeDispatcher _bridgeDispatcher;
+
+ public WebViewHostFactory(
+ IDiagnosticsService diagnostics,
+ IRuntimeEventBus events,
+ PluginBridgeDispatcher bridgeDispatcher)
+ {
+ _diagnostics = diagnostics;
+ _events = events;
+ _bridgeDispatcher = bridgeDispatcher;
+ }
+
+ public IWebViewHost Create(PluginDescriptor plugin)
+ {
+ return new WebViewHost(plugin, _diagnostics, _events, _bridgeDispatcher);
+ }
+}
diff --git a/src/Moli.Desktop/WebView/WebViewHostOptions.cs b/src/Moli.Desktop/WebView/WebViewHostOptions.cs
new file mode 100644
index 0000000..eef8cf0
--- /dev/null
+++ b/src/Moli.Desktop/WebView/WebViewHostOptions.cs
@@ -0,0 +1,10 @@
+namespace Moli.Desktop.WebView;
+
+public sealed record WebViewHostOptions
+{
+ public required string UserDataFolder { get; init; }
+ public bool IsTransparent { get; init; }
+ public bool AreDevToolsEnabled { get; init; }
+ public bool IsMuted { get; init; }
+ public string? InitialScript { get; init; }
+}
--
Gitblit v1.9.1