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.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs | 9
src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs | 17
docs/solution/multi-monitor-display-bug-analysis.md | 734 +++++++++++++++++++++++++++++
src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs | 153 +++++
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs | 29 +
src/Moli.Desktop/Windows/RuntimeSurfaceController.cs | 153 +++++
src/Moli.Desktop/Layout/LayoutManager.cs | 75 ++
src/Moli.Desktop/Interop/Win32InteropService.cs | 54 +
src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs | 3
src/Moli.Desktop/Windows/WidgetWindow.cs | 46 +
src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs | 17
src/Moli.Desktop/Runtime/IDesktopRuntime.cs | 1
src/Moli.Desktop/Host/DesktopHostBuilder.cs | 1
src/Moli.Desktop/Interop/NativeMethods.cs | 21
src/Moli.Desktop/Interop/DisplayChangeMonitor.cs | 113 ++++
src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs | 15
src/Moli.Desktop/Windows/WallpaperWindow.cs | 10
scripts/publish-to-apps.ps1 | 2
src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs | 3
src/Moli.Desktop/Interop/IWin32InteropService.cs | 5
20 files changed, 1,366 insertions(+), 95 deletions(-)
diff --git a/docs/solution/multi-monitor-display-bug-analysis.md b/docs/solution/multi-monitor-display-bug-analysis.md
new file mode 100644
index 0000000..b93916d
--- /dev/null
+++ b/docs/solution/multi-monitor-display-bug-analysis.md
@@ -0,0 +1,734 @@
+# 澶氭樉绀哄櫒 / 鏄剧ず鍣ㄥ垏鎹㈡樉绀哄紓甯� 鈥� 鏍瑰洜鍒嗘瀽涓庤В鍐虫柟妗�
+
+## 闂鎻忚堪
+
+绋嬪簭鍚姩鍚庯紝鍦ㄥ鏄剧ず鍣ㄧ幆澧冩垨鏄剧ず鍣ㄦ帴鍏�/鍒囨崲锛堢儹鎻掓嫈銆佷富鏄剧ず鍣ㄥ垏鎹級鍚庯紝widget 鍜� wallpaper 绐楀彛鍑虹幇鏄剧ず寮傚父锛屽寘鎷絾涓嶉檺浜庯細绐楀彛鍑虹幇鍦ㄥ睆骞曞銆佺獥鍙e畾浣嶅埌閿欒鏄剧ず鍣ㄣ�佹闈㈠眰绐楀彛涓嶅彲瑙併��
+
+---
+
+## 鏍瑰洜鍒嗘瀽
+
+### 鏍瑰洜 1锛欴PI / 鍧愭爣鍗曚綅涓嶄竴鑷达紙P0锛�
+
+**浣嶇疆**: `src/Moli.Desktop/Interop/Win32InteropService.cs:147-154`
+
+```csharp
+monitors.Add(new MonitorInfo
+{
+ Id = new MonitorId(native.Flags ? "primary" : id),
+ Bounds = ToRectD(native.Monitor), // 鈫� 鐗╃悊鍍忕礌
+ WorkArea = ToRectD(native.WorkArea), // 鈫� 鐗╃悊鍍忕礌
+ IsPrimary = native.Flags,
+ Scale = 1 // 鈫� 纭紪鐮佷负 1
+});
+```
+
+`GetMonitorInfo` 杩斿洖鐨� `MONITORINFOEX.Monitor / WorkArea` 鏄�**鐗╃悊鍍忕礌**锛屼絾 WPF 鐨� `Window.Left/Top/Width/Height` 鏄�**璁惧鏃犲叧鍍忕礌锛圖IP锛�**銆傚湪闈� 100% 缂╂斁鐨勬樉绀哄櫒涓婏紙濡� 150%锛夛紝涓よ�呭瓨鍦� `Scale` 鍊嶇殑鍋忓樊锛�
+
+- 150% 缂╂斁鐨� 4K 鏄剧ず鍣細鐗╃悊 bounds = 3840脳2160锛孌IP bounds = 2560脳1440
+- 鑻ュ皢鐗╃悊鍍忕礌 3840 鐩存帴璧嬬粰 WPF Width锛岀獥鍙e搴﹀皢鏄璁$殑 1.5 鍊�
+- 鑻ュ皢 DIP 鍧愭爣 1920 璧嬬粰鐗╃悊鍍忕礌鏄剧ず鍣ㄤ綅缃� X锛岀獥鍙e皢鍙亸绉� 2/3 鐨勯鏈熻窛绂�
+
+鍚屾椂 `Scale = 1` 琚‖缂栫爜锛屾棤娉曠敤浜庝换浣曡浆鎹㈣绠椼��
+
+**褰卞搷**: 娣峰悎 DPI 鐜锛堝绗旇鏈� 150% + 澶栨帴鏄剧ず鍣� 100%锛変笅锛屽嵆浣挎嫇鎵戠洃鍚拰 WorkerW 鍖归厤閮芥纭紝绐楀彛浠嶄細閿欎綅鎴栧昂瀵稿紓甯搞��
+
+**娑夊強鐨勫簳灞傚師鐞�**:
+- `GetMonitorInfo` 鈫� 鐗╃悊鍍忕礌鍧愭爣
+- 鑾峰彇鐪熷疄 DPI锛歚GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, out dpiX, out dpiY)` 鈫� `Scale = dpiX / 96.0`
+- 杞崲鍏紡锛歚DIP = Physical / Scale`
+
+---
+
+### 鏍瑰洜 2锛氬畬鍏ㄦ病鏈夋樉绀哄櫒鍙樻洿妫�娴嬫満鍒讹紙P0锛�
+
+**浣嶇疆**: `src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs:260-264`
+
+```csharp
+private void ReconcileCurrentMonitors()
+{
+ var monitors = _interop.GetMonitors();
+ _layout.ReconcileMonitors(monitors);
+}
+```
+
+璇ユ柟娉曚粎鍦� `StartAsync` 涓皟鐢�**涓�娆�**銆備唬鐮佷腑娌℃湁浠讳綍 `WM_DISPLAYCHANGE`銆乣SystemEvents.DisplaySettingsChanged` 鎴� `HwndSource.AddHook` 閽╁瓙銆�
+
+褰撶敤鎴锋彃鎷旀樉绀哄櫒鎴栧垏鎹富鏄剧ず鍣ㄥ悗锛屽簲鐢ㄥ畬鍏ㄤ笉鎰熺煡鎷撴墤鍙樺寲锛岀獥鍙d粛鐣欏湪鏃у潗鏍囦笂銆�
+
+**褰卞搷**: 鏄剧ず鍣ㄥ彉鏇村悗锛屾墍鏈� surface 绐楀彛鐨勫睆骞曞潗鏍囧け鏁堬紝widget 鍙兘鏄剧ず鍦ㄥ凡涓嶅瓨鍦ㄧ殑鏄剧ず鍣ㄥ尯鍩熴��
+
+---
+
+### 鏍瑰洜 3锛歐orkerW 绛栫暐鍦ㄥ鏄剧ず鍣ㄤ笅鐨勪袱涓棶棰橈紙P0锛�
+
+#### 闂 A锛氬彧鍙栫涓�涓� WorkerW锛屾湭鍖哄垎鏄剧ず鍣�
+
+**浣嶇疆**: `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs:96-105`
+
+```csharp
+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);
+```
+
+鎵�鏈� Desptop 灞傜殑 window 閮借 reparent 鍒板悓涓�涓� WorkerW銆�
+
+#### 闂 B锛歋etParent 鍚庝娇鐢ㄥ睆骞曠粷瀵瑰潗鏍囷紝鏈浆涓虹埗瀹㈡埛鍖哄潗鏍�
+
+**浣嶇疆**: `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs:48-55`
+
+```csharp
+NativeMethods.SetWindowPos(
+ hwnd, IntPtr.Zero,
+ (int)bounds.X, (int)bounds.Y, // 鈫� 灞忓箷缁濆鍧愭爣
+ (int)bounds.Width, (int)bounds.Height,
+ ...);
+```
+
+`SetParent` 鍚庯紝瀛愮獥鍙g殑鍧愭爣鏄浉瀵圭埗绐楀彛**瀹㈡埛鍖哄師鐐�**鐨勩�傝嫢 WorkerW 鐨勫師鐐规槸璇ユ樉绀哄櫒宸︿笂瑙掞紝鍓睆 widget锛堝睆骞曞潗鏍� X=2560锛夐渶瑕佸噺鍘绘樉绀哄櫒鍘熺偣锛�2560鈫�0锛夛紝鍚﹀垯瀛愮獥鍙e潗鏍囪秴鍑虹埗绐楀彛鍖哄煙涓嶅彲瑙併��
+
+浠g爜涓病鏈夎皟鐢� `GetWindowRect` 鑾峰彇 WorkerW 鐨勫睆骞曚綅缃紝涔熸病鏈� `ScreenToClient` 鎴� `MapWindowPoints` 鍋氬潗鏍囪浆鎹€��
+
+**鍏充簬 WorkerW 鎷撴墤鐨勪簨瀹�**锛堟緞娓呭師鏈夊亣璁撅級:
+
+Win10/11 涓婏紝Explorer 鐨� WorkerW 瀛樺湪涓ょ甯歌褰㈡�侊細
+1. **鍗� WorkerW 妯法铏氭嫙妗岄潰**: 涓�涓� WorkerW 瑕嗙洊鎵�鏈夋樉绀哄櫒缁勫悎鎴愮殑铏氭嫙妗岄潰鍖哄煙锛堝 3840脳1080锛夈�傛鏃跺瓙绐楀彛鍧愭爣灏辨槸灞忓箷缁濆鍧愭爣锛孲etParent 鍚庢棤闇�棰濆鍙樻崲銆�
+2. **姣忓睆涓�涓� WorkerW**: 姣忎釜鏄剧ず鍣ㄥ搴斾竴涓嫭绔嬬殑 WorkerW锛屽師鐐瑰嵆璇ユ樉绀哄櫒宸︿笂瑙掋��
+
+瀹炵幇蹇呴』鍚屾椂瑕嗙洊涓ょ褰㈡�侊細鍏堝垽鏂� WorkerW 鐨� `GetWindowRect` 鏄惁瑕嗙洊澶氫釜鏄剧ず鍣ㄥ尯鍩燂紝鍐嶅喅瀹氬潗鏍囩瓥鐣ャ��
+
+**褰卞搷**: 妗岄潰灞傜獥鍙e湪闈為灞忎笂涓嶅彲瑙佹垨浣嶇疆閿欒銆�
+
+---
+
+### 鏍瑰洜 4锛氫富鏄剧ず鍣� MonitorId 鍥哄畾涓鸿涔� ID "primary"锛圥1锛�
+
+**浣嶇疆**: `src/Moli.Desktop/Interop/Win32InteropService.cs:148-149`
+
+```csharp
+Id = new MonitorId(native.Flags ? "primary" : id),
+```
+
+涓绘樉绀哄櫒鐨� MonitorId 濮嬬粓涓� `"primary"`锛堝拷鐣ョ湡瀹炶澶囧悕濡� `\\.\DISPLAY1`锛夛紝闈炰富鏄剧ず鍣ㄦ墠浣跨敤璁惧鍚嶃�俙IsPrimary` 瀛楁鏈韩宸叉爣璁颁富鏄剧ず鍣紝ID 涓殑璇箟淇℃伅鏄啑浣欑殑銆�
+
+**褰卞搷**: 鐢ㄦ埛鍒囨崲涓绘樉绀哄櫒鍚庯紝涔嬪墠淇濆瓨 `"primary"` 鐨� widget 甯冨眬鐩存帴鏄犲皠鍒版柊涓绘樉绀哄櫒锛涗繚瀛樿澶囧悕鐨� widget 鍙兘鍥犲師鏄剧ず鍣ㄤ笉鍐嶆槸涓绘樉绀哄櫒鑰屽尮閰嶅紓甯搞��
+
+**DeviceName 绋冲畾鎬ч檺鍒�**: `\\.\DISPLAYn` 鍦ㄩ噸鎻掋�侀┍鍔ㄩ噸瑁呫�佹嫇鎵戝彉鍖栧悗缂栧彿鍙兘鍙樺寲锛屽苟闈炲畬鍏ㄧǔ瀹氱殑韬唤鏍囪瘑銆傛洿绋冲仴鐨勬柟妗堥渶瑕� `QueryDisplayConfig` 鑾峰彇璁惧瀹炰緥璺緞鎴栦娇鐢ㄩ�傞厤鍣ㄥ悕绉颁綔涓哄閫夈�傛湰鏂囨柟妗� 3 涓細棰濆璁ㄨ杩欎竴鐐广��
+
+---
+
+### 鏍瑰洜 5锛氭嫋鎷借法灞忔嫋鏀句笉鏇存柊 MonitorId锛圥1锛�
+
+**浣嶇疆**: `src/Moli.Desktop/Windows/WidgetWindow.cs:216-228`
+
+```csharp
+private async void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+{
+ var bounds = new RectD(Left, Top, Width, Height);
+ await _commitLayoutAsync(_layout.InstanceId,
+ new WidgetLayoutPatch { Bounds = bounds }, // 鈫� 鍙湁 Bounds锛屾病鏈� MonitorId
+ CancellationToken.None);
+}
+```
+
+鐢ㄦ埛灏� widget 浠庝竴涓樉绀哄櫒鎷栧埌鍙︿竴涓樉绀哄櫒鍚庯紝`MonitorId` 浠嶆寚鍚戝師鏄剧ず鍣ㄣ�傚悗缁� `ReconcileMonitors` 鎸夐敊璇殑 MonitorId 绾︽潫锛屽彲鑳藉鑷� widget 琚帹鍥炲師鏄剧ず鍣ㄦ垨瑁佸壀寮傚父銆�
+
+**褰卞搷**: 璺ㄥ睆鎷栨斁鍚庡竷灞�韬唤涓庝綅缃笉涓�鑷达紝绾︽潫/鎸佷箙鍖栧潎鍑洪敊銆�
+
+---
+
+### 鏍瑰洜 6锛歐allpaper 浠呰鐩栧崟涓樉绀哄櫒锛圥2锛�
+
+**浣嶇疆**: `src/Moli.Desktop/Windows/RuntimeSurfaceController.cs:128-137`
+
+```csharp
+var monitor = _interop.GetMonitors()
+ .FirstOrDefault(monitor => monitor.IsPrimary)
+ ?? _interop.GetMonitors().First();
+_wallpaper = new WallpaperWindow(plugin, monitor, ...);
+```
+
+**褰卞搷**: 澶氬睆鐢ㄦ埛鍙兘鍦ㄤ富鏄剧ず鍣ㄧ湅鍒� wallpaper銆�
+
+---
+
+### 鏍瑰洜 7锛歀ayoutManager 涓嶆洿鏂拌繍琛屾椂 MonitorSnapshot锛圥3锛�
+
+**浣嶇疆**: `src/Moli.Desktop/Layout/LayoutManager.cs:128-169`
+
+`ReconcileMonitors` 鍙洿鏂� `_document.Instances`锛屼笉鏇存柊 `_document.Monitors`銆俙FindLatestMonitor()` 浠� `_document.Monitors` 璇诲彇鏈�鍚庝竴娆℃寔涔呭寲鐨勫揩鐓э紝鑰岄潪褰撳墠瀹為檯鏄剧ず鍣ㄦ暟鎹��
+
+**褰卞搷**: reconcile 涔嬪悗鐨� `Constrain` 璁$畻鍙兘浣跨敤杩囨湡鏄剧ず鍣� bounds銆�
+
+---
+
+## 瑙e喅鏂规
+
+---
+
+### 鏂规 1锛氱粺涓� DPI 鍧愭爣鑾峰彇涓庤浆鎹� 鉁揘EW
+
+**姒傝堪**: 鍦� `GetMonitors()` 涓幏鍙栫湡瀹� DPI 骞跺~鍏� `Scale`锛屾墍鏈夌獥鍙e畾浣嶄娇鐢� DIP 鍧愭爣锛屽湪闇�瑕佺墿鐞嗗儚绱犵殑 Win32 璋冪敤澶勫仛杞崲銆�
+
+**淇敼鐐�**:
+
+1. `NativeMethods.cs` 鏂板 P/Invoke锛�
+
+```csharp
+// 鑾峰彇姣忎釜鏄剧ず鍣ㄧ殑鏈夋晥 DPI
+[DllImport("shcore.dll", SetLastError = true)]
+internal static extern int GetDpiForMonitor(
+ IntPtr hMonitor, int dpiType, out uint dpiX, out uint dpiY);
+
+internal const int MDT_EFFECTIVE_DPI = 0;
+```
+
+2. `Win32InteropService.GetMonitors()` 濉厖鐪熷疄 Scale锛屽苟灏� Bounds/WorkArea 杞负 DIP锛�
+
+```csharp
+monitors.Add(new MonitorInfo
+{
+ Id = new MonitorId(id),
+ Bounds = ToRectD(native.Monitor), // 鐗╃悊鍍忕礌锛屾殏瀛�
+ WorkArea = ToRectD(native.WorkArea), // 鐗╃悊鍍忕礌锛屾殏瀛�
+ IsPrimary = native.Flags,
+ Scale = scale // 浠� GetDpiForMonitor 鑾峰彇
+});
+
+// 鍦ㄥ惊鐜粨鏉熷悗缁熶竴杞崲
+// Bounds / WorkArea 缁熶竴杞负 DIP 渚涗笂灞備娇鐢�
+monitor.Bounds = new RectD(
+ monitor.Bounds.X / monitor.Scale,
+ monitor.Bounds.Y / monitor.Scale,
+ monitor.Bounds.Width / monitor.Scale,
+ monitor.Bounds.Height / monitor.Scale);
+// WorkArea 鍚岀悊
+```
+
+3. 鎵�鏈� `SetWindowPos` 璋冪敤澶勶紙`WorkerWDesktopLayerStrategy`銆乣BottomDesktopLayerStrategy`锛夐渶瑕佸皢 DIP 鍧愭爣杩樺師涓虹墿鐞嗗儚绱狅細
+
+```csharp
+// WidgetWindow / WallpaperWindow 浼犻�� DIP bounds
+// 鍦� Win32 璋冪敤鍓嶈浆鎹�
+var physicalX = (int)(dipBounds.X * monitor.Scale);
+var physicalY = (int)(dipBounds.Y * monitor.Scale);
+var physicalW = (int)(dipBounds.Width * monitor.Scale);
+var physicalH = (int)(dipBounds.Height * monitor.Scale);
+```
+
+4. WPF 鐨� `Window.Left/Top/Width/Height` 鏈韩灏辨槸 DIP锛屾墍浠ヤ粠 layout 璇诲彇鐨勫�肩洿鎺ヨ祴缁� WPF 绐楀彛锛屾棤闇�棰濆杞崲銆傚叧閿槸瑕佷繚璇佸瓨鍌ㄥ埌 layout 鐨勫潗鏍囧凡缁忔槸 DIP銆�
+
+**娑夊強鏂囦欢**:
+- `src/Moli.Desktop/Interop/NativeMethods.cs`
+- `src/Moli.Desktop/Interop/Win32InteropService.cs`
+- `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs`
+- `src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs`
+
+---
+
+### 鏂规 2锛氭坊鍔犳樉绀哄櫒鍙樻洿鐩戝惉锛堝父椹绘秷鎭獥鍙o級
+
+**姒傝堪**: 鍦ㄥ簲鐢ㄧ骇鍒垱寤哄父椹绘秷鎭獥鍙o紝鐩戝惉 `WM_DISPLAYCHANGE` 鍙婂叾浠栨嫇鎵戠浉鍏虫秷鎭紝瑙﹀彂瀹屾暣鐨勬樉绀哄櫒鎷撴墤鍚屾銆�
+
+**鍏抽敭淇**: 涓嶈兘鎸傚湪 `ManagementWindow` 涓婏紙璇ョ獥鍙f寜闇�鍒涘缓銆佸彲鑳借鍏抽棴锛夈�傚簲鍒涘缓搴旂敤绾у父椹婚殣钘忕獥鍙f垨鎸傝浇鍦� `TrayShell` / `Application.MainWindow` 涓娿��
+
+**瀹炵幇鏂瑰紡**:
+
+鍒涘缓 `DisplayChangeMonitor` 鏈嶅姟绫伙紝鍐呴儴缁存姢涓�涓殣钘忕殑 `HwndSource`锛�
+
+```csharp
+public sealed class DisplayChangeMonitor : IDisposable
+{
+ private HwndSource? _source;
+ private CancellationTokenSource? _debounceCts;
+ private readonly SemaphoreSlim _syncLock = new(1, 1);
+ private readonly IDesktopRuntime _runtime;
+
+ public void Start()
+ {
+ var parameters = new HwndSourceParameters("MoliDisplayMonitor")
+ {
+ Width = 0, Height = 0,
+ WindowStyle = 0,
+ ExtendedWindowStyle = NativeMethods.WsExToolWindow | NativeMethods.WsExNoActivate
+ };
+ _source = new HwndSource(parameters);
+ _source.AddHook(WndProc);
+ }
+
+ private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
+ {
+ const int WM_DISPLAYCHANGE = 0x007E;
+ const int WM_SETTINGCHANGE = 0x001A;
+ const int WM_DEVICECHANGE = 0x0219;
+
+ if (msg is WM_DISPLAYCHANGE or WM_SETTINGCHANGE or WM_DEVICECHANGE)
+ {
+ DebounceReconcileAsync();
+ }
+ return IntPtr.Zero;
+ }
+
+ private void DebounceReconcileAsync()
+ {
+ _debounceCts?.Cancel();
+ _debounceCts = new CancellationTokenSource();
+ var token = _debounceCts.Token;
+ // 闃叉姈 500ms锛岄伩鍏嶈繛缁秷鎭Е鍙戝娆� reconcile
+ Task.Delay(500, token).ContinueWith(async _ =>
+ {
+ if (token.IsCancellationRequested) return;
+ await _syncLock.WaitAsync();
+ try
+ {
+ await Application.Current.Dispatcher.InvokeAsync(async () =>
+ await _runtime.OnDisplayTopologyChangedAsync(CancellationToken.None));
+ }
+ finally { _syncLock.Release(); }
+ }, token);
+ }
+
+ public void Dispose()
+ {
+ _debounceCts?.Cancel();
+ _source?.Dispose();
+ }
+}
+```
+
+**鍚屾閫昏緫**锛坄IDesktopRuntime` 鏂板 `OnDisplayTopologyChangedAsync`锛�:
+
+```
+OnDisplayTopologyChangedAsync:
+ 1. 闃叉姈绛夊緟锛圖ebounceReconcileAsync 宸插鐞嗭級
+ 2. 鑾峰彇鏈�鏂版樉绀哄櫒鍒楄〃 鈫� _interop.GetMonitors()
+ 3. 璋冪敤 _layout.ReconcileMonitors(monitors) 杩佺Щ widget
+ 4. 璋冪敤 _layout.SaveAsync() 鎸佷箙鍖�
+ 5. 璋冪敤 _surfaces.SyncAllLayoutsAsync(monitors) 閲嶆柊搴旂敤鎵�鏈夌獥鍙e竷灞�
+ 6. 璋冪敤 _surfaces.SyncWallpaperMonitorsAsync(monitors) 鍚屾 wallpaper
+ 7. 瀵� Desktop 灞傜獥鍙i噸鏂拌皟鐢� MoveToDesktopLayer锛圵orkerW 鍙兘宸查噸寤猴級
+```
+
+**`IRuntimeSurfaceController` 闇�瑕佹柊澧炵殑鏂规硶**:
+
+```csharp
+// 鍚屾鎵�鏈夌幇鏈� widget 绐楀彛鐨勫竷灞�
+Task SyncAllLayoutsAsync(IReadOnlyList<MonitorInfo> monitors, CancellationToken ct);
+
+// 鍚屾 wallpaper锛堝垱寤�/閿�姣�/閲嶅畾浣嶏級
+Task SyncWallpaperMonitorsAsync(IReadOnlyList<MonitorInfo> monitors, CancellationToken ct);
+
+// 閲嶅缓鎵�鏈� Desktop 灞傜獥鍙g殑 WorkerW 闄勭潃
+Task ReattachDesktopLayersAsync(IReadOnlyList<MonitorInfo> monitors, CancellationToken ct);
+```
+
+**娑夊強鏂囦欢**:
+- `src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs`
+- `src/Moli.Desktop/Runtime/IDesktopRuntime.cs`
+- `src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs`
+- `src/Moli.Desktop/Windows/RuntimeSurfaceController.cs`
+- 鏂板缓 `src/Moli.Desktop/Interop/DisplayChangeMonitor.cs`锛堟垨鏀惧湪 Host 灞傦級
+
+---
+
+### 鏂规 3锛歐orkerW 鎸夋樉绀哄櫒鍖归厤 + 鍧愭爣杞崲
+
+**姒傝堪**: 鏀堕泦鎵�鏈� WorkerW 鍙ユ焺鍙婂睆骞曚綅缃紝鏍规嵁鍏舵嫇鎵戝舰鎬侊紙鍗曟í璺ㄦ垨澶氱嫭绔嬶級鍐冲畾鍖归厤鍜屽潗鏍囪浆鎹㈢瓥鐣ャ��
+
+**瀹炵幇姝ラ**:
+
+1. 鏀堕泦鎵�鏈夊寘鍚� `SHELLDLL_DefView` 瀛愮獥鍙g殑 WorkerW锛岃褰曞叾 HWND 鍜屽睆骞� Rect锛�
+
+```csharp
+private static List<(IntPtr Hwnd, NativeMethods.Rect ScreenRect)> EnumerateWorkerWindows()
+{
+ var results = new List<(IntPtr, NativeMethods.Rect)>();
+ NativeMethods.EnumWindows((topHandle, _) =>
+ {
+ var shellView = NativeMethods.FindWindowEx(
+ topHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
+ if (shellView == IntPtr.Zero) return true;
+
+ var workerW = NativeMethods.FindWindowEx(
+ IntPtr.Zero, topHandle, "WorkerW", null);
+ if (workerW != IntPtr.Zero &&
+ NativeMethods.GetWindowRect(workerW, out var rect))
+ {
+ results.Add((workerW, rect));
+ }
+ return true;
+ }, IntPtr.Zero);
+ return results;
+}
+```
+
+2. 鍒ゆ柇 WorkerW 鎷撴墤褰㈡�佸苟閫夋嫨鍖归厤绛栫暐锛�
+
+```
+if (workerWs.Count == 1 && workerW 妯法澶氫釜鏄剧ず鍣ㄥ尯鍩�)
+ 鈫� 鍗� WorkerW 妯″紡锛氱洿鎺ョ敤杩欎竴涓� WorkerW锛屼笉闇�瑕� per-monitor 鍖归厤
+ 鈫� 鍧愭爣杞崲锛氬瓙绐楀彛鍧愭爣 = 灞忓箷缁濆鍧愭爣锛圵orkerW 鍘熺偣鍗宠櫄鎷熸闈㈠師鐐癸級
+
+else (姣忓睆涓�涓� WorkerW)
+ 鈫� 鎸夐噸鍙犻潰绉尮閰� WorkerW 涓� MonitorInfo.Bounds
+ 鈫� 鍧愭爣杞崲锛氬瓙绐楀彛鍧愭爣 = 灞忓箷缁濆鍧愭爣 - WorkerW 鍘熺偣鍧愭爣锛圡apWindowPoints 鎴栨墜鍔ㄨ绠楋級
+```
+
+3. 鍖归厤鏃朵娇鐢�**閲嶅彔闈㈢Н鏈�澶�**鑰岄潪 X/Y 绮剧‘鐩哥瓑锛圖PI 缂╂斁鎴栫獥鍙h竟妗嗗彲鑳藉鑷村井灏忓亸宸級锛�
+
+```csharp
+private static IntPtr? FindBestWorkerW(
+ RectD monitorBounds,
+ List<(IntPtr Hwnd, NativeMethods.Rect ScreenRect)> workerWs)
+{
+ (IntPtr Hwnd, double Overlap) best = (IntPtr.Zero, 0);
+ foreach (var (hwnd, rect) in workerWs)
+ {
+ var wr = new RectD(rect.Left, rect.Top,
+ rect.Right - rect.Left, rect.Bottom - rect.Top);
+ var overlap = IntersectionArea(monitorBounds, wr);
+ if (overlap > best.Overlap)
+ best = (hwnd, overlap);
+ }
+ return best.Hwnd != IntPtr.Zero ? best.Hwnd : null;
+}
+```
+
+4. `TryAttachDesktopWindow` 鍦� `SetWindowPos` 鍓嶅仛鍧愭爣杞崲锛�
+
+```csharp
+// 鍗曟í璺� WorkerW锛氬睆骞曞潗鏍囧嵆瀛愮獥鍙e潗鏍�
+// 姣忓睆 WorkerW锛氬噺鍘� WorkerW 鍘熺偣
+int childX = (int)bounds.X;
+int childY = (int)bounds.Y;
+if (!isSingleSpanningWorkerW)
+{
+ childX -= workerWRect.Left;
+ childY -= workerWRect.Top;
+}
+NativeMethods.SetWindowPos(hwnd, IntPtr.Zero,
+ childX, childY, (int)bounds.Width, (int)bounds.Height, ...);
+```
+
+5. `IWin32InteropService.MoveToDesktopLayer` 鎵╁睍涓轰紶閫� `MonitorInfo`锛堝惈 Scale锛屾柟妗� 1锛夛細
+
+```csharp
+void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode,
+ RectD dipBounds, MonitorInfo monitor);
+```
+
+6. 缁存姢 WorkerW 鏄犲皠缂撳瓨锛屽湪鏄剧ず鍣ㄥ彉鏇存椂閫氳繃 `ReattachDesktopLayersAsync` 閲嶅缓銆�
+
+**娑夊強鏂囦欢**:
+- `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs`
+- `src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs`
+- `src/Moli.Desktop/Interop/IWin32InteropService.cs`
+- `src/Moli.Desktop/Interop/Win32InteropService.cs`
+- `src/Moli.Desktop/Interop/NativeMethods.cs`锛堟柊澧� `GetWindowRect` P/Invoke锛�
+- `src/Moli.Desktop/Windows/WidgetWindow.cs`
+- `src/Moli.Desktop/Windows/WallpaperWindow.cs`
+
+---
+
+### 鏂规 4锛歁onitorId 浣跨敤璁惧鍚� + "primary" 鏄惧紡杩佺Щ
+
+**姒傝堪**:
+- `GetMonitors()` 涓Щ闄� `"primary"` 璇箟 ID锛岀粺涓�浣跨敤璁惧鍚�
+- 鍦� `LayoutManager` 鍔犺浇/Reconcile 鏃讹紝灏嗘棫鐨� `"primary"` 鏄惧紡鏄犲皠涓哄綋鍓嶄富鏄剧ず鍣ㄧ殑璁惧鍚嶏紝閬垮厤鎵�鏈夋棫甯冨眬琚綋浣滃鍎�
+
+**姝ラ 1 鈥� Win32InteropService 涓嶅啀瑕嗙洊 ID**:
+
+```diff
+- Id = new MonitorId(native.Flags ? "primary" : id),
++ Id = new MonitorId(id),
+```
+
+**姝ラ 2 鈥� LayoutManager 澧炲姞杩佺Щ閫昏緫**:
+
+鍦� `ReconcileMonitors` 涓紝瀵� `MonitorId == "primary"` 鐨勬棫甯冨眬鍋氭樉寮忚縼绉伙細
+
+```csharp
+// ReconcileMonitors 鍐�
+var primary = monitors.FirstOrDefault(m => m.IsPrimary) ?? monitors[0];
+
+if (layout.MonitorId.Value == "primary")
+{
+ // 鏃� primary 鈫� 鏄犲皠鍒板綋鍓嶄富鏄剧ず鍣ㄨ澶囧悕
+ // 灏介噺淇濈暀鍘熺浉瀵逛綅缃紙鍩轰簬鏃ф枃妗d腑鏈�鍚庣殑 MonitorSnapshot锛�
+ var oldSnapshot = _document.Monitors
+ .OrderByDescending(s => s.CapturedAt)
+ .FirstOrDefault();
+ var oldPrimary = oldSnapshot?.Monitors
+ .FirstOrDefault(m => m.Id.Value == "primary");
+ if (oldPrimary is not null)
+ {
+ // 鏈夋棫蹇収锛氭寜鏃т富灞忓拰鏂颁富灞忕殑姣斾緥缂╂斁浣嶇疆
+ layout = ScaleLayoutBetweenMonitors(layout, oldPrimary, primary);
+ }
+ else
+ {
+ // 鏃犲揩鐓э細灞呬腑鍒版柊涓诲睆
+ layout = CenterInMonitor(layout, primary);
+ }
+ _document.Instances[i] = layout;
+ continue;
+}
+```
+
+**姝ラ 3 鈥� DeviceName 绋冲畾鎬ц鏄�**:
+
+`\\.\DISPLAYn` 鍦ㄤ互涓嬪満鏅彲鑳藉彉鍖栵細
+- USB-C/Thunderbolt 鏄剧ず鍣ㄩ噸鏂版彃鎷�
+- 鏄惧崱椹卞姩鏇存柊
+- Windows 鏄剧ず鎷撴墤閲嶇疆
+
+鐭湡锛堝悓涓�娆� Windows 浼氳瘽鍐咃級璁惧鍚嶇ǔ瀹氾紱闀挎湡鍙�冭檻鏇寸ǔ鍋ョ殑韬唤鏍囪瘑锛�
+- 浣跨敤 `QueryDisplayConfig` + `DISPLAYCONFIG_PATH_INFO` 鑾峰彇璁惧瀹炰緥璺緞
+- 鎴栫粍鍚堥�傞厤鍣ㄥ悕绉� + 搴忓垪鍙凤紙閫氳繃 WMI `Win32_DesktopMonitor`锛�
+- 鎴栧洖閫�绛栫暐锛氬綋璁惧鍚嶅尮閰嶅け璐ユ椂锛屾寜閲嶅彔闈㈢Н鍖归厤锛堜笌鏂规 3 鐨� WorkerW 鍖归厤绫讳技锛�
+
+**娑夊強鏂囦欢**:
+- `src/Moli.Desktop/Interop/Win32InteropService.cs`
+- `src/Moli.Desktop/Layout/LayoutManager.cs`
+
+---
+
+### 鏂规 5锛氭嫋鎷芥澗鎵嬫椂閲嶆柊璁$畻 MonitorId
+
+**姒傝堪**: `WidgetWindow.OnMouseLeftButtonUp` 鎻愪氦甯冨眬鏃讹紝鏍规嵁 widget 涓績鐐规墍鍦ㄦ樉绀哄櫒鏇存柊 MonitorId銆�
+
+**淇敼鐐�**:
+
+`src/Moli.Desktop/Windows/WidgetWindow.cs:216-228`:
+
+```diff
+ private async void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+ {
+ var bounds = new RectD(Left, Top, Width, Height);
++ var centerX = bounds.X + bounds.Width / 2;
++ var centerY = bounds.Y + bounds.Height / 2;
++ var monitorId = _interop.GetMonitors()
++ .FirstOrDefault(m => centerX >= m.Bounds.X
++ && centerX < m.Bounds.Right
++ && centerY >= m.Bounds.Y
++ && centerY < m.Bounds.Bottom)
++ ?.Id ?? _layout.MonitorId;
+ await _commitLayoutAsync(_layout.InstanceId,
+- new WidgetLayoutPatch { Bounds = bounds },
++ new WidgetLayoutPatch { Bounds = bounds, MonitorId = monitorId },
+ CancellationToken.None);
+ }
+```
+
+WidgetWindow 闇�瑕佹寔鏈� `IWin32InteropService` 寮曠敤锛堝綋鍓嶆瀯閫犲嚱鏁版病鏈夛級銆�
+
+**鏇寸ǔ鍋ョ殑鏂规**: 鏍规嵁 widget 涓庡悇鏄剧ず鍣ㄧ殑**鍙闈㈢Н閲嶅彔鏈�澶ц��**纭畾 MonitorId锛岃�岄潪浠呬腑鐐瑰垽鏂紙widget 鍙兘妯法涓や釜鏄剧ず鍣級銆�
+
+**娑夊強鏂囦欢**:
+- `src/Moli.Desktop/Windows/WidgetWindow.cs`
+
+---
+
+### 鏂规 6锛歐allpaper 鏀寔澶氭樉绀哄櫒
+
+**姒傝堪**: 灏嗗崟涓� `_wallpaper` 鏀逛负姣忎釜鏄剧ず鍣ㄤ竴涓� `WallpaperWindow`銆�
+
+**淇敼鐐�**:
+
+1. `RuntimeSurfaceController` 涓皢 `_wallpaper` 鏀逛负瀛楀吀锛�
+
+```csharp
+private readonly Dictionary<MonitorId, WallpaperWindow> _wallpapers = [];
+```
+
+2. `EnableWallpaperAsync` 涓烘墍鏈夋樉绀哄櫒鍒涘缓 WallpaperWindow锛�
+
+```csharp
+public Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, ...)
+{
+ var monitors = _interop.GetMonitors();
+ foreach (var monitor in monitors)
+ {
+ var wallWin = new WallpaperWindow(plugin, monitor, ...);
+ _wallpapers[monitor.Id] = wallWin;
+ wallWin.Show();
+ }
+}
+```
+
+3. `DisableWallpaperAsync` 鍏抽棴鎵�鏈夈��
+
+4. `SyncWallpaperMonitorsAsync`锛堟柟妗� 2 鑱斿姩锛夛細瀵规瘮鏂版棫鏄剧ず鍣ㄥ垪琛紝鍒涘缓鏂板鐨勩�侀攢姣佺Щ闄ょ殑銆�
+
+**NFR 娉ㄦ剰 鈥� WebView2 璧勬簮鎴愭湰**: 姣忎釜 WallpaperWindow 鎸佹湁鐙珛鐨� WebView2 瀹炰緥锛屽鏄剧ず鍣ㄦ剰鍛崇潃澶氬�嶅唴瀛�/GPU 寮�閿�銆傞渶璇勪及锛�
+
+- 鏄惁鍏佽鐢ㄦ埛閰嶇疆"浠呬富灞忓绾�" vs "鍏ㄥ睆澹佺焊"
+- 鏄惁鏆傚仠涓嶅彲瑙佹樉绀哄睆鐨� WebView 娓叉煋锛坄TrySuspendAsync` / `Resume`锛�
+- 鏄惁鍏变韩 WebView 瀹炰緥锛堝鏉傦紝褰撳墠鏋舵瀯涓嶆帹鑽愶級
+
+杩欎簺鍐崇瓥褰卞搷鏂规 6 鐨勪紭鍏堢骇鏄惁淇濇寔 P2 鎴栭檷绾с��
+
+**娑夊強鏂囦欢**:
+- `src/Moli.Desktop/Windows/RuntimeSurfaceController.cs`
+- `src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs`
+- `src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs`
+
+---
+
+### 鏂规 7锛歊econcileMonitors 鏃舵洿鏂� MonitorSnapshot + 鍒嗚鲸鐜�/Dpi 鍙樺寲绛栫暐
+
+**姒傝堪**:
+- 鍦� reconcile 瀹屾垚鍚庡皢褰撳墠鏄剧ず鍣ㄥ揩鐓ц拷鍔犲埌 `_document.Monitors`
+- 鏄庣‘鍒嗚鲸鐜�/DPI 鍙樺寲鏃� widget 甯冨眬鐨勪繚鐣欑瓥鐣�
+
+**淇敼鐐� A 鈥� 鏇存柊蹇収**:
+
+```diff
+ lock (_gate)
+ {
+ for (var i = 0; i < _document.Instances.Count; i++)
+ {
+ // ... 鐜版湁 reconcile 閫昏緫 ...
+ }
+
++ _document.Monitors.Add(new MonitorSnapshot
++ {
++ CapturedAt = DateTimeOffset.UtcNow,
++ Monitors = [.. monitors]
++ });
++
++ // 闄愬埗蹇収鏁伴噺锛屼粎淇濈暀鏈�杩� 5 涓�
++ while (_document.Monitors.Count > 5)
++ _document.Monitors.RemoveAt(0);
+
+ return [.. _document.Instances];
+ }
+```
+
+**淇敼鐐� B 鈥� 鍒嗚鲸鐜�/DPI 鍙樺寲鐨勫竷灞�绛栫暐**:
+
+褰撳墠 `Constrain` 鏂规硶浠呭仛閽冲埗锛坈lamp锛夛紝涓嶆寜姣斾緥缂╂斁銆傚綋鏄剧ず鍣ㄥ垎杈ㄧ巼鍙樺寲鏃讹紙濡� 1080p鈫�4K 鎴栫浉鍙嶏級锛寃idget 浣嶇疆浠呬繚璇佸湪鍙鍖哄煙鍐咃紝涓嶄細鎸夌浉瀵规瘮渚嬩繚鐣欍��
+
+寤鸿鏄庣‘绛栫暐锛堜簩閫変竴锛夛細
+
+| 绛栫暐 | 琛屼负 | 閫傜敤鍦烘櫙 |
+|------|------|----------|
+| **閽冲埗锛堝綋鍓嶏級** | 淇濇寔缁濆浣嶇疆鍜屽ぇ灏忥紝浠呬繚璇佸湪 work area 鍐� | 涓存椂鍒嗚鲸鐜囧彉鍖栵紙濡傛父鎴忓叏灞忥級 |
+| **鐩稿姣斾緥缂╂斁** | 鎸� work area 姣斾緥缂╂斁浣嶇疆鍜屽ぇ灏� | 鎸佷箙鎬ф樉绀哄櫒鍒囨崲锛堜笉鍚屽垎杈ㄧ巼鐨勬樉绀哄櫒锛� |
+
+瀹炵幇鐩稿姣斾緥缂╂斁锛�
+
+```csharp
+// 鍦� ReconcileMonitors 涓紝褰� monitor.Id 鍖归厤浣� work area 灏哄鍙樺寲鏃�
+if (oldMonitor is not null &&
+ (oldMonitor.WorkArea.Width != monitor.WorkArea.Width ||
+ oldMonitor.WorkArea.Height != monitor.WorkArea.Height))
+{
+ var ratioX = monitor.WorkArea.Width / oldMonitor.WorkArea.Width;
+ var ratioY = monitor.WorkArea.Height / oldMonitor.WorkArea.Height;
+ layout = layout with
+ {
+ Bounds = new RectD(
+ monitor.WorkArea.X + (layout.Bounds.X - oldMonitor.WorkArea.X) * ratioX,
+ monitor.WorkArea.Y + (layout.Bounds.Y - oldMonitor.WorkArea.Y) * ratioY,
+ layout.Bounds.Width * ratioX,
+ layout.Bounds.Height * ratioY)
+ };
+}
+```
+
+姝ょ瓥鐣ラ渶涓庝骇鍝佺‘璁ゃ��
+
+**娑夊強鏂囦欢**:
+- `src/Moli.Desktop/Layout/LayoutManager.cs`
+
+---
+
+### 琛ュ厖鏂规 A锛欵xplorer 閲嶅惎 / WorkerW 澶辨晥妫�娴�
+
+**闂**: 鐫$湢/鍞ら啋銆佹潃鎺� explorer.exe銆乄in+D 绛夊満鏅彲鑳藉鑷� WorkerW 鍙ユ焺澶辨晥锛屼絾涓嶄竴瀹氳Е鍙� `WM_DISPLAYCHANGE`銆�
+
+**寤鸿**:
+- 鍦� `ReattachDesktopLayersAsync` 涓紝姣忔鍏堟牎楠屽凡缂撳瓨鐨� WorkerW 鍙ユ焺鏄惁浠嶇劧鏈夋晥锛坄IsWindow(hwnd)`锛�
+- 鑻ュけ鏁堝垯閲嶆柊鏋氫妇 WorkerW 骞堕噸寤烘槧灏�
+- 鍛ㄦ湡鎬э紙濡傛瘡 30 绉掞級鍋氫竴娆¤交閲忔牎楠岋紙浠� `IsWindow`锛屼笉閲嶅缓锛�
+
+姝ら�昏緫搴斿唴缃湪鏂规 3 鐨� WorkerW 鏄犲皠缂撳瓨涓��
+
+---
+
+### 琛ュ厖鏂规 B锛欱ottomDesktopLayerStrategy 闄嶇骇璺緞鐨� DPI 淇
+
+`BottomDesktopLayerStrategy` 鍚屾牱浣跨敤灞忓箷缁濆鍧愭爣璋冪敤 `SetWindowPos`锛屼笖涓嶅尯鍒嗘樉绀哄櫒銆傚湪鏂规 1锛圖PI锛夊拰鏂规 3锛堝潗鏍囪浆鎹級淇鍚庯紝璇ラ檷绾ц矾寰勫簲鍚屾浣跨敤鐗╃悊鍍忕礌杞崲鍚庣殑鍧愭爣銆�
+
+---
+
+### 琛ュ厖鏂规 C锛氳瘖鏂爜鎵╁睍
+
+寤鸿鏂板璇婃柇浜嬩欢鐮侊細
+- `DisplayTopologyChanged` 鈥� 鏄剧ず鍣ㄦ嫇鎵戝彉鏇�
+- `WorkerWRemapped` 鈥� WorkerW 鏄犲皠閲嶅缓
+- `LayoutMigratedFromPrimary` 鈥� 鏃� "primary" 甯冨眬杩佺Щ
+- `WorkerWValidationFailed` 鈥� WorkerW 鍙ユ焺澶辨晥闇�閲嶅缓
+
+渚夸簬楠屾敹鍜屾帓闅溿��
+
+---
+
+## 瀹炴柦浼樺厛绾�
+
+| 浼樺厛绾� | 鏂规 | 鐞嗙敱 |
+|--------|------|------|
+| **P0** | 鏂规 1锛圖PI/鍧愭爣锛� | 娣峰悎 DPI 涓嬬獥鍙d綅缃�/灏哄閿欒锛屾槸鏈�鍩虹鐨勪慨姝� |
+| **P0** | 鏂规 2锛堝彉鏇寸洃鍚級 | 涓嶆劅鐭ユ嫇鎵戝彉鍖栵紝绐楀彛鍧愭爣姘镐箙澶辨晥 |
+| **P0** | 鏂规 3锛圵orkerW 鍖归厤+鍧愭爣杞崲锛� | 妗岄潰灞傞檮鐫�鏄灞� widget 鍙鎬х殑鍓嶆彁 |
+| **P1** | 鏂规 4锛圡onitorId 杩佺Щ锛� | 褰卞搷甯冨眬鎸佷箙鍖栨纭�э紝闇�鍚�"primary"鏄惧紡杩佺Щ |
+| **P1** | 鏂规 5锛堟嫋鎷芥洿鏂� MonitorId锛� | 璺ㄥ睆鎷栨斁鏄珮棰戞搷浣滐紝韬唤涓嶄竴鑷村鑷寸害鏉熷紓甯� |
+| **P2** | 鏂规 6锛堝灞� Wallpaper锛� | 鍔熻兘澧炲己锛岄渶鍏堝畾浜у搧鑼冨洿涓� WebView 鎴愭湰 |
+| **P2** | 鏂规 7锛堝揩鐓�+甯冨眬绛栫暐锛� | 杈呭姪鎬т慨澶嶏紝瑙e喅绾︽潫璁$畻涓庡垎杈ㄧ巼鍙樺寲 |
+| **P2** | 琛ュ厖鏂规 A锛圵orkerW 澶辨晥妫�娴嬶級 | 瑕嗙洊 Explorer 閲嶅惎绛夎竟缂樺満鏅� |
+| **P3** | 琛ュ厖鏂规 B锛堥檷绾ц矾寰勶級 | 浠呭湪 WorkerW 绛栫暐澶辫触鏃惰Е鍙� |
+| **P3** | 琛ュ厖鏂规 C锛堣瘖鏂爜锛� | 寮�鍙戦獙鏀惰緟鍔� |
+
+---
+
+## 娴嬭瘯楠岃瘉寤鸿
+
+1. **娣峰悎 DPI锛�100% + 150%锛�**: 鍦ㄤ笉鍚� DPI 缂╂斁鐨勬樉绀哄櫒闂村垱寤�/绉诲姩 widget锛岄獙璇佷綅缃拰灏哄姝g‘
+2. **娣峰悎 DPI 涓嬬殑妗岄潰灞�**: 鍓樉绀哄櫒锛�150%锛変笂 widget 鍦� Desktop 灞傚彲瑙佷笖浣嶇疆姝g‘
+3. **鍙屾樉绀哄櫒 鈫� 鍗曟樉绀哄櫒鐑嫈**: 鎷旀帀鍓樉绀哄櫒锛岄獙璇佸壇鏄剧ず鍣ㄤ笂鐨� widget 鑷姩杩佺Щ鍒颁富鏄剧ず鍣�
+4. **鍗曟樉绀哄櫒 鈫� 鍙屾樉绀哄櫒鐑彃**: 鎻掑叆鍓樉绀哄櫒锛岄獙璇佸彲鍦ㄦ柊鏄剧ず鍣ㄤ笂姝e父鍒涘缓 widget
+5. **鍒囨崲涓绘樉绀哄櫒**: 閫氳繃 Windows 鏄剧ず璁剧疆鍒囨崲涓绘樉绀哄櫒锛岄獙璇� widget 鍜� wallpaper 姝g‘璺熼殢锛屾棤"灞呬腑閲嶆帓"鐨勬暟鎹洖褰�
+6. **璺ㄥ睆鎷栨斁 widget**: 灏� widget 浠庝竴涓樉绀哄櫒鎷栧埌鍙︿竴涓樉绀哄櫒锛岄獙璇� MonitorId 鏇存柊姝g‘
+7. **涓嶅悓鍒嗚鲸鐜囨樉绀哄櫒**: 鍦� 1080p 鍜� 4K 鏄剧ず鍣ㄩ棿鎷栨嫿 widget锛岄獙璇佸ぇ灏忓拰浣嶇疆绾︽潫姝g‘
+8. **鐫$湢/鍞ら啋**: 绯荤粺鐫$湢鍐嶅敜閱掞紝楠岃瘉绐楀彛浠嶅湪姝g‘浣嶇疆涓� WorkerW 闄勭潃姝e父锛堝彲鑳介渶瑕� Explorer 閲嶅惎妫�娴嬶級
+9. **RDP 杩滅▼妗岄潰**: 杩炴帴/鏂紑 RDP 浼氳瘽锛堜細鏀瑰彉鏄剧ず鍣ㄦ嫇鎵戯級锛岄獙璇佽涓烘纭�
+10. **Explorer 閲嶅惎**: 鏉�鎺� explorer.exe 鍐嶅惎鍔紝楠岃瘉妗岄潰灞傞噸鏂伴檮鐫�
+11. **Win+D / 鏄剧ず妗岄潰**: 楠岃瘉 WidgetWindow 涓嶈甯﹀埌鍓嶅彴
+
+---
+
+## 娑夊強鏂囦欢娓呭崟锛堟渶缁堢増 v2锛�
+
+| 鏂囦欢 | P0 鏂规 | P1 鏂规 | P2 鏂规 | P3 琛ュ厖 |
+|------|---------|---------|---------|---------|
+| `NativeMethods.cs` | 鉁� | | | |
+| `Win32InteropService.cs` | 鉁� | | | |
+| `WorkerWDesktopLayerStrategy.cs` | 鉁� | | | 鉁� |
+| `BottomDesktopLayerStrategy.cs` | | | | 鉁� |
+| `IDesktopLayerStrategy.cs` | 鉁� | | | |
+| `IWin32InteropService.cs` | 鉁� | | | |
+| `DesktopRuntimeCoordinator.cs` | 鉁� | | 鉁� | |
+| `IDesktopRuntime.cs` | 鉁� | | | |
+| `RuntimeSurfaceController.cs` | 鉁� | | 鉁� | |
+| `IRuntimeSurfaceController.cs` | 鉁� | | 鉁� | |
+| `WidgetWindow.cs` | 鉁� | 鉁� | | |
+| `WallpaperWindow.cs` | 鉁� | | | |
+| `LayoutManager.cs` | | 鉁� | 鉁� | |
+| `DiscoveryChangeMonitor.cs`锛堟柊寤猴級 | 鉁� | | | |
+| `DiagnosticCodes.cs` | | | | 鉁� |
diff --git a/scripts/publish-to-apps.ps1 b/scripts/publish-to-apps.ps1
index 09aca40..a82d274 100644
--- a/scripts/publish-to-apps.ps1
+++ b/scripts/publish-to-apps.ps1
@@ -1,7 +1,7 @@
param(
[string]$Configuration = "Release",
[string]$Runtime = "win-x64",
- [string]$TargetRoot = "Y:\Application",
+ [string]$TargetRoot = "D:\lin\tools\Moli.Desktop\Moli.Desktop",
[string]$AppName = "Moli.Desktop",
[switch]$SelfContained,
[switch]$SkipTests,
diff --git a/src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs b/src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs
index 0af2ed1..d728e74 100644
--- a/src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs
+++ b/src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs
@@ -9,8 +9,9 @@
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 bool LayeredEnabled { get; private set; }
public DesktopLayerMode? LayerMode { get; private set; }
+ public MonitorInfo? LayerMonitor { get; private set; }
public Moli.Desktop.Layout.RectD? LayerBounds { get; private set; }
public bool RestoredTopLevel { get; private set; }
@@ -22,17 +23,12 @@
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 SetLayered(IntPtr hwnd, bool enabled) => LayeredEnabled = enabled;
- public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor)
+ public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor, Moli.Desktop.Layout.RectD bounds)
{
LayerMode = mode;
- LayerBounds = monitor.Bounds;
- }
-
- public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, Moli.Desktop.Layout.RectD bounds)
- {
- LayerMode = mode;
+ LayerMonitor = monitor;
LayerBounds = bounds;
}
@@ -47,7 +43,8 @@
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
+ IsPrimary = true,
+ Scale = 1
}
];
}
diff --git a/src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs b/src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs
index 01c32f2..c1cf9cd 100644
--- a/src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs
+++ b/src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs
@@ -1,3 +1,4 @@
+using Moli.Desktop.Configuration;
using Moli.Desktop.Interop;
namespace Moli.Desktop.Tests.Interop;
@@ -13,15 +14,23 @@
interop.SetClickThrough(hwnd, true);
interop.SetToolWindow(hwnd, true);
interop.SetNoActivate(hwnd, true);
- interop.SetLayered(hwnd, true, 128);
- interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, new Moli.Desktop.Layout.RectD(10, 20, 300, 120));
+ interop.SetLayered(hwnd, true);
+ var monitor = 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,
+ Scale = 1
+ };
+ interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, monitor, new Moli.Desktop.Layout.RectD(10, 20, 300, 120));
interop.RestoreTopLevelWindow(hwnd);
interop.SetBottomMost(hwnd);
Assert.True(interop.ClickThroughEnabled);
Assert.True(interop.ToolWindowEnabled);
Assert.True(interop.NoActivateEnabled);
- Assert.Equal(128, interop.Opacity);
+ Assert.True(interop.LayeredEnabled);
Assert.Equal(new Moli.Desktop.Layout.RectD(10, 20, 300, 120), interop.LayerBounds);
Assert.True(interop.RestoredTopLevel);
Assert.Single(interop.GetMonitors());
diff --git a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs b/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
index 7edad8b..3b3ebde 100644
--- a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
+++ b/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
@@ -169,7 +169,8 @@
new FakeWin32InteropService(),
diagnostics,
events,
- surface);
+ surface,
+ new DisplayChangeMonitor());
return new RuntimeFixture(runtime, configuration, events, surface, widgetId);
}
@@ -237,5 +238,11 @@
public Task DisableWallpaperAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
+
+ public Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
+
+ public Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
+
+ public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
}
}
diff --git a/src/Moli.Desktop/Host/DesktopHostBuilder.cs b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
index 182b8fb..e2f0b12 100644
--- a/src/Moli.Desktop/Host/DesktopHostBuilder.cs
+++ b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -54,6 +54,7 @@
services.AddSingleton<ILayoutManager, LayoutManager>();
services.AddSingleton<IDesktopLayerStrategy, WorkerWDesktopLayerStrategy>();
services.AddSingleton<IDesktopLayerStrategy, BottomDesktopLayerStrategy>();
+ services.AddSingleton<DisplayChangeMonitor>();
services.AddSingleton<IWin32InteropService, Win32InteropService>();
services.AddSingleton<PluginBridgeDispatcher>();
services.AddSingleton<IWebViewHostFactory, WebViewHostFactory>();
diff --git a/src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs b/src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs
index 45e0692..f7f5b18 100644
--- a/src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs
+++ b/src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs
@@ -1,3 +1,4 @@
+using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
@@ -17,16 +18,22 @@
public bool IsSupported() => true;
- public bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error)
+ public bool TryAttachDesktopWindow(IntPtr hwnd, MonitorInfo monitor, RectD bounds, out string? error)
{
error = null;
+ var scale = monitor.Scale;
+ var x = (int)(bounds.X * scale);
+ var y = (int)(bounds.Y * scale);
+ var w = (int)(bounds.Width * scale);
+ var h = (int)(bounds.Height * scale);
+
if (!NativeMethods.SetWindowPos(
hwnd,
NativeMethods.HwndBottom,
- (int)bounds.X,
- (int)bounds.Y,
- (int)bounds.Width,
- (int)bounds.Height,
+ x,
+ y,
+ w,
+ h,
NativeMethods.SwpNoActivate | NativeMethods.SwpShowWindow))
{
error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
diff --git a/src/Moli.Desktop/Interop/DisplayChangeMonitor.cs b/src/Moli.Desktop/Interop/DisplayChangeMonitor.cs
new file mode 100644
index 0000000..197fa43
--- /dev/null
+++ b/src/Moli.Desktop/Interop/DisplayChangeMonitor.cs
@@ -0,0 +1,113 @@
+using System.Windows;
+using System.Windows.Interop;
+
+namespace Moli.Desktop.Interop;
+
+public sealed class DisplayChangeMonitor : IDisposable
+{
+ private HwndSource? _source;
+ private readonly SemaphoreSlim _singleFlight = new(1, 1);
+ private readonly int _debounceMs;
+ private CancellationTokenSource? _debounceCts;
+ private bool _disposed;
+
+ public event Func<Task>? DisplayChanged;
+
+ public DisplayChangeMonitor(int debounceMs = 500)
+ {
+ _debounceMs = debounceMs;
+ }
+
+ public void Start()
+ {
+ if (_source is not null)
+ {
+ return;
+ }
+
+ try
+ {
+ var parameters = new HwndSourceParameters("MoliDisplayChangeMonitor")
+ {
+ WindowStyle = 0,
+ ExtendedWindowStyle = 0,
+ ParentWindow = NativeMethods.HwndMessage,
+ };
+
+ _source = new HwndSource(parameters);
+ _source.AddHook(WndProc);
+ }
+ catch (InvalidOperationException)
+ {
+ _source = null;
+ }
+ }
+
+ public void Stop()
+ {
+ if (_source is null)
+ {
+ return;
+ }
+
+ _source.RemoveHook(WndProc);
+ _source.Dispose();
+ _source = null;
+ }
+
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+ Stop();
+ _debounceCts?.Cancel();
+ _debounceCts?.Dispose();
+ _singleFlight.Dispose();
+ }
+
+ private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
+ {
+ if (msg == NativeMethods.WmDisplayChange
+ || msg == NativeMethods.WmSettingChange
+ || msg == NativeMethods.WmDeviceChange)
+ {
+ OnDisplayChanged();
+ }
+
+ return IntPtr.Zero;
+ }
+
+ private async void OnDisplayChanged()
+ {
+ _debounceCts?.Cancel();
+ _debounceCts?.Dispose();
+ _debounceCts = new CancellationTokenSource();
+ var token = _debounceCts.Token;
+
+ try
+ {
+ await Task.Delay(_debounceMs, token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ return;
+ }
+
+ await _singleFlight.WaitAsync(CancellationToken.None).ConfigureAwait(false);
+ try
+ {
+ if (DisplayChanged is not null)
+ {
+ await DisplayChanged.Invoke().ConfigureAwait(false);
+ }
+ }
+ finally
+ {
+ _singleFlight.Release();
+ }
+ }
+}
diff --git a/src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs b/src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs
index 5397fe2..229e0fc 100644
--- a/src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs
+++ b/src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs
@@ -1,3 +1,4 @@
+using Moli.Desktop.Configuration;
using Moli.Desktop.Layout;
namespace Moli.Desktop.Interop;
@@ -7,5 +8,5 @@
{
string Name { get; }
bool IsSupported();
- bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error);
+ bool TryAttachDesktopWindow(IntPtr hwnd, MonitorInfo monitor, RectD bounds, out string? error);
}
diff --git a/src/Moli.Desktop/Interop/IWin32InteropService.cs b/src/Moli.Desktop/Interop/IWin32InteropService.cs
index dc60356..0a44f7c 100644
--- a/src/Moli.Desktop/Interop/IWin32InteropService.cs
+++ b/src/Moli.Desktop/Interop/IWin32InteropService.cs
@@ -11,9 +11,8 @@
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 MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, RectD bounds);
+ void SetLayered(IntPtr hwnd, bool enabled);
+ void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor, RectD bounds);
void RestoreTopLevelWindow(IntPtr hwnd);
void SetBottomMost(IntPtr hwnd);
IReadOnlyList<MonitorInfo> GetMonitors();
diff --git a/src/Moli.Desktop/Interop/NativeMethods.cs b/src/Moli.Desktop/Interop/NativeMethods.cs
index ccd5c8a..d3fa8d1 100644
--- a/src/Moli.Desktop/Interop/NativeMethods.cs
+++ b/src/Moli.Desktop/Interop/NativeMethods.cs
@@ -15,7 +15,6 @@
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;
@@ -23,7 +22,12 @@
internal const uint SwpFrameChanged = 0x0020;
internal const uint SwpShowWindow = 0x0040;
internal const uint SmtoNormal = 0x0000;
+ internal const int WmDisplayChange = 0x007E;
+ internal const int WmSettingChange = 0x001A;
+ internal const int WmDeviceChange = 0x0219;
+ internal const int MdtEffectiveDpi = 0;
internal static readonly IntPtr HwndBottom = new(1);
+ internal static readonly IntPtr HwndMessage = new(-3);
internal delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
internal delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData);
@@ -39,10 +43,6 @@
[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)]
@@ -72,6 +72,17 @@
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);
+ [DllImport("shcore.dll", SetLastError = false)]
+ internal static extern int GetDpiForMonitor(IntPtr hMonitor, int dpiType, out uint dpiX, out uint dpiY);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
+
+ [DllImport("user32.dll", SetLastError = false)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool IsWindow(IntPtr hWnd);
+
internal static IntPtr GetWindowLongPtr(IntPtr hwnd, int index)
{
return IntPtr.Size == 8
diff --git a/src/Moli.Desktop/Interop/Win32InteropService.cs b/src/Moli.Desktop/Interop/Win32InteropService.cs
index 6bed968..1b56207 100644
--- a/src/Moli.Desktop/Interop/Win32InteropService.cs
+++ b/src/Moli.Desktop/Interop/Win32InteropService.cs
@@ -22,7 +22,9 @@
public void SetClickThrough(IntPtr hwnd, bool enabled)
{
- SetStyleFlag(hwnd, NativeMethods.WsExLayered | NativeMethods.WsExTransparent, enabled, "SetClickThrough");
+ // Only toggle WS_EX_TRANSPARENT. WS_EX_LAYERED is owned by SetLayered / WPF
+ // AllowsTransparency; clearing it here would break per-pixel transparency.
+ SetStyleFlag(hwnd, NativeMethods.WsExTransparent, enabled, "SetClickThrough");
}
public void SetToolWindow(IntPtr hwnd, bool enabled)
@@ -35,19 +37,16 @@
SetStyleFlag(hwnd, NativeMethods.WsExNoActivate, enabled, "SetNoActivate");
}
- public void SetLayered(IntPtr hwnd, bool enabled, byte opacity)
+ public void SetLayered(IntPtr hwnd, bool enabled)
{
+ // Only manage the WS_EX_LAYERED style bit. Never call SetLayeredWindowAttributes here:
+ // it switches the window from WPF AllowsTransparency per-pixel alpha (UpdateLayeredWindow)
+ // to constant-alpha mode, in which transparent pixels composite as opaque black.
+ // Global opacity is handled by Window.Opacity instead.
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)
- => MoveToDesktopLayer(hwnd, mode, monitor.Bounds);
-
- public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, RectD bounds)
+ public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor, RectD bounds)
{
var candidates = mode == DesktopLayerMode.WorkerW
? _strategies.OrderBy(strategy => strategy is WorkerWDesktopLayerStrategy ? 0 : 1)
@@ -60,7 +59,7 @@
continue;
}
- if (strategy.TryAttachDesktopWindow(hwnd, bounds, out var error))
+ if (strategy.TryAttachDesktopWindow(hwnd, monitor, bounds, out var error))
{
return;
}
@@ -139,16 +138,36 @@
return true;
}
- var id = string.IsNullOrWhiteSpace(native.DeviceName)
+ var scale = 1.0;
+ var hr = NativeMethods.GetDpiForMonitor(hMonitor, NativeMethods.MdtEffectiveDpi, out var dpiX, out _);
+ if (hr == 0 && dpiX > 0)
+ {
+ scale = dpiX / 96.0;
+ }
+
+ var physicalBounds = ToRectD(native.Monitor);
+ var physicalWorkArea = ToRectD(native.WorkArea);
+ var dipBounds = new RectD(
+ physicalBounds.X / scale,
+ physicalBounds.Y / scale,
+ physicalBounds.Width / scale,
+ physicalBounds.Height / scale);
+ var dipWorkArea = new RectD(
+ physicalWorkArea.X / scale,
+ physicalWorkArea.Y / scale,
+ physicalWorkArea.Width / scale,
+ physicalWorkArea.Height / scale);
+
+ var deviceName = 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),
+ Id = new MonitorId(deviceName),
+ Bounds = dipBounds,
+ WorkArea = dipWorkArea,
IsPrimary = native.Flags,
- Scale = 1
+ Scale = scale
});
return true;
}, IntPtr.Zero);
@@ -160,7 +179,8 @@
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
+ IsPrimary = true,
+ Scale = 1
}];
}
diff --git a/src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs b/src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs
index bbda7f6..9756b3f 100644
--- a/src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs
+++ b/src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs
@@ -1,3 +1,4 @@
+using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
@@ -17,18 +18,56 @@
public bool IsSupported() => NativeMethods.FindWindow("Progman", null) != IntPtr.Zero;
- public bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error)
+ public bool TryAttachDesktopWindow(IntPtr hwnd, MonitorInfo monitor, RectD bounds, out string? error)
{
error = null;
- var desktopHost = FindDesktopHostWindow(out var hostClass);
- if (desktopHost == IntPtr.Zero)
+ var scale = monitor.Scale;
+ var physicalX = (int)(bounds.X * scale);
+ var physicalY = (int)(bounds.Y * scale);
+ var physicalW = (int)(bounds.Width * scale);
+ var physicalH = (int)(bounds.Height * scale);
+
+ var workers = EnumerateWorkerWindows();
+ if (workers.Count == 0)
{
- error = "Explorer desktop host window was not found.";
+ error = "No WorkerW or Progman desktop host window found.";
_diagnostics.Record(
DiagnosticSeverity.Warning,
DiagnosticCodes.DesktopLayerAttachFailed,
- "Explorer desktop host window was not found.",
+ "No WorkerW or Progman desktop host window found.",
new Dictionary<string, string> { ["strategy"] = Name });
+ return false;
+ }
+
+ var desktopHost = MatchWorkerWToMonitor(workers, monitor);
+ if (desktopHost == IntPtr.Zero)
+ {
+ error = "No matching WorkerW for target monitor.";
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.DesktopLayerAttachFailed,
+ "No matching WorkerW for target monitor.",
+ new Dictionary<string, string>
+ {
+ ["strategy"] = Name,
+ ["monitorId"] = monitor.Id.Value
+ });
+ return false;
+ }
+
+ desktopHost = ValidateAndRefreshHandle(desktopHost, monitor, ref workers);
+ if (desktopHost == IntPtr.Zero)
+ {
+ error = "WorkerW handle became invalid and no replacement was found.";
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.DesktopLayerAttachFailed,
+ "WorkerW handle invalidated and re-enumeration failed.",
+ new Dictionary<string, string>
+ {
+ ["strategy"] = Name,
+ ["monitorId"] = monitor.Id.Value
+ });
return false;
}
@@ -45,13 +84,17 @@
}
}
+ NativeMethods.GetWindowRect(desktopHost, out var hostRect);
+ var clientX = physicalX - hostRect.Left;
+ var clientY = physicalY - hostRect.Top;
+
if (!NativeMethods.SetWindowPos(
hwnd,
IntPtr.Zero,
- (int)bounds.X,
- (int)bounds.Y,
- (int)bounds.Width,
- (int)bounds.Height,
+ clientX,
+ clientY,
+ physicalW,
+ physicalH,
NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged | NativeMethods.SwpShowWindow))
{
error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
@@ -64,13 +107,39 @@
DiagnosticSeverity.Info,
DiagnosticCodes.DesktopLayerStrategySelected,
"Desktop layer strategy selected.",
- new Dictionary<string, string> { ["strategy"] = Name, ["host"] = hostClass });
+ new Dictionary<string, string>
+ {
+ ["strategy"] = Name,
+ ["host"] = desktopHost.ToString("X"),
+ ["monitorId"] = monitor.Id.Value,
+ ["scale"] = scale.ToString("F2")
+ });
return true;
}
- private static IntPtr FindDesktopHostWindow(out string hostClass)
+ private static IntPtr ValidateAndRefreshHandle(
+ IntPtr candidate,
+ MonitorInfo monitor,
+ ref List<(IntPtr hwnd, NativeMethods.Rect rect)> workers)
{
- hostClass = "WorkerW";
+ if (NativeMethods.IsWindow(candidate))
+ {
+ return candidate;
+ }
+
+ workers.RemoveAll(w => w.hwnd == candidate);
+ if (workers.Count == 0)
+ {
+ workers = EnumerateWorkerWindows();
+ }
+
+ return MatchWorkerWToMonitor(workers, monitor);
+ }
+
+ private static List<(IntPtr hwnd, NativeMethods.Rect rect)> EnumerateWorkerWindows()
+ {
+ var workers = new List<(IntPtr, NativeMethods.Rect)>();
+
var progman = NativeMethods.FindWindow("Progman", null);
if (progman != IntPtr.Zero)
{
@@ -92,7 +161,6 @@
out _);
}
- IntPtr workerW = IntPtr.Zero;
NativeMethods.EnumWindows((topHandle, _) =>
{
var shellView = NativeMethods.FindWindowEx(topHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
@@ -101,17 +169,64 @@
return true;
}
- workerW = NativeMethods.FindWindowEx(IntPtr.Zero, topHandle, "WorkerW", null);
- return workerW == IntPtr.Zero;
+ var workerW = NativeMethods.FindWindowEx(IntPtr.Zero, topHandle, "WorkerW", null);
+ if (workerW != IntPtr.Zero && NativeMethods.IsWindow(workerW) && NativeMethods.GetWindowRect(workerW, out var rect))
+ {
+ workers.Add((workerW, rect));
+ }
+
+ return true;
}, IntPtr.Zero);
- if (workerW != IntPtr.Zero)
+ if (workers.Count == 0 && progman != IntPtr.Zero && NativeMethods.GetWindowRect(progman, out var progmanRect))
{
- return workerW;
+ workers.Add((progman, progmanRect));
}
- hostClass = "Progman";
- return progman;
+ return workers;
+ }
+
+ private static IntPtr MatchWorkerWToMonitor(
+ List<(IntPtr hwnd, NativeMethods.Rect rect)> workers,
+ MonitorInfo monitor)
+ {
+ if (workers.Count == 0)
+ {
+ return IntPtr.Zero;
+ }
+
+ if (workers.Count == 1)
+ {
+ return workers[0].hwnd;
+ }
+
+ var scale = monitor.Scale;
+ var monitorLeft = monitor.Bounds.X * scale;
+ var monitorTop = monitor.Bounds.Y * scale;
+ var monitorRight = (monitor.Bounds.X + monitor.Bounds.Width) * scale;
+ var monitorBottom = (monitor.Bounds.Y + monitor.Bounds.Height) * scale;
+
+ var bestMatch = workers[0].hwnd;
+ var bestOverlap = 0.0;
+
+ foreach (var (hwnd, rect) in workers)
+ {
+ var overlapLeft = Math.Max(monitorLeft, (double)rect.Left);
+ var overlapTop = Math.Max(monitorTop, (double)rect.Top);
+ var overlapRight = Math.Min(monitorRight, (double)rect.Right);
+ var overlapBottom = Math.Min(monitorBottom, (double)rect.Bottom);
+ var overlapWidth = Math.Max(0, overlapRight - overlapLeft);
+ var overlapHeight = Math.Max(0, overlapBottom - overlapTop);
+ var overlapArea = overlapWidth * overlapHeight;
+
+ if (overlapArea > bestOverlap)
+ {
+ bestOverlap = overlapArea;
+ bestMatch = hwnd;
+ }
+ }
+
+ return bestMatch;
}
private static void SetDesktopChildStyle(IntPtr hwnd)
diff --git a/src/Moli.Desktop/Layout/LayoutManager.cs b/src/Moli.Desktop/Layout/LayoutManager.cs
index f2215d9..d1c42a1 100644
--- a/src/Moli.Desktop/Layout/LayoutManager.cs
+++ b/src/Moli.Desktop/Layout/LayoutManager.cs
@@ -142,12 +142,12 @@
var monitor = byId.GetValueOrDefault(layout.MonitorId);
if (monitor is null)
{
- var centered = CenterInMonitor(layout, primary);
- _document.Instances[i] = centered;
+ var migrated = MigrateToPrimary(layout, primary);
+ _document.Instances[i] = migrated;
_diagnostics.Record(
DiagnosticSeverity.Info,
"LayoutReconciled",
- "Widget layout moved to primary monitor after monitor topology changed.",
+ "Widget layout migrated to primary monitor after monitor topology changed.",
new Dictionary<string, string>
{
["instanceId"] = layout.InstanceId.Value,
@@ -157,11 +157,22 @@
continue;
}
- var constrained = Constrain(layout, monitor);
+ 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];
@@ -254,6 +265,62 @@
};
}
+ 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);
diff --git a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs b/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
index 33b594b..76e3087 100644
--- a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
+++ b/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
@@ -15,6 +15,7 @@
private readonly IDiagnosticsService _diagnostics;
private readonly IRuntimeEventBus _events;
private readonly IRuntimeSurfaceController _surfaces;
+ private readonly DisplayChangeMonitor _displayMonitor;
private readonly SemaphoreSlim _lock = new(1, 1);
private AppSettingsDocument _settings = new();
private IReadOnlyList<PluginDescriptor> _pluginSnapshot = [];
@@ -30,7 +31,8 @@
IWin32InteropService interop,
IDiagnosticsService diagnostics,
IRuntimeEventBus events,
- IRuntimeSurfaceController surfaces)
+ IRuntimeSurfaceController surfaces,
+ DisplayChangeMonitor displayMonitor)
{
_configuration = configuration;
_plugins = plugins;
@@ -39,6 +41,7 @@
_diagnostics = diagnostics;
_events = events;
_surfaces = surfaces;
+ _displayMonitor = displayMonitor;
}
public async Task<OperationResult<AppRuntimeState>> StartAsync(CancellationToken cancellationToken = default)
@@ -61,6 +64,9 @@
{
await _surfaces.ApplyWidgetLayoutAsync(ToSurfaceLayout(layout), cancellationToken).ConfigureAwait(false);
}
+
+ _displayMonitor.DisplayChanged += () => OnDisplayTopologyChangedAsync();
+ _displayMonitor.Start();
_diagnostics.Record(DiagnosticSeverity.Info, DiagnosticCodes.ApplicationStarted, "Desktop runtime started.");
var state = BuildState();
@@ -234,6 +240,27 @@
}
}
+ public async Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ ReconcileCurrentMonitors();
+ await _layout.SaveAsync(cancellationToken).ConfigureAwait(false);
+ await _surfaces.SyncAllLayoutsAsync(cancellationToken).ConfigureAwait(false);
+ await _surfaces.SyncWallpaperMonitorsAsync(cancellationToken).ConfigureAwait(false);
+ await _surfaces.ReattachDesktopLayersAsync(cancellationToken).ConfigureAwait(false);
+
+ var state = BuildState();
+ await _events.PublishAsync(new RuntimeEvent { Name = "display.topologyChanged", Payload = state }, cancellationToken).ConfigureAwait(false);
+ await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
private async Task<OperationResult<AppRuntimeState>> UpdateRuntimeFlagAsync(
string eventName,
Action update,
diff --git a/src/Moli.Desktop/Runtime/IDesktopRuntime.cs b/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
index 858965f..9304d8d 100644
--- a/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
+++ b/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
@@ -18,4 +18,5 @@
WidgetInstanceId instanceId,
WidgetLayoutPatch patch,
CancellationToken cancellationToken = default);
+ Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default);
}
diff --git a/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs b/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs
index 4acbae1..44699ce 100644
--- a/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs
+++ b/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs
@@ -11,4 +11,7 @@
Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default);
Task DisableWallpaperAsync(CancellationToken cancellationToken = default);
Task ShutdownAsync(CancellationToken cancellationToken = default);
+ Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default);
+ Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default);
+ Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default);
}
diff --git a/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
index 00fd78c..68b4983 100644
--- a/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
+++ b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
@@ -24,7 +24,7 @@
private readonly IServiceProvider _services;
private readonly IRuntimeEventBus _events;
private readonly Dictionary<WidgetInstanceId, WidgetWindow> _widgets = [];
- private WallpaperWindow? _wallpaper;
+ private readonly Dictionary<MonitorId, WallpaperWindow> _wallpapers = [];
private WallpaperRuntimeState _wallpaperState = new();
private bool _editMode;
private bool _safeInputMode;
@@ -64,7 +64,11 @@
=> OnUiThreadAsync(() =>
{
_safeInputMode = enabled;
- _wallpaper?.ApplyState(_wallpaperState, _safeInputMode);
+ foreach (var wallpaper in _wallpapers.Values)
+ {
+ wallpaper.ApplyState(_wallpaperState, _safeInputMode);
+ }
+
foreach (var widget in _widgets.Values)
{
widget.SetSafeInputMode(enabled);
@@ -103,6 +107,13 @@
await window.LoadAsync(cancellationToken).ConfigureAwait(true);
}
+ var monitors = _interop.GetMonitors();
+ var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
+ if (monitor is not null)
+ {
+ window.SetMonitorInfo(monitor);
+ }
+
window.ApplyLayout(layout, _editMode, _safeInputMode);
});
@@ -125,14 +136,26 @@
return;
}
- _wallpaper?.Close();
+ foreach (var (_, existing) in _wallpapers)
+ {
+ existing.Close();
+ }
+
+ _wallpapers.Clear();
_wallpaperState = wallpaper;
- var monitor = _interop.GetMonitors().FirstOrDefault(monitor => monitor.IsPrimary) ?? _interop.GetMonitors().First();
- _wallpaper = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
- _wallpaper.Closed += (_, _) => _wallpaper = null;
- _wallpaper.Show();
- await _wallpaper.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
- _wallpaper.ApplyState(wallpaper, _safeInputMode);
+
+ var monitors = _interop.GetMonitors();
+ foreach (var monitor in monitors)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var wallpaperWindow = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
+ _wallpapers[monitor.Id] = wallpaperWindow;
+ wallpaperWindow.Closed += (_, _) => _wallpapers.Remove(monitor.Id);
+ wallpaperWindow.Show();
+ await wallpaperWindow.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
+ wallpaperWindow.ApplyState(wallpaper, _safeInputMode);
+ }
+
ReapplyDesktopWidgetLayers();
});
@@ -140,8 +163,12 @@
=> OnUiThreadAsync(() =>
{
_wallpaperState = _wallpaperState with { IsEnabled = false };
- _wallpaper?.Close();
- _wallpaper = null;
+ foreach (var (_, wallpaper) in _wallpapers)
+ {
+ wallpaper.Close();
+ }
+
+ _wallpapers.Clear();
return Task.CompletedTask;
});
@@ -154,13 +181,113 @@
}
_widgets.Clear();
- _wallpaper?.Close();
- _wallpaper = null;
+ foreach (var (_, wallpaper) in _wallpapers)
+ {
+ wallpaper.Close();
+ }
+
+ _wallpapers.Clear();
_eventSubscription?.Dispose();
_eventSubscription = null;
return Task.CompletedTask;
});
+ public Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default)
+ => OnUiThreadAsync(() =>
+ {
+ var monitors = _interop.GetMonitors();
+ foreach (var (id, window) in _widgets)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var layout = window.CurrentLayout;
+ var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
+ if (monitor is not null)
+ {
+ window.SetMonitorInfo(monitor);
+ }
+
+ window.ApplyLayout(layout, _editMode, _safeInputMode);
+ }
+
+ return Task.CompletedTask;
+ });
+
+ public Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default)
+ => OnUiThreadAsync(async () =>
+ {
+ if (_wallpaperState.PluginId is null || _wallpapers.Count == 0)
+ {
+ return;
+ }
+
+ var plugin = await _plugins.GetAsync(_wallpaperState.PluginId.Value, cancellationToken).ConfigureAwait(true);
+ if (plugin is null)
+ {
+ return;
+ }
+
+ var monitors = _interop.GetMonitors();
+ var currentIds = new HashSet<MonitorId>(_wallpapers.Keys);
+ var newIds = new HashSet<MonitorId>(monitors.Select(m => m.Id));
+
+ foreach (var removed in currentIds.Where(id => !newIds.Contains(id)))
+ {
+ if (_wallpapers.TryGetValue(removed, out var removedWindow))
+ {
+ removedWindow.Close();
+ _wallpapers.Remove(removed);
+ }
+ }
+
+ foreach (var monitor in monitors)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (_wallpapers.TryGetValue(monitor.Id, out var existing))
+ {
+ existing.ApplyState(_wallpaperState, _safeInputMode);
+ }
+ else
+ {
+ var wallpaperWindow = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
+ _wallpapers[monitor.Id] = wallpaperWindow;
+ wallpaperWindow.Closed += (_, _) => _wallpapers.Remove(monitor.Id);
+ wallpaperWindow.Show();
+ await wallpaperWindow.LoadAsync(_wallpaperState, cancellationToken).ConfigureAwait(true);
+ wallpaperWindow.ApplyState(_wallpaperState, _safeInputMode);
+ }
+ }
+ });
+
+ public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default)
+ => OnUiThreadAsync(() =>
+ {
+ var monitors = _interop.GetMonitors();
+ foreach (var (_, window) in _widgets.Where(kv => kv.Value.CurrentLayout.DisplayLayer == DisplayLayer.Desktop))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var layout = window.CurrentLayout;
+ var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
+ if (monitor is not null)
+ {
+ window.SetMonitorInfo(monitor);
+ }
+
+ window.ApplyLayout(layout, _editMode, _safeInputMode);
+ }
+
+ foreach (var (monitorId, wallpaper) in _wallpapers)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var monitor = monitors.FirstOrDefault(m => m.Id == monitorId);
+ if (monitor is not null)
+ {
+ wallpaper.ApplyState(_wallpaperState, _safeInputMode);
+ }
+ }
+
+ return Task.CompletedTask;
+ });
+
private async Task CommitWidgetLayoutAsync(
WidgetInstanceId instanceId,
WidgetLayoutPatch patch,
diff --git a/src/Moli.Desktop/Windows/WallpaperWindow.cs b/src/Moli.Desktop/Windows/WallpaperWindow.cs
index 9cc0132..a639f2e 100644
--- a/src/Moli.Desktop/Windows/WallpaperWindow.cs
+++ b/src/Moli.Desktop/Windows/WallpaperWindow.cs
@@ -23,7 +23,6 @@
private readonly DesktopPaths _paths;
private readonly IDiagnosticsService _diagnostics;
private bool _clickThrough = true;
- private double _opacity = 1;
public WallpaperWindow(
PluginDescriptor plugin,
@@ -59,7 +58,7 @@
public async Task LoadAsync(WallpaperRuntimeState state, CancellationToken cancellationToken = default)
{
_clickThrough = state.ClickThrough;
- _opacity = state.Opacity;
+ Opacity = Math.Clamp(state.Opacity, 0.1, 1.0);
await _webView.InitializeAsync(new WebViewHostOptions
{
UserDataFolder = Path.Combine(_paths.WebViewDataDirectory, "wallpaper", _plugin.Id.Value),
@@ -77,7 +76,6 @@
public void ApplyState(WallpaperRuntimeState state, bool safeInputMode)
{
_clickThrough = !safeInputMode && state.ClickThrough;
- _opacity = state.Opacity;
Opacity = Math.Clamp(state.Opacity, 0.1, 1.0);
ApplyWin32Styles();
}
@@ -124,9 +122,9 @@
{
_interop.SetToolWindow(hwnd, true);
_interop.SetNoActivate(hwnd, true);
- _interop.SetLayered(hwnd, true, ToAlpha(_opacity));
+ _interop.SetLayered(hwnd, true);
_interop.SetClickThrough(hwnd, _clickThrough);
- _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitor);
+ _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitor, _monitor.Bounds);
}
catch (Exception ex)
{
@@ -137,6 +135,4 @@
new Dictionary<string, string> { ["pluginId"] = _plugin.Id.Value, ["exception"] = ex.GetType().Name });
}
}
-
- private static byte ToAlpha(double opacity) => (byte)Math.Round(Math.Clamp(opacity, 0.1, 1.0) * 255);
}
diff --git a/src/Moli.Desktop/Windows/WidgetWindow.cs b/src/Moli.Desktop/Windows/WidgetWindow.cs
index ed232bc..94ecba0 100644
--- a/src/Moli.Desktop/Windows/WidgetWindow.cs
+++ b/src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -33,6 +33,7 @@
private readonly Border _editBorder;
private readonly Border _resizeGrip;
private WidgetLayout _layout;
+ private MonitorInfo? _monitorInfo;
private double? _requestedHeight;
private bool _editMode;
private bool _safeInputMode;
@@ -163,6 +164,12 @@
ApplyWin32Styles();
}
+ public void SetMonitorInfo(MonitorInfo? monitorInfo)
+ {
+ _monitorInfo = monitorInfo;
+ ApplyWin32Styles();
+ }
+
protected override async void OnClosed(EventArgs e)
{
await _webView.DisposeAsync();
@@ -224,7 +231,27 @@
var bounds = new RectD(Left, Top, Width, Height);
_dragStart = null;
_resizing = false;
- await _commitLayoutAsync(_layout.InstanceId, new WidgetLayoutPatch { Bounds = bounds }, CancellationToken.None);
+
+ var patch = new WidgetLayoutPatch { Bounds = bounds };
+ try
+ {
+ var monitors = _interop.GetMonitors();
+ if (monitors.Count > 0)
+ {
+ var bestMonitor = monitors
+ .Select(m => new { Monitor = m, Overlap = ComputeOverlapArea(bounds, m.Bounds) })
+ .MaxBy(x => x.Overlap);
+ if (bestMonitor is not null && bestMonitor.Monitor.Id != _layout.MonitorId)
+ {
+ patch = patch with { MonitorId = bestMonitor.Monitor.Id };
+ }
+ }
+ }
+ catch
+ {
+ }
+
+ await _commitLayoutAsync(_layout.InstanceId, patch, CancellationToken.None);
}
private void BeginPointerOperation(MouseButtonEventArgs e)
@@ -264,6 +291,13 @@
DisplayLayer = _layout.DisplayLayer
};
+ private static double ComputeOverlapArea(RectD a, RectD b)
+ {
+ var overlapX = Math.Max(0, Math.Min(a.Right, b.Right) - Math.Max(a.X, b.X));
+ var overlapY = Math.Max(0, Math.Min(a.Bottom, b.Bottom) - Math.Max(a.Y, b.Y));
+ return overlapX * overlapY;
+ }
+
private void ApplyWin32Styles()
{
var hwnd = _interop.GetWindowHandle(this);
@@ -275,13 +309,17 @@
try
{
_interop.SetToolWindow(hwnd, true);
- _interop.SetLayered(hwnd, true, ToAlpha(_layout.Opacity));
+ _interop.SetLayered(hwnd, true);
_interop.SetClickThrough(hwnd, !_editMode && !_safeInputMode && _layout.ClickThrough);
switch (_layout.DisplayLayer)
{
case DisplayLayer.Desktop:
Topmost = false;
- _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _layout.Bounds);
+ if (_monitorInfo is not null)
+ {
+ _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitorInfo, _layout.Bounds);
+ }
+
break;
case DisplayLayer.GlobalTop:
_interop.RestoreTopLevelWindow(hwnd);
@@ -304,6 +342,4 @@
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);
}
--
Gitblit v1.9.1