From b84db8983d63a9a981083ebce1a139860c6bdf25 Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期五, 14 八月 2026 15:35:21 +0800
Subject: [PATCH] commit

---
 src/Moli.Desktop/Windows/WidgetWindow.cs |  186 ++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 171 insertions(+), 15 deletions(-)

diff --git a/src/Moli.Desktop/Windows/WidgetWindow.cs b/src/Moli.Desktop/Windows/WidgetWindow.cs
index 8fe0a6e..4d6a24e 100644
--- a/src/Moli.Desktop/Windows/WidgetWindow.cs
+++ b/src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -13,6 +13,8 @@
 using Moli.Desktop.Runtime;
 using Moli.Desktop.WebView;
 using Brushes = System.Windows.Media.Brushes;
+using Color = System.Windows.Media.Color;
+using SolidColorBrush = System.Windows.Media.SolidColorBrush;
 using Cursors = System.Windows.Input.Cursors;
 using HorizontalAlignment = System.Windows.HorizontalAlignment;
 using MouseEventArgs = System.Windows.Input.MouseEventArgs;
@@ -24,6 +26,13 @@
 public sealed class WidgetWindow : Window
 {
     private const double ResizeGripSize = 18;
+    /// <summary>
+    /// WPF AllowsTransparency uses UpdateLayeredWindow hit-testing against the WPF alpha
+    /// bitmap. Fully transparent pixels are skipped even when WS_EX_TRANSPARENT is off, so a
+    /// Transparent background over WebView2 (HwndHost) makes the widget look like a sticker.
+    /// Alpha=1 keeps hits while remaining visually invisible.
+    /// </summary>
+    private static readonly SolidColorBrush HitTestBackground = CreateHitTestBackground();
     private readonly PluginDescriptor _plugin;
     private readonly IWebViewHost _webView;
     private readonly IWin32InteropService _interop;
@@ -33,11 +42,16 @@
     private readonly Border _editBorder;
     private readonly Border _resizeGrip;
     private WidgetLayout _layout;
+    private MonitorInfo? _monitorInfo;
+    private double? _requestedHeight;
     private bool _editMode;
     private bool _safeInputMode;
     private Point? _dragStart;
     private RectD _startBounds;
     private bool _resizing;
+    private DisplayLayer? _lastDisplayLayer;
+    private bool _desktopLayerAttached;
+    private WidgetSessionOverlay _session = WidgetSessionOverlay.Empty;
 
     public WidgetWindow(
         PluginDescriptor plugin,
@@ -60,12 +74,12 @@
         WindowStyle = WindowStyle.None;
         ResizeMode = ResizeMode.NoResize;
         AllowsTransparency = true;
-        Background = Brushes.Transparent;
+        Background = HitTestBackground;
         ShowInTaskbar = false;
-        Topmost = true;
+        Topmost = false;
         SizeToContent = SizeToContent.Manual;
 
-        var root = new Grid { Background = Brushes.Transparent };
+        var root = new Grid { Background = HitTestBackground };
         root.Children.Add(webView.View);
         _editBorder = new Border
         {
@@ -98,9 +112,13 @@
 
     public WidgetInstanceId InstanceId => _layout.InstanceId;
 
+    public WidgetLayout CurrentLayout => _layout;
+
+    public string HostId => _webView.HostId;
+
     public async Task LoadAsync(CancellationToken cancellationToken = default)
     {
-        ApplyLayout(_layout, _editMode, _safeInputMode);
+        ApplyLayout(_layout, _editMode, _safeInputMode, _session);
         await _webView.InitializeAsync(new WebViewHostOptions
         {
             UserDataFolder = Path.Combine(_paths.WebViewDataDirectory, "widgets", _layout.InstanceId.Value),
@@ -115,31 +133,73 @@
         await _webView.DispatchLifecycleEventAsync("moli:widget-loaded", ToRuntimeState(), cancellationToken).ConfigureAwait(true);
     }
 
-    public void ApplyLayout(WidgetLayout layout, bool editMode, bool safeInputMode)
+    public void ApplyLayout(WidgetLayout layout, bool editMode, bool safeInputMode, WidgetSessionOverlay? session = null)
     {
         _layout = layout;
         _editMode = editMode;
         _safeInputMode = safeInputMode;
+        if (session is not null)
+        {
+            _session = session;
+        }
+
         Left = layout.Bounds.X;
         Top = layout.Bounds.Y;
         Width = layout.Bounds.Width;
-        Height = layout.Bounds.Height;
+        Height = Math.Max(layout.Bounds.Height, _requestedHeight ?? layout.Bounds.Height);
         Opacity = Math.Clamp(layout.Opacity, 0.1, 1.0);
-        Visibility = layout.IsVisible ? Visibility.Visible : Visibility.Hidden;
+        Visibility = WidgetSurfaceRules.ComputeVisible(_session, layout.IsVisible) ? Visibility.Visible : Visibility.Hidden;
+        Topmost = layout.DisplayLayer == DisplayLayer.GlobalTop;
         _editBorder.Visibility = editMode ? Visibility.Visible : Visibility.Collapsed;
         _resizeGrip.Visibility = editMode && !layout.IsLocked ? Visibility.Visible : Visibility.Collapsed;
         ApplyWin32Styles();
     }
 
+    public async Task ApplySessionOverlayAsync(
+        WidgetSessionOverlay overlay,
+        bool editMode,
+        bool safeInputMode,
+        CancellationToken cancellationToken = default)
+    {
+        var wasInteractable = _session.Interactable == true;
+        ApplyLayout(_layout, editMode, safeInputMode, overlay);
+        var enabled = overlay.Interactable == true;
+        if (enabled && !wasInteractable)
+        {
+            Activate();
+        }
+
+        await _webView.DispatchLifecycleEventAsync("moli:interactable-changed", new { enabled }, cancellationToken).ConfigureAwait(true);
+    }
+
+    public void ApplyRequestedSize(double? width, double? height)
+    {
+        if (width is > 0)
+        {
+            Width = Math.Max(LayoutManager.MinWidth, width.Value);
+        }
+
+        _requestedHeight = height is > 0 && height.Value > _layout.Bounds.Height
+            ? height.Value
+            : null;
+        Height = Math.Max(_layout.Bounds.Height, _requestedHeight ?? _layout.Bounds.Height);
+    }
+
     public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
     {
-        ApplyLayout(_layout, enabled, _safeInputMode);
+        ApplyLayout(_layout, enabled, _safeInputMode, _session);
         return _webView.DispatchLifecycleEventAsync("moli:edit-mode-changed", new { enabled }, cancellationToken);
     }
 
     public void SetSafeInputMode(bool enabled)
     {
         _safeInputMode = enabled;
+        ApplyWin32Styles();
+    }
+
+    public void SetMonitorInfo(MonitorInfo? monitorInfo)
+    {
+        _monitorInfo = monitorInfo;
         ApplyWin32Styles();
     }
 
@@ -204,7 +264,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)
@@ -237,11 +317,30 @@
         PluginId = _layout.PluginId,
         Bounds = _layout.Bounds,
         MonitorId = _layout.MonitorId,
-        IsVisible = _layout.IsVisible,
+        IsVisible = WidgetSurfaceRules.ComputeVisible(_session, _layout.IsVisible),
+        LayoutIsVisible = _layout.IsVisible,
         IsLocked = _layout.IsLocked,
         Opacity = _layout.Opacity,
-        ClickThrough = _layout.ClickThrough
+        ClickThrough = WidgetSurfaceRules.ComputeClickThrough(_editMode, _safeInputMode, _session, _layout.ClickThrough),
+        LayoutClickThrough = _layout.ClickThrough,
+        IsInteractable = _session.Interactable == true,
+        HasSessionInteractable = _session.HasInteractableOverride,
+        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 static SolidColorBrush CreateHitTestBackground()
+    {
+        var brush = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));
+        brush.Freeze();
+        return brush;
+    }
 
     private void ApplyWin32Styles()
     {
@@ -254,8 +353,67 @@
         try
         {
             _interop.SetToolWindow(hwnd, true);
-            _interop.SetLayered(hwnd, true, ToAlpha(_layout.Opacity));
-            _interop.SetClickThrough(hwnd, !_editMode && !_safeInputMode && _layout.ClickThrough);
+            _interop.SetLayered(hwnd, true);
+            _interop.SetClickThrough(
+                hwnd,
+                WidgetSurfaceRules.ComputeClickThrough(_editMode, _safeInputMode, _session, _layout.ClickThrough));
+
+            var currentLayer = _layout.DisplayLayer;
+            var layerChanged = currentLayer != _lastDisplayLayer;
+            var needsDesktopAttach = currentLayer == DisplayLayer.Desktop
+                && _monitorInfo is not null
+                && (!_desktopLayerAttached || layerChanged);
+            var needsTopLevelRestore = currentLayer != DisplayLayer.Desktop
+                && (layerChanged || _desktopLayerAttached);
+
+            if (!layerChanged && !needsDesktopAttach && !needsTopLevelRestore)
+            {
+                return;
+            }
+
+            var parentChanged = false;
+            switch (currentLayer)
+            {
+                case DisplayLayer.Desktop:
+                    Topmost = false;
+                    if (needsDesktopAttach)
+                    {
+                        _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitorInfo!, _layout.Bounds);
+                        _desktopLayerAttached = true;
+                        parentChanged = true;
+                    }
+
+                    break;
+                case DisplayLayer.GlobalTop:
+                    if (needsTopLevelRestore)
+                    {
+                        _interop.RestoreTopLevelWindow(hwnd);
+                        _desktopLayerAttached = false;
+                        parentChanged = true;
+                    }
+
+                    Topmost = true;
+                    break;
+                case DisplayLayer.AppTop:
+                case DisplayLayer.Normal:
+                default:
+                    if (needsTopLevelRestore)
+                    {
+                        _interop.RestoreTopLevelWindow(hwnd);
+                        _desktopLayerAttached = false;
+                        parentChanged = true;
+                    }
+
+                    Topmost = false;
+                    break;
+            }
+
+            _lastDisplayLayer = currentLayer;
+
+            if (parentChanged)
+            {
+                _ = _webView.NotifyParentWindowPositionChangedAsync();
+            }
         }
         catch (Exception ex)
         {
@@ -266,6 +424,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