using System.Runtime.InteropServices; using Microsoft.UI.Input; using Microsoft.UI.Xaml.Hosting; using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using XFEEDToolBox.Views; namespace XFEEDToolBox.Services; /// A native tool popup hosting XAML content, with no WinUI Window or caption chrome. public sealed class FloatingUpgradeList : IDisposable { private const string ClassName="XFEEDToolBox.MaterialFlyout"; private static readonly Dictionary surfaces=[]; private static readonly WindowProc procedure=OnMessage; private static ushort windowClass; private DesktopWindowXamlSource? source; private nint window; private bool disposed; private (Point Cursor,Rect Window)? dragOrigin; private (Point Cursor,Rect Window,ResizeEdge Edges,ResizeGrip Grip,Pointer Pointer)? resizeOrigin; internal const int MinimumWidth=320,MinimumHeight=320; [Flags] internal enum ResizeEdge { Left=1,Top=2,Right=4,Bottom=8 } public nint Handle=>window; public UpgradeListContent Panel{get;}=new(); public Border Surface{get;} public bool IsPinned{get;private set;} public event Action? Closed; public FloatingUpgradeList(nint owner,int x,int y,bool hidden=false) { if(windowClass==0) { var definition=new WindowClass{Size=(uint)Marshal.SizeOf(),Instance=GetModuleHandle(null),ClassName=ClassName,Procedure=Marshal.GetFunctionPointerForDelegate(procedure)}; windowClass=RegisterClassEx(ref definition);if(windowClass==0)throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } var scale=GetDpiForWindow(owner)/96d;var width=(int)(400*scale);var height=(int)(570*scale); var monitor=new MonitorInfo{Size=(uint)Marshal.SizeOf()}; if(GetMonitorInfo(MonitorFromWindow(owner,2),ref monitor)) {height=Math.Min(height,monitor.Work.Bottom-monitor.Work.Top-24);x=Math.Clamp(x,monitor.Work.Left+8,Math.Max(monitor.Work.Left+8,monitor.Work.Right-width-8));y=Math.Clamp(y,monitor.Work.Top+8,Math.Max(monitor.Work.Top+8,monitor.Work.Bottom-height-8));} window=CreateWindowEx(0x00000080|0x00200000,ClassName,"全局改装清单",0x80000000|0x02000000,x,y,width,height,0,0,GetModuleHandle(null),0); if(window==0)throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); surfaces.Add(window,this); Panel.ConfigureFloating();Panel.PinRequested+=TogglePin; Panel.DragStarted+=BeginMove;Panel.DragUpdated+=MoveWithPointer;Panel.DragCompleted+=()=>dragOrigin=null; Panel.CloseRequested+=QueueClose; Panel.DetailsRequested+=()=>{AppShellPage.Current?.ShowUpgradeDetails();App.MainWindow.Activate();}; var content=new Grid();Panel.Margin=new(14);content.Children.Add(Panel); AddResizeGrips(content); Surface=new Border{CornerRadius=new(12),BorderThickness=new(0),Background=new SolidColorBrush(Windows.UI.Color.FromArgb(255,17,29,43)),Child=content,RequestedTheme=ElementTheme.Dark}; try { source=new();source.Initialize(Microsoft.UI.Win32Interop.GetWindowIdFromWindow(window));source.Content=Surface;ResizeContent(); var rounded=2;DwmSetWindowAttribute(window,33,ref rounded,4);var dark=1;DwmSetWindowAttribute(window,20,ref dark,4); var noBorder=unchecked((int)0xFFFFFFFE);DwmSetWindowAttribute(window,34,ref noBorder,4); if(!hidden){ShowWindow(window,4);source.SiteBridge.Show();} } catch{Dispose();throw;} } public void Show(){ObjectDisposedException.ThrowIf(disposed,this);ShowWindow(window,4);source!.SiteBridge.Show();SetWindowPos(window,IsPinned?new nint(-1):0,0,0,0,0,0x0013);} public void TogglePin() { if(disposed)return;var pinned=!IsPinned; if(!SetWindowPos(window,pinned?new nint(-1):new nint(-2),0,0,0,0,0x0013))throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); IsPinned=pinned;Panel.ShowPinned(pinned); } private void BeginMove() { if(disposed)return; StopResizing(); if(GetCursorPos(out var cursor)&&GetWindowRect(window,out var rect))dragOrigin=(cursor,rect); else Panel.StopDragging(); } private void MoveWithPointer() { if(disposed||dragOrigin is not {} origin)return; // Use desktop pixels, not coordinates relative to the moving XAML island. // Moving the window must not feed its own displacement into the next pointer delta. if(!GetCursorPos(out var cursor)){Panel.StopDragging();return;} var x=origin.Window.Left+cursor.X-origin.Cursor.X;var y=origin.Window.Top+cursor.Y-origin.Cursor.Y; if(GetWindowRect(window,out var current)&&(current.Left!=x||current.Top!=y))MoveTo(x,y); } private void AddResizeGrips(Grid content) { const double edge=6,corner=14; Add(ResizeEdge.Left,edge,double.NaN,HorizontalAlignment.Left,VerticalAlignment.Stretch,new(0,corner,0,corner),InputSystemCursorShape.SizeWestEast); Add(ResizeEdge.Right,edge,double.NaN,HorizontalAlignment.Right,VerticalAlignment.Stretch,new(0,corner,0,corner),InputSystemCursorShape.SizeWestEast); Add(ResizeEdge.Top,double.NaN,edge,HorizontalAlignment.Stretch,VerticalAlignment.Top,new(corner,0,corner,0),InputSystemCursorShape.SizeNorthSouth); Add(ResizeEdge.Bottom,double.NaN,edge,HorizontalAlignment.Stretch,VerticalAlignment.Bottom,new(corner,0,corner,0),InputSystemCursorShape.SizeNorthSouth); Add(ResizeEdge.Left|ResizeEdge.Top,corner,corner,HorizontalAlignment.Left,VerticalAlignment.Top,new(0),InputSystemCursorShape.SizeNorthwestSoutheast); Add(ResizeEdge.Right|ResizeEdge.Top,corner,corner,HorizontalAlignment.Right,VerticalAlignment.Top,new(0),InputSystemCursorShape.SizeNortheastSouthwest); Add(ResizeEdge.Left|ResizeEdge.Bottom,corner,corner,HorizontalAlignment.Left,VerticalAlignment.Bottom,new(0),InputSystemCursorShape.SizeNortheastSouthwest); Add(ResizeEdge.Right|ResizeEdge.Bottom,corner,corner,HorizontalAlignment.Right,VerticalAlignment.Bottom,new(0),InputSystemCursorShape.SizeNorthwestSoutheast); void Add(ResizeEdge edges,double width,double height,HorizontalAlignment horizontal,VerticalAlignment vertical,Thickness margin,InputSystemCursorShape cursor) { var grip=new ResizeGrip(cursor){Width=width,Height=height,HorizontalAlignment=horizontal,VerticalAlignment=vertical,Margin=margin,Tag=edges,Background=new SolidColorBrush(Microsoft.UI.Colors.Transparent)}; Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(grip,"拖动调整清单大小"); grip.PointerPressed+=ResizePressed;grip.PointerMoved+=ResizeMoved;grip.PointerReleased+=ResizeReleased; grip.PointerCanceled+=ResizeCancelled;grip.PointerCaptureLost+=ResizeCancelled;content.Children.Add(grip); } } private void ResizePressed(object sender,PointerRoutedEventArgs args) { if(disposed||resizeOrigin is not null||sender is not ResizeGrip grip||!args.GetCurrentPoint(grip).Properties.IsLeftButtonPressed)return; if(!GetCursorPos(out var cursor)||!GetWindowRect(window,out var rect)||!grip.CapturePointer(args.Pointer))return; Panel.StopDragging();dragOrigin=null;resizeOrigin=(cursor,rect,(ResizeEdge)grip.Tag,grip,args.Pointer);args.Handled=true; } private void ResizeMoved(object sender,PointerRoutedEventArgs args) { if(resizeOrigin is not {} origin||origin.Pointer.PointerId!=args.Pointer.PointerId)return; args.Handled=true; if(!args.GetCurrentPoint(origin.Grip).Properties.IsLeftButtonPressed||!GetCursorPos(out var cursor)){StopResizing();return;} // Desktop pixels keep left/top resizing from feeding the moving island's position back into the pointer delta. ApplyResize(origin.Window,origin.Edges,cursor.X-origin.Cursor.X,cursor.Y-origin.Cursor.Y); } private void ResizeReleased(object sender,PointerRoutedEventArgs args) { if(resizeOrigin is not {} origin||origin.Pointer.PointerId!=args.Pointer.PointerId)return; if(GetCursorPos(out var cursor))ApplyResize(origin.Window,origin.Edges,cursor.X-origin.Cursor.X,cursor.Y-origin.Cursor.Y); StopResizing();args.Handled=true; } private void ResizeCancelled(object sender,PointerRoutedEventArgs args) {if(resizeOrigin?.Pointer.PointerId==args.Pointer.PointerId)StopResizing();} private void StopResizing() { if(resizeOrigin is not {} origin)return; resizeOrigin=null;origin.Grip.ReleasePointerCapture(origin.Pointer); } private void ApplyResize(Rect origin,ResizeEdge edges,int deltaX,int deltaY) { if(disposed)return; var scale=GetDpiForWindow(window)/96d;var minimumWidth=(int)Math.Ceiling(MinimumWidth*scale);var minimumHeight=(int)Math.Ceiling(MinimumHeight*scale); var left=origin.Left;var top=origin.Top;var right=origin.Right;var bottom=origin.Bottom; if(edges.HasFlag(ResizeEdge.Left))left=Math.Min(origin.Left+deltaX,origin.Right-minimumWidth); if(edges.HasFlag(ResizeEdge.Right))right=Math.Max(origin.Right+deltaX,origin.Left+minimumWidth); if(edges.HasFlag(ResizeEdge.Top))top=Math.Min(origin.Top+deltaY,origin.Bottom-minimumHeight); if(edges.HasFlag(ResizeEdge.Bottom))bottom=Math.Max(origin.Bottom+deltaY,origin.Top+minimumHeight); SetWindowPos(window,0,left,top,right-left,bottom-top,0x0014); } internal void ResizeBy(ResizeEdge edges,int deltaX,int deltaY) {if(!disposed&&GetWindowRect(window,out var rect))ApplyResize(rect,edges,deltaX,deltaY);} internal (int X,int Y,int Width,int Height) Bounds {get{GetWindowRect(window,out var rect);return(rect.Left,rect.Top,rect.Right-rect.Left,rect.Bottom-rect.Top);}} private sealed class ResizeGrip : Grid { public ResizeGrip(InputSystemCursorShape shape) {Loaded+=(_,_)=>ProtectedCursor=InputSystemCursor.Create(shape);} } private void QueueClose()=>App.MainWindow.DispatcherQueue.TryEnqueue(Dispose); private void ResizeContent() { if(disposed||source is null||!GetClientRect(window,out var rect))return; var child=Microsoft.UI.Win32Interop.GetWindowFromWindowId(source.SiteBridge.WindowId); SetWindowPos(child,0,0,0,rect.Right,rect.Bottom,0x0014); } public void MoveTo(int x,int y)=>SetWindowPos(window,0,x,y,0,0,0x0015); public (int X,int Y) Position {get{GetWindowRect(window,out var rect);return(rect.Left,rect.Top);}} public bool NativeTopmost=>(GetWindowLong(window,-20)&8)!=0; public bool IsToolPopup=>(GetWindowLong(window,-20)&0x80)!=0&&(GetWindowLong(window,-16)&unchecked((int)0x80C00000))==unchecked((int)0x80000000); private static nint OnMessage(nint hwnd,uint message,nuint wParam,nint lParam) { if(surfaces.TryGetValue(hwnd,out var popup)) { if(message==0x0005)popup.ResizeContent(); if(message==0x0010){popup.QueueClose();return 0;} if(message==0x02E0) {var rect=Marshal.PtrToStructure(lParam);SetWindowPos(hwnd,0,rect.Left,rect.Top,rect.Right-rect.Left,rect.Bottom-rect.Top,0x0014);return 0;} } return DefWindowProc(hwnd,message,wParam,lParam); } public void Dispose() { if(disposed)return;StopResizing();Panel.StopDragging();disposed=true;dragOrigin=null; source?.Dispose();source=null;surfaces.Remove(window);if(window!=0)DestroyWindow(window);window=0;Closed?.Invoke(); } [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate nint WindowProc(nint hwnd,uint message,nuint wParam,nint lParam); [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] private struct WindowClass {public uint Size,Style;public nint Procedure;public int ClassExtra,WindowExtra;public nint Instance,Icon,Cursor,Background;public string? MenuName,ClassName;public nint SmallIcon;} [StructLayout(LayoutKind.Sequential)] private struct Rect{public int Left,Top,Right,Bottom;} [StructLayout(LayoutKind.Sequential)] private struct Point{public int X,Y;} [StructLayout(LayoutKind.Sequential)] private struct MonitorInfo{public uint Size;public Rect Monitor,Work;public uint Flags;} [DllImport("user32.dll",EntryPoint="RegisterClassExW",CharSet=CharSet.Unicode,SetLastError=true)] private static extern ushort RegisterClassEx(ref WindowClass value); [DllImport("user32.dll",EntryPoint="CreateWindowExW",CharSet=CharSet.Unicode,SetLastError=true)] private static extern nint CreateWindowEx(uint extended,string className,string title,uint style,int x,int y,int width,int height,nint parent,nint menu,nint instance,nint data); [DllImport("kernel32.dll",EntryPoint="GetModuleHandleW",CharSet=CharSet.Unicode)] private static extern nint GetModuleHandle(string? module); [DllImport("user32.dll")] private static extern uint GetDpiForWindow(nint hwnd); [DllImport("user32.dll")] private static extern nint MonitorFromWindow(nint hwnd,uint flags); [DllImport("user32.dll",EntryPoint="GetMonitorInfoW")] private static extern bool GetMonitorInfo(nint monitor,ref MonitorInfo info); [DllImport("user32.dll")] private static extern bool GetClientRect(nint hwnd,out Rect rect); [DllImport("user32.dll")] private static extern bool GetWindowRect(nint hwnd,out Rect rect); [DllImport("user32.dll",SetLastError=true)] private static extern bool SetWindowPos(nint hwnd,nint after,int x,int y,int width,int height,uint flags); [DllImport("user32.dll",EntryPoint="GetWindowLongW")] private static extern int GetWindowLong(nint hwnd,int index); [DllImport("user32.dll")] private static extern bool ShowWindow(nint hwnd,int command); [DllImport("user32.dll")] private static extern bool DestroyWindow(nint hwnd); [DllImport("user32.dll")] private static extern bool GetCursorPos(out Point point); [DllImport("user32.dll",EntryPoint="DefWindowProcW")] private static extern nint DefWindowProc(nint hwnd,uint message,nuint wParam,nint lParam); [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(nint hwnd,int attribute,ref int value,int size); }