基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 97df0fb5ed49e37d1c8e0e62057bb72ba5c9eb6a
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
 
namespace Moli.Desktop.Layout;
 
public sealed class LayoutManager : ILayoutManager
{
    public const double MinWidth = 80;
    public const double MinHeight = 40;
    public const double MinVisibleDip = 48;
    public const double MinScale = 0.5;
    public const double MaxScale = 3;
    public const double MinOpacity = 0.1;
    public const double MaxOpacity = 1;
 
    private readonly IConfigurationService _configuration;
    private readonly IDiagnosticsService _diagnostics;
    private readonly object _gate = new();
    private LayoutDocument _document = new();
 
    public LayoutManager(IConfigurationService configuration, IDiagnosticsService diagnostics)
    {
        _configuration = configuration;
        _diagnostics = diagnostics;
    }
 
    public async Task LoadAsync(CancellationToken cancellationToken = default)
    {
        var document = await _configuration.LoadLayoutAsync(cancellationToken).ConfigureAwait(false);
        lock (_gate)
        {
            _document = document;
        }
    }
 
    public Task SaveAsync(CancellationToken cancellationToken = default)
    {
        LayoutDocument snapshot;
        lock (_gate)
        {
            snapshot = _document;
        }
 
        return _configuration.SaveLayoutAsync(snapshot, cancellationToken);
    }
 
    public IReadOnlyList<WidgetLayout> GetAll()
    {
        lock (_gate)
        {
            return [.. _document.Instances];
        }
    }
 
    public WidgetLayout? Get(WidgetInstanceId instanceId)
    {
        lock (_gate)
        {
            return _document.Instances.FirstOrDefault(instance => instance.InstanceId == instanceId);
        }
    }
 
    public WidgetLayout CreateFromPlugin(PluginDescriptor plugin, MonitorId monitorId)
    {
        if (plugin.Type != PluginType.Widget)
        {
            throw new InvalidOperationException("Only widget plugins can create widget layouts.");
        }
 
        var layout = new WidgetLayout
        {
            InstanceId = new WidgetInstanceId($"{plugin.Id.Value}-{Guid.NewGuid():N}"),
            PluginId = plugin.Id,
            MonitorId = monitorId,
            Bounds = new RectD(
                plugin.Manifest.DefaultLayout.X,
                plugin.Manifest.DefaultLayout.Y,
                Math.Max(MinWidth, plugin.Manifest.DefaultLayout.Width),
                Math.Max(MinHeight, plugin.Manifest.DefaultLayout.Height)),
            IsLocked = plugin.Manifest.DefaultLayout.Locked,
            ClickThrough = plugin.Manifest.DefaultLayout.ClickThrough,
            Opacity = Clamp(plugin.Manifest.DefaultLayout.Opacity, MinOpacity, MaxOpacity),
            Scale = Clamp(plugin.Manifest.DefaultLayout.Scale, MinScale, MaxScale),
            DisplayLayer = plugin.Manifest.DefaultLayout.DisplayLayer
        };
 
        lock (_gate)
        {
            _document.Instances.Add(layout);
        }
 
        return layout;
    }
 
    public OperationResult<WidgetLayout> Move(WidgetInstanceId instanceId, PointD position)
    {
        return Mutate(instanceId, layout => layout with
        {
            Bounds = layout.Bounds with { X = position.X, Y = position.Y }
        });
    }
 
    public OperationResult<WidgetLayout> Resize(WidgetInstanceId instanceId, SizeD size)
    {
        return Mutate(instanceId, layout => layout with
        {
            Bounds = layout.Bounds with { Width = size.Width, Height = size.Height }
        });
    }
 
    public OperationResult<WidgetLayout> Update(WidgetInstanceId instanceId, WidgetLayoutPatch patch)
    {
        return Mutate(instanceId, layout => layout with
        {
            Bounds = patch.Bounds ?? layout.Bounds,
            MonitorId = patch.MonitorId ?? layout.MonitorId,
            IsVisible = patch.IsVisible ?? layout.IsVisible,
            IsLocked = patch.IsLocked ?? layout.IsLocked,
            Opacity = patch.Opacity ?? layout.Opacity,
            ClickThrough = patch.ClickThrough ?? layout.ClickThrough,
            Scale = patch.Scale ?? layout.Scale,
            DisplayLayer = patch.DisplayLayer ?? layout.DisplayLayer
        }, allowLocked: IsUnlockPatch(patch));
    }
 
    public IReadOnlyList<WidgetLayout> ReconcileMonitors(IReadOnlyList<MonitorInfo> monitors)
    {
        if (monitors.Count == 0)
        {
            return GetAll();
        }
 
        var primary = monitors.FirstOrDefault(monitor => monitor.IsPrimary) ?? monitors[0];
        var byId = monitors.ToDictionary(monitor => monitor.Id, monitor => monitor);
        lock (_gate)
        {
            for (var i = 0; i < _document.Instances.Count; i++)
            {
                var layout = _document.Instances[i];
                var monitor = byId.GetValueOrDefault(layout.MonitorId);
                if (monitor is null)
                {
                    var migrated = MigrateToPrimary(layout, primary);
                    _document.Instances[i] = migrated;
                    _diagnostics.Record(
                        DiagnosticSeverity.Info,
                        "LayoutReconciled",
                        "Widget layout migrated to primary monitor after monitor topology changed.",
                        new Dictionary<string, string>
                        {
                            ["instanceId"] = layout.InstanceId.Value,
                            ["monitorId"] = layout.MonitorId.Value,
                            ["targetMonitorId"] = primary.Id.Value
                        });
                    continue;
                }
 
                var scaled = ScaleToWorkArea(layout, monitor);
                var constrained = Constrain(scaled, monitor);
                if (constrained != layout)
                {
                    _document.Instances[i] = constrained;
                }
            }
 
            _document.Monitors.Add(new MonitorSnapshot
            {
                CapturedAt = DateTimeOffset.UtcNow,
                Monitors = [.. monitors]
            });
            while (_document.Monitors.Count > 5)
            {
                _document.Monitors.RemoveAt(0);
            }
 
            return [.. _document.Instances];
        }
    }
 
    private OperationResult<WidgetLayout> Mutate(WidgetInstanceId instanceId, Func<WidgetLayout, WidgetLayout> update, bool allowLocked = false)
    {
        lock (_gate)
        {
            var index = _document.Instances.FindIndex(instance => instance.InstanceId == instanceId);
            if (index < 0)
            {
                return OperationResult<WidgetLayout>.Failure("WidgetLayoutNotFound", $"Widget layout {instanceId} was not found.");
            }
 
            var current = _document.Instances[index];
            if (current.IsLocked && !allowLocked)
            {
                return OperationResult<WidgetLayout>.Failure("WidgetLayoutLocked", $"Widget layout {instanceId} is locked.");
            }
 
            var updated = ApplyScalarConstraints(update(current));
            var monitor = FindLatestMonitor(updated.MonitorId);
            if (monitor is not null)
            {
                updated = Constrain(updated, monitor);
            }
 
            _document.Instances[index] = updated;
            return OperationResult<WidgetLayout>.Success(updated);
        }
    }
 
    private MonitorInfo? FindLatestMonitor(MonitorId monitorId)
    {
        var latest = _document.Monitors.OrderByDescending(snapshot => snapshot.CapturedAt).FirstOrDefault();
        return latest?.Monitors.FirstOrDefault(monitor => monitor.Id == monitorId);
    }
 
    private static WidgetLayout ApplyScalarConstraints(WidgetLayout layout)
    {
        return layout with
        {
            Bounds = layout.Bounds with
            {
                Width = Math.Max(MinWidth, layout.Bounds.Width),
                Height = Math.Max(MinHeight, layout.Bounds.Height)
            },
            Scale = Clamp(layout.Scale, MinScale, MaxScale),
            Opacity = Clamp(layout.Opacity, MinOpacity, MaxOpacity)
        };
    }
 
    private static WidgetLayout Constrain(WidgetLayout layout, MonitorInfo monitor)
    {
        var work = monitor.WorkArea;
        var width = Clamp(layout.Bounds.Width, MinWidth, Math.Max(MinWidth, work.Width));
        var height = Clamp(layout.Bounds.Height, MinHeight, Math.Max(MinHeight, work.Height));
        var minX = work.X - width + MinVisibleDip;
        var maxX = work.Right - MinVisibleDip;
        var minY = work.Y - height + MinVisibleDip;
        var maxY = work.Bottom - MinVisibleDip;
 
        return ApplyScalarConstraints(layout with
        {
            MonitorId = monitor.Id,
            Bounds = new RectD(
                Clamp(layout.Bounds.X, minX, maxX),
                Clamp(layout.Bounds.Y, minY, maxY),
                width,
                height)
        });
    }
 
    private static WidgetLayout CenterInMonitor(WidgetLayout layout, MonitorInfo monitor)
    {
        var constrained = ApplyScalarConstraints(layout);
        var work = monitor.WorkArea;
        var width = Math.Min(constrained.Bounds.Width, work.Width);
        var height = Math.Min(constrained.Bounds.Height, work.Height);
        return constrained with
        {
            MonitorId = monitor.Id,
            Bounds = new RectD(
                work.X + (work.Width - width) / 2,
                work.Y + (work.Height - height) / 2,
                width,
                height)
        };
    }
 
    private WidgetLayout MigrateToPrimary(WidgetLayout layout, MonitorInfo primary)
    {
        var previousPrimary = _document.Monitors
            .OrderByDescending(snapshot => snapshot.CapturedAt)
            .SelectMany(snapshot => snapshot.Monitors)
            .FirstOrDefault(m => m.IsPrimary);
 
        if (previousPrimary is null || previousPrimary.WorkArea.Width <= 0 || previousPrimary.WorkArea.Height <= 0)
        {
            return layout with { MonitorId = primary.Id };
        }
 
        var scaleX = primary.WorkArea.Width / previousPrimary.WorkArea.Width;
        var scaleY = primary.WorkArea.Height / previousPrimary.WorkArea.Height;
        var relX = (layout.Bounds.X - previousPrimary.WorkArea.X) / previousPrimary.WorkArea.Width;
        var relY = (layout.Bounds.Y - previousPrimary.WorkArea.Y) / previousPrimary.WorkArea.Height;
 
        return ApplyScalarConstraints(layout with
        {
            MonitorId = primary.Id,
            Bounds = new RectD(
                primary.WorkArea.X + relX * primary.WorkArea.Width,
                primary.WorkArea.Y + relY * primary.WorkArea.Height,
                layout.Bounds.Width * scaleX,
                layout.Bounds.Height * scaleY)
        });
    }
 
    private WidgetLayout ScaleToWorkArea(WidgetLayout layout, MonitorInfo current)
    {
        var previous = _document.Monitors
            .OrderByDescending(snapshot => snapshot.CapturedAt)
            .SelectMany(snapshot => snapshot.Monitors)
            .FirstOrDefault(m => m.Id == current.Id);
 
        if (previous is null || previous.WorkArea == current.WorkArea ||
            previous.WorkArea.Width <= 0 || previous.WorkArea.Height <= 0)
        {
            return layout;
        }
 
        var scaleX = current.WorkArea.Width / previous.WorkArea.Width;
        var scaleY = current.WorkArea.Height / previous.WorkArea.Height;
        var relX = (layout.Bounds.X - previous.WorkArea.X) / previous.WorkArea.Width;
        var relY = (layout.Bounds.Y - previous.WorkArea.Y) / previous.WorkArea.Height;
 
        return layout with
        {
            Bounds = new RectD(
                current.WorkArea.X + relX * current.WorkArea.Width,
                current.WorkArea.Y + relY * current.WorkArea.Height,
                layout.Bounds.Width * scaleX,
                layout.Bounds.Height * scaleY)
        };
    }
 
    private static double Clamp(double value, double min, double max)
        => Math.Min(Math.Max(value, min), max);
 
    private static bool IsUnlockPatch(WidgetLayoutPatch patch)
        => patch.IsLocked == false &&
           patch.Bounds is null &&
           patch.MonitorId is null &&
           patch.IsVisible is null &&
           patch.Opacity is null &&
           patch.ClickThrough is null &&
           patch.Scale is null &&
           patch.DisplayLayer is null;
}