基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-03 9806138b910904d2f982ebf9471b295fb6939715
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
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
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 Brushes = System.Windows.Media.Brushes;
using Cursors = System.Windows.Input.Cursors;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using Point = System.Windows.Point;
 
namespace Moli.Desktop.Windows;
 
/// <summary>Desktop widget surface with edit-mode drag and resize behavior.</summary>
public sealed class WidgetWindow : Window
{
    private const double ResizeGripSize = 18;
    private readonly PluginDescriptor _plugin;
    private readonly IWebViewHost _webView;
    private readonly IWin32InteropService _interop;
    private readonly DesktopPaths _paths;
    private readonly IDiagnosticsService _diagnostics;
    private readonly Func<WidgetInstanceId, WidgetLayoutPatch, CancellationToken, Task> _commitLayoutAsync;
    private readonly Border _editBorder;
    private readonly Border _resizeGrip;
    private WidgetLayout _layout;
    private bool _editMode;
    private bool _safeInputMode;
    private Point? _dragStart;
    private RectD _startBounds;
    private bool _resizing;
 
    public WidgetWindow(
        PluginDescriptor plugin,
        WidgetLayout layout,
        IWebViewHost webView,
        IWin32InteropService interop,
        DesktopPaths paths,
        IDiagnosticsService diagnostics,
        Func<WidgetInstanceId, WidgetLayoutPatch, CancellationToken, Task> commitLayoutAsync)
    {
        _plugin = plugin;
        _layout = layout;
        _webView = webView;
        _interop = interop;
        _paths = paths;
        _diagnostics = diagnostics;
        _commitLayoutAsync = commitLayoutAsync;
 
        Title = $"Moli Widget - {plugin.Manifest.Name}";
        WindowStyle = WindowStyle.None;
        ResizeMode = ResizeMode.NoResize;
        AllowsTransparency = true;
        Background = Brushes.Transparent;
        ShowInTaskbar = false;
        Topmost = true;
        SizeToContent = SizeToContent.Manual;
 
        var root = new Grid { Background = Brushes.Transparent };
        root.Children.Add(webView.View);
        _editBorder = new Border
        {
            BorderBrush = Brushes.DeepSkyBlue,
            BorderThickness = new Thickness(2),
            Visibility = Visibility.Collapsed,
            IsHitTestVisible = false
        };
        _resizeGrip = new Border
        {
            Width = ResizeGripSize,
            Height = ResizeGripSize,
            HorizontalAlignment = HorizontalAlignment.Right,
            VerticalAlignment = VerticalAlignment.Bottom,
            Background = Brushes.DeepSkyBlue,
            Opacity = 0.85,
            Cursor = Cursors.SizeNWSE,
            Visibility = Visibility.Collapsed
        };
        root.Children.Add(_editBorder);
        root.Children.Add(_resizeGrip);
        Content = root;
 
        Loaded += (_, _) => ApplyWin32Styles();
        MouseLeftButtonDown += OnMouseLeftButtonDown;
        MouseMove += OnMouseMove;
        MouseLeftButtonUp += OnMouseLeftButtonUp;
        _resizeGrip.MouseLeftButtonDown += OnResizeGripMouseLeftButtonDown;
    }
 
    public WidgetInstanceId InstanceId => _layout.InstanceId;
 
    public async Task LoadAsync(CancellationToken cancellationToken = default)
    {
        ApplyLayout(_layout, _editMode, _safeInputMode);
        await _webView.InitializeAsync(new WebViewHostOptions
        {
            UserDataFolder = Path.Combine(_paths.WebViewDataDirectory, "widgets", _layout.InstanceId.Value),
            IsTransparent = true,
            AreDevToolsEnabled = true,
            IsMuted = false,
            InitialScript = PluginBridgeScript.Build()
        }, cancellationToken).ConfigureAwait(true);
 
        await _webView.InjectBridgeAsync(CreateBridgeContext(), cancellationToken).ConfigureAwait(true);
        await _webView.NavigateAsync(_plugin.EntryUri, cancellationToken).ConfigureAwait(true);
        await _webView.DispatchLifecycleEventAsync("moli:widget-loaded", ToRuntimeState(), cancellationToken).ConfigureAwait(true);
    }
 
    public void ApplyLayout(WidgetLayout layout, bool editMode, bool safeInputMode)
    {
        _layout = layout;
        _editMode = editMode;
        _safeInputMode = safeInputMode;
        Left = layout.Bounds.X;
        Top = layout.Bounds.Y;
        Width = layout.Bounds.Width;
        Height = layout.Bounds.Height;
        Opacity = Math.Clamp(layout.Opacity, 0.1, 1.0);
        Visibility = layout.IsVisible ? Visibility.Visible : Visibility.Hidden;
        Topmost = layout.DisplayPriority is DisplayPriority.IconLayer or DisplayPriority.AppLayer;
        _editBorder.Visibility = editMode ? Visibility.Visible : Visibility.Collapsed;
        _resizeGrip.Visibility = editMode && !layout.IsLocked ? Visibility.Visible : Visibility.Collapsed;
        ApplyWin32Styles();
    }
 
    public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
    {
        ApplyLayout(_layout, enabled, _safeInputMode);
        return _webView.DispatchLifecycleEventAsync("moli:edit-mode-changed", new { enabled }, cancellationToken);
    }
 
    public void SetSafeInputMode(bool enabled)
    {
        _safeInputMode = enabled;
        ApplyWin32Styles();
    }
 
    protected override async void OnClosed(EventArgs e)
    {
        await _webView.DisposeAsync();
        base.OnClosed(e);
    }
 
    private void OnResizeGripMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (!_editMode || _layout.IsLocked)
        {
            return;
        }
 
        _resizing = true;
        BeginPointerOperation(e);
        e.Handled = true;
    }
 
    private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (!_editMode || _layout.IsLocked || _resizing)
        {
            return;
        }
 
        BeginPointerOperation(e);
    }
 
    private void OnMouseMove(object sender, MouseEventArgs e)
    {
        if (_dragStart is null || e.LeftButton != MouseButtonState.Pressed)
        {
            return;
        }
 
        var current = PointToScreen(e.GetPosition(this));
        var deltaX = current.X - _dragStart.Value.X;
        var deltaY = current.Y - _dragStart.Value.Y;
        if (_resizing)
        {
            Width = Math.Max(LayoutManager.MinWidth, _startBounds.Width + deltaX);
            Height = Math.Max(LayoutManager.MinHeight, _startBounds.Height + deltaY);
        }
        else
        {
            Left = _startBounds.X + deltaX;
            Top = _startBounds.Y + deltaY;
        }
    }
 
    private async void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (_dragStart is null)
        {
            return;
        }
 
        ReleaseMouseCapture();
        var bounds = new RectD(Left, Top, Width, Height);
        _dragStart = null;
        _resizing = false;
        await _commitLayoutAsync(_layout.InstanceId, new WidgetLayoutPatch { Bounds = bounds }, CancellationToken.None);
    }
 
    private void BeginPointerOperation(MouseButtonEventArgs e)
    {
        _dragStart = PointToScreen(e.GetPosition(this));
        _startBounds = new RectD(Left, Top, Width, Height);
        CaptureMouse();
    }
 
    private PluginBridgeContext CreateBridgeContext() => new()
    {
        HostId = _webView.HostId,
        Manifest = _plugin.Manifest,
        RuntimeInfo = new PluginRuntimeBridgeInfo
        {
            HostId = _webView.HostId,
            PluginId = _plugin.Id.Value,
            PluginType = _plugin.Type,
            IsVisible = _layout.IsVisible,
            IsEditMode = _editMode
        },
        Config = _plugin.Manifest.Config.ValueKind == JsonValueKind.Undefined
            ? default
            : _plugin.Manifest.Config.Clone()
    };
 
    private WidgetRuntimeState ToRuntimeState() => new()
    {
        InstanceId = _layout.InstanceId,
        PluginId = _layout.PluginId,
        Bounds = _layout.Bounds,
        MonitorId = _layout.MonitorId,
        IsVisible = _layout.IsVisible,
        IsLocked = _layout.IsLocked,
        Opacity = _layout.Opacity,
        ClickThrough = _layout.ClickThrough
    };
 
    private void ApplyWin32Styles()
    {
        var hwnd = _interop.GetWindowHandle(this);
        if (hwnd == IntPtr.Zero)
        {
            return;
        }
 
        try
        {
            _interop.SetToolWindow(hwnd, true);
            _interop.SetLayered(hwnd, true, ToAlpha(_layout.Opacity));
            _interop.SetClickThrough(hwnd, !_editMode && !_safeInputMode && _layout.ClickThrough);
        }
        catch (Exception ex)
        {
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.Win32InteropFailed,
                "Failed to apply widget window styles.",
                new Dictionary<string, string> { ["instanceId"] = _layout.InstanceId.Value, ["exception"] = ex.GetType().Name });
        }
    }
 
    private static byte ToAlpha(double opacity) => (byte)Math.Round(Math.Clamp(opacity, 0.1, 1.0) * 255);
}