-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
WindowImpl.cs
1683 lines (1373 loc) · 61 KB
/
WindowImpl.cs
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using Avalonia.Collections.Pooled;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Input.Raw;
using Avalonia.Input.TextInput;
using Avalonia.OpenGL.Egl;
using Avalonia.Platform;
using Avalonia.Platform.Storage;
using Avalonia.Rendering.Composition;
using Avalonia.Win32.DirectX;
using Avalonia.Win32.Input;
using Avalonia.Win32.Interop;
using Avalonia.Win32.OpenGl;
using Avalonia.Win32.OpenGl.Angle;
using Avalonia.Win32.WinRT;
using Avalonia.Win32.WinRT.Composition;
using static Avalonia.Win32.Interop.UnmanagedMethods;
using System.Diagnostics;
using Avalonia.Platform.Storage.FileIO;
using Avalonia.Threading;
using static Avalonia.Controls.Platform.IWin32OptionsTopLevelImpl;
using static Avalonia.Controls.Win32Properties;
using Avalonia.Logging;
namespace Avalonia.Win32
{
/// <summary>
/// Window implementation for Win32 platform.
/// </summary>
internal partial class WindowImpl : IWindowImpl, EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo, IWin32OptionsTopLevelImpl
{
private static readonly List<WindowImpl> s_instances = new();
private static readonly IntPtr s_defaultCursor = LoadCursor(
IntPtr.Zero, new IntPtr((int)UnmanagedMethods.Cursor.IDC_ARROW));
private static readonly Dictionary<WindowEdge, HitTestValues> s_edgeLookup =
new()
{
{ WindowEdge.East, HitTestValues.HTRIGHT },
{ WindowEdge.North, HitTestValues.HTTOP },
{ WindowEdge.NorthEast, HitTestValues.HTTOPRIGHT },
{ WindowEdge.NorthWest, HitTestValues.HTTOPLEFT },
{ WindowEdge.South, HitTestValues.HTBOTTOM },
{ WindowEdge.SouthEast, HitTestValues.HTBOTTOMRIGHT },
{ WindowEdge.SouthWest, HitTestValues.HTBOTTOMLEFT },
{ WindowEdge.West, HitTestValues.HTLEFT }
};
/// <summary>
/// The Windows DPI which equates to a <see cref="RenderScaling"/> of 1.0.
/// </summary>
public const double StandardDpi = 96;
private SavedWindowInfo _savedWindowInfo;
private bool _isFullScreenActive;
private bool _isClientAreaExtended;
private Thickness _extendedMargins;
private Thickness _offScreenMargin;
private double _extendTitleBarHint = -1;
private WindowResizeReason _resizeReason;
private MOUSEMOVEPOINT _lastWmMousePoint;
#if USE_MANAGED_DRAG
private readonly ManagedWindowResizeDragHelper _managedDrag;
#endif
private const WindowStyles WindowStateMask = (WindowStyles.WS_MAXIMIZE | WindowStyles.WS_MINIMIZE);
private readonly TouchDevice _touchDevice;
private readonly WindowsMouseDevice _mouseDevice;
private readonly PenDevice _penDevice;
private readonly FramebufferManager _framebuffer;
private readonly object? _glSurface;
private readonly bool _wmPointerEnabled;
private readonly Win32NativeControlHost _nativeControlHost;
private readonly IStorageProvider _storageProvider;
private readonly WindowsInputPane? _inputPane;
private WndProc _wndProcDelegate;
private string? _className;
private IntPtr _hwnd;
private IInputRoot? _owner;
protected WindowProperties _windowProperties;
private IconImpl? _iconImpl;
private readonly Dictionary<(Icons type, uint dpi), Win32Icon> _iconCache = new();
private bool _trackingMouse;//ToDo - there is something missed. Needs investigation @Steven Kirk
private bool _topmost;
private double _scaling = 1;
private uint _dpi = 96;
private WindowState _showWindowState;
private WindowState _lastWindowState;
private OleDropTarget? _dropTarget;
private Size _minSize;
private Size _maxSize;
private POINT _maxTrackSize;
private WindowImpl? _parent;
private ExtendClientAreaChromeHints _extendChromeHints = ExtendClientAreaChromeHints.Default;
private bool _isCloseRequested;
private bool _shown;
private bool _hiddenWindowIsParent;
private uint _langid;
internal bool _ignoreWmChar;
private WindowTransparencyLevel _transparencyLevel;
private readonly WindowTransparencyLevel _defaultTransparencyLevel;
private const int MaxPointerHistorySize = 512;
private static readonly PooledList<RawPointerPoint> s_intermediatePointsPooledList = new();
private static POINTER_TOUCH_INFO[]? s_historyTouchInfos;
private static POINTER_PEN_INFO[]? s_historyPenInfos;
private static POINTER_INFO[]? s_historyInfos;
private static MOUSEMOVEPOINT[]? s_mouseHistoryInfos;
private PlatformThemeVariant _currentThemeVariant;
public WindowImpl()
{
_touchDevice = new TouchDevice();
_mouseDevice = new WindowsMouseDevice();
_penDevice = new PenDevice();
#if USE_MANAGED_DRAG
_managedDrag = new ManagedWindowResizeDragHelper(this, capture =>
{
if (capture)
UnmanagedMethods.SetCapture(Handle.Handle);
else
UnmanagedMethods.ReleaseCapture();
});
#endif
_windowProperties = new WindowProperties
{
ShowInTaskbar = false,
IsResizable = true,
Decorations = SystemDecorations.Full
};
var surfaceFactory = AvaloniaLocator.Current.GetService<IWindowsSurfaceFactory>();
var glPlatform = AvaloniaLocator.Current.GetService<IPlatformGraphics>();
UseRedirectionBitmap = surfaceFactory is null || glPlatform is null ||
!surfaceFactory.RequiresNoRedirectionBitmap;
_wmPointerEnabled = Win32Platform.WindowsVersion >= PlatformConstants.Windows8;
CreateWindow();
_framebuffer = new FramebufferManager(_hwnd);
if (this is not PopupImpl)
{
UpdateInputMethod(GetKeyboardLayout(0));
}
if (glPlatform != null)
{
if (surfaceFactory is not null)
{
_glSurface = surfaceFactory.CreateSurface(this);
}
else
{
if (glPlatform is D3D11AngleWin32PlatformGraphics or D3D9AngleWin32PlatformGraphics)
_glSurface = new EglGlPlatformSurface(this);
else if (glPlatform is WglPlatformOpenGlInterface)
_glSurface = new WglGlPlatformSurface(this);
}
}
Screen = new ScreenImpl();
_storageProvider = new Win32StorageProvider(this);
_inputPane = WindowsInputPane.TryCreate(this);
_nativeControlHost = new Win32NativeControlHost(this, !UseRedirectionBitmap);
_defaultTransparencyLevel = UseRedirectionBitmap ? WindowTransparencyLevel.None : WindowTransparencyLevel.Transparent;
_transparencyLevel = _defaultTransparencyLevel;
s_instances.Add(this);
}
internal IInputRoot Owner
=> _owner ?? throw new InvalidOperationException($"{nameof(SetInputRoot)} must have been called");
internal WindowImpl? ParentImpl => _parent;
public Action? Activated { get; set; }
public Func<WindowCloseReason, bool>? Closing { get; set; }
public Action? Closed { get; set; }
public Action? Deactivated { get; set; }
public Action<RawInputEventArgs>? Input { get; set; }
public Action<Rect>? Paint { get; set; }
public Action<Size, WindowResizeReason>? Resized { get; set; }
public Action<double>? ScalingChanged { get; set; }
public Action<PixelPoint>? PositionChanged { get; set; }
public Action<WindowState>? WindowStateChanged { get; set; }
public Action? LostFocus { get; set; }
public Action<WindowTransparencyLevel>? TransparencyLevelChanged { get; set; }
public Thickness BorderThickness
{
get
{
if (HasFullDecorations)
{
var style = GetStyle();
var exStyle = GetExtendedStyle();
var padding = new RECT();
if (AdjustWindowRectEx(ref padding, (uint)style, false, (uint)exStyle))
{
return new Thickness(-padding.left, -padding.top, padding.right, padding.bottom);
}
else
{
throw new Win32Exception();
}
}
else
{
return new Thickness();
}
}
}
private double PrimaryScreenRenderScaling => Screen.AllScreens.FirstOrDefault(screen => screen.IsPrimary)?.Scaling ?? 1;
private ICompositionEffectsSurface? CompositionEffectsSurface => _glSurface as ICompositionEffectsSurface;
private bool UseRedirectionBitmap { get; }
public double RenderScaling => _scaling;
public double DesktopScaling => RenderScaling;
public Size ClientSize
{
get
{
GetClientRect(_hwnd, out var rect);
return new Size(rect.right, rect.bottom) / RenderScaling;
}
}
Size? ITopLevelImpl.FrameSize => FrameSize;
public Size FrameSize
{
get
{
if (DwmIsCompositionEnabled(out var compositionEnabled) != 0 || !compositionEnabled)
{
GetWindowRect(_hwnd, out var rcWindow);
return new Size(rcWindow.Width, rcWindow.Height) / RenderScaling;
}
DwmGetWindowAttribute(_hwnd, (int)DwmWindowAttribute.DWMWA_EXTENDED_FRAME_BOUNDS, out var rect, Marshal.SizeOf<RECT>());
return new Size(rect.Width, rect.Height) / RenderScaling;
}
}
public IScreenImpl Screen { get; }
public IPlatformHandle Handle { get; private set; }
public virtual Size MaxAutoSizeHint => new Size(_maxTrackSize.X / RenderScaling, _maxTrackSize.Y / RenderScaling);
public IMouseDevice MouseDevice => _mouseDevice;
public WindowState WindowState
{
get
{
if (!IsWindowVisible(_hwnd))
{
return _showWindowState;
}
if (_isFullScreenActive)
{
return WindowState.FullScreen;
}
GetWindowPlacement(_hwnd, out var placement);
return placement.ShowCmd switch
{
ShowWindowCommand.Maximize => WindowState.Maximized,
ShowWindowCommand.Minimize => WindowState.Minimized,
_ => WindowState.Normal
};
}
set
{
if (IsWindowVisible(_hwnd) && _lastWindowState != value)
{
ShowWindow(value, value != WindowState.Minimized); // If the window is minimized, it shouldn't be activated
}
_lastWindowState = value;
_showWindowState = value;
}
}
public WindowTransparencyLevel TransparencyLevel
{
get => _transparencyLevel;
private set
{
if (_transparencyLevel != value)
{
_transparencyLevel = value;
TransparencyLevelChanged?.Invoke(value);
}
}
}
protected IntPtr Hwnd => _hwnd;
private bool IsMouseInPointerEnabled => _wmPointerEnabled && IsMouseInPointerEnabled();
public object? TryGetFeature(Type featureType)
{
if (featureType == typeof(ITextInputMethodImpl))
{
return Imm32InputMethod.Current;
}
if (featureType == typeof(INativeControlHostImpl))
{
return _nativeControlHost;
}
if (featureType == typeof(IStorageProvider))
{
return _storageProvider;
}
if (featureType == typeof(IClipboard))
{
return AvaloniaLocator.Current.GetRequiredService<IClipboard>();
}
if (featureType == typeof(IInputPane))
{
return _inputPane;
}
if (featureType == typeof(ILauncher))
{
return new BclLauncher();
}
return null;
}
public void SetTransparencyLevelHint(IReadOnlyList<WindowTransparencyLevel> transparencyLevels)
{
foreach (var level in transparencyLevels)
{
if (!IsSupported(level))
continue;
if (level == TransparencyLevel)
{
return;
}
if (level == WindowTransparencyLevel.Transparent)
{
if (!SetTransparencyTransparent())
continue;
}
else if (level == WindowTransparencyLevel.AcrylicBlur)
{
if (!SetTransparencyAcrylicBlur())
continue;
}
else if (level == WindowTransparencyLevel.Mica)
{
if (!SetTransparencyMica())
continue;
}
TransparencyLevel = level;
return;
}
// If we get here, we didn't find a supported level. Report the default.
TransparencyLevel = _defaultTransparencyLevel;
}
private bool IsSupported(WindowTransparencyLevel level)
{
// None is only supported with redirection bitmap.
// Note, it's still possible to have non-transparent window with a fallback background brush.
if (level == WindowTransparencyLevel.None)
return UseRedirectionBitmap;
// Transparent is supported either with DwmEnableBlurBehindWindow (win8+) or with NoRedirectionBitmap.
if (level == WindowTransparencyLevel.Transparent)
return !UseRedirectionBitmap || Win32Platform.WindowsVersion >= PlatformConstants.Windows8;
if (level == WindowTransparencyLevel.Blur)
return CompositionEffectsSurface?.IsBlurSupported(BlurEffect.GaussianBlur) ?? false;
if (level == WindowTransparencyLevel.AcrylicBlur)
return CompositionEffectsSurface?.IsBlurSupported(BlurEffect.Acrylic) ?? false;
if (level == WindowTransparencyLevel.Mica)
return CompositionEffectsSurface?.IsBlurSupported(BlurEffect.MicaDark) ?? false;
return false;
}
private bool SetTransparencyTransparent()
{
if (CompositionEffectsSurface is {} surface)
{
surface.SetBlur(BlurEffect.None);
return true;
}
else
{
return SetLegacyTransparency(true);
}
}
private bool SetTransparencyAcrylicBlur()
{
SetUseHostBackdropBrush(true);
SetLegacyTransparency(false);
CompositionEffectsSurface!.SetBlur(BlurEffect.Acrylic);
return true;
}
/// <summary>
/// Sets the transparency mica
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private bool SetTransparencyMica()
{
SetUseHostBackdropBrush(false);
SetLegacyTransparency(false);
CompositionEffectsSurface!.SetBlur(_currentThemeVariant switch
{
PlatformThemeVariant.Light => BlurEffect.MicaLight,
PlatformThemeVariant.Dark => BlurEffect.MicaDark,
_ => throw new ArgumentOutOfRangeException()
});
return true;
}
private bool SetLegacyTransparency(bool enabled)
{
if (Win32Platform.WindowsVersion < PlatformConstants.Windows8 || !UseRedirectionBitmap)
return false;
// On pre-Win8 this method was blurring a window, which is a different from desired behavior.
// On win8+ we use this method as a fallback, when WinUI/DComp composition with true transparency isn't available.
// Note: there is no guarantee that this behavior won't be changed back to true blur in Win12.
// See https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/nf-dwmapi-dwmenableblurbehindwindow#remarks
// Also https://github.com/qt/qtbase/blob/fd300f143fd30947bba60a03d614acd2711b635f/src/plugins/platforms/windows/qwindowswindow.cpp#L519
var blurInfo = new DWM_BLURBEHIND();
blurInfo.fEnable = enabled;
blurInfo.dwFlags = DWM_BB.Enable | DWM_BB.BlurRegion;
blurInfo.hRgnBlur = CreateRectRgn(0, 0, -1, -1);
var result = DwmEnableBlurBehindWindow(_hwnd, ref blurInfo);
if (blurInfo.hRgnBlur != default)
{
DeleteObject(blurInfo.hRgnBlur);
}
return result == 0;
}
private unsafe bool SetUseHostBackdropBrush(bool useHostBackdropBrush)
{
if (Win32Platform.WindowsVersion < WinUiCompositionShared.MinHostBackdropVersion)
return false;
// AcrylicBlur requires window to set DWMWA_USE_HOSTBACKDROPBRUSH flag on Win11+.
// It's not necessary on older versions and it's not necessary with Mica brush.
var pvUseBackdropBrush = useHostBackdropBrush ? 1 : 0;
var result = DwmSetWindowAttribute(_hwnd, (int)DwmWindowAttribute.DWMWA_USE_HOSTBACKDROPBRUSH, &pvUseBackdropBrush, sizeof(int));
return result == 0;
}
public IEnumerable<object> Surfaces
=> _glSurface is null ?
new object[] { Handle, _framebuffer } :
new object[] { Handle, _glSurface, _framebuffer };
public PixelPoint Position
{
get
{
GetWindowRect(_hwnd, out var rc);
var border = HiddenBorderSize;
return new PixelPoint(rc.left + border.Width, rc.top + border.Height);
}
set
{
var border = HiddenBorderSize;
value = new PixelPoint(value.X - border.Width, value.Y - border.Height);
SetWindowPos(
Handle.Handle,
IntPtr.Zero,
value.X,
value.Y,
0,
0,
SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOZORDER);
}
}
private bool HasFullDecorations => _windowProperties.Decorations == SystemDecorations.Full;
private PixelSize HiddenBorderSize
{
get
{
// Windows 10 and 11 add a 7 pixel invisible border on the left/right/bottom of windows for resizing
if (Win32Platform.WindowsVersion.Major < 10 || !HasFullDecorations || GetStyle().HasFlag(WindowStyles.WS_POPUP))
{
return PixelSize.Empty;
}
DwmGetWindowAttribute(_hwnd, (int)DwmWindowAttribute.DWMWA_EXTENDED_FRAME_BOUNDS, out var clientRect, Marshal.SizeOf<RECT>());
GetWindowRect(_hwnd, out var frameRect);
var borderWidth = GetSystemMetrics(SystemMetric.SM_CXBORDER);
return new PixelSize(clientRect.left - frameRect.left - borderWidth, 0);
}
}
public void Move(PixelPoint point) => Position = point;
public void SetMinMaxSize(Size minSize, Size maxSize)
{
_minSize = minSize;
_maxSize = maxSize;
}
public Compositor Compositor => Win32Platform.Compositor;
public void Resize(Size value, WindowResizeReason reason)
{
int requestedClientWidth = (int)(value.Width * RenderScaling);
int requestedClientHeight = (int)(value.Height * RenderScaling);
GetClientRect(_hwnd, out var currentClientRect);
if (currentClientRect.Width == requestedClientWidth && currentClientRect.Height == requestedClientHeight)
{
// Don't update our window position if the client size is already correct. This leads to Windows updating our
// "normal position" (i.e. restored bounds) to match our maximised or areo snap size, which is incorrect behaviour.
// We only want to proceed with this method if the new size is coming from Avalonia.
return;
}
if (_lastWindowState == WindowState.FullScreen)
{
// Fullscreen mode is really a restored window without a frame filling the whole monitor.
// It doesn't make sense to resize the window in this state, so ignore this request.
Logger.TryGet(LogEventLevel.Warning, LogArea.Win32Platform)?.Log(this, "Ignoring resize event on fullscreen window.");
return;
}
GetWindowPlacement(_hwnd, out var windowPlacement);
var clientScreenOrigin = new POINT();
ClientToScreen(_hwnd, ref clientScreenOrigin);
var requestedClientRect = new RECT
{
left = clientScreenOrigin.X,
right = clientScreenOrigin.X + requestedClientWidth,
top = clientScreenOrigin.Y,
bottom = clientScreenOrigin.Y + requestedClientHeight,
};
var requestedWindowRect = _isClientAreaExtended ? requestedClientRect : ClientRectToWindowRect(requestedClientRect);
if (requestedWindowRect.Width == windowPlacement.NormalPosition.Width && requestedWindowRect.Height == windowPlacement.NormalPosition.Height)
{
return;
}
windowPlacement.NormalPosition = requestedWindowRect;
windowPlacement.ShowCmd = !_shown ? ShowWindowCommand.Hide : _lastWindowState switch
{
WindowState.Minimized => ShowWindowCommand.ShowMinNoActive,
WindowState.Maximized => ShowWindowCommand.ShowMaximized,
WindowState.Normal => ShowWindowCommand.ShowNoActivate,
_ => throw new NotImplementedException(),
};
using var scope = SetResizeReason(reason);
SetWindowPlacement(_hwnd, in windowPlacement);
}
public void Activate()
{
SetForegroundWindow(_hwnd);
}
public IPopupImpl? CreatePopup() => Win32Platform.UseOverlayPopups ? null : new PopupImpl(this);
public void Dispose()
{
if (_hwnd != IntPtr.Zero)
{
// Detect if we are being closed programmatically - this would mean that WM_CLOSE was not called
// and we didn't prepare this window for destruction.
if (!_isCloseRequested)
{
BeforeCloseCleanup(true);
}
DestroyWindow(_hwnd);
_hwnd = IntPtr.Zero;
}
ClearIconCache();
}
public void Invalidate(Rect rect)
{
var scaling = RenderScaling;
var r = new RECT
{
left = (int)Math.Floor(rect.X * scaling),
top = (int)Math.Floor(rect.Y * scaling),
right = (int)Math.Ceiling(rect.Right * scaling),
bottom = (int)Math.Ceiling(rect.Bottom * scaling),
};
InvalidateRect(_hwnd, ref r, false);
}
public Point PointToClient(PixelPoint point)
{
var p = new POINT { X = point.X, Y = point.Y };
ScreenToClient(_hwnd, ref p);
return new Point(p.X, p.Y) / RenderScaling;
}
public PixelPoint PointToScreen(Point point)
{
point *= RenderScaling;
var p = new POINT { X = (int)point.X, Y = (int)point.Y };
ClientToScreen(_hwnd, ref p);
return new PixelPoint(p.X, p.Y);
}
public void SetInputRoot(IInputRoot inputRoot)
{
_owner = inputRoot;
CreateDropTarget(inputRoot);
}
public void Hide()
{
UnmanagedMethods.ShowWindow(_hwnd, ShowWindowCommand.Hide);
}
public virtual void Show(bool activate, bool isDialog)
{
SetParent(_parent);
ShowWindow(_showWindowState, activate);
}
public Action? GotInputWhenDisabled { get; set; }
public void SetParent(IWindowImpl? parent)
{
_parent = parent as WindowImpl;
var parentHwnd = _parent?._hwnd ?? IntPtr.Zero;
if (parentHwnd == IntPtr.Zero && !_windowProperties.ShowInTaskbar)
{
parentHwnd = OffscreenParentWindow.Handle;
}
_hiddenWindowIsParent = parentHwnd == OffscreenParentWindow.Handle;
SetWindowLongPtr(_hwnd, (int)WindowLongParam.GWL_HWNDPARENT, parentHwnd);
}
public void SetEnabled(bool enable) => EnableWindow(_hwnd, enable);
public void BeginMoveDrag(PointerPressedEventArgs e)
{
e.Pointer.Capture(null);
Dispatcher.UIThread.Post(() =>
{
if (e.Pointer.IsPrimary)
{
// SendMessage's return value is dependent on the message send. WM_SYSCOMMAND
// and WM_LBUTTONUP return value just signify whether the WndProc handled the
// message or not, so they are not interesting
SendMessage(_hwnd, (int)WindowsMessage.WM_SYSCOMMAND, (IntPtr)SC_MOUSEMOVE, IntPtr.Zero);
SendMessage(_hwnd, (int)WindowsMessage.WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero);
}
else
{
throw new InvalidOperationException("BeginMoveDrag Failed");
}
}, DispatcherPriority.Send);
}
public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e)
{
if (_windowProperties.IsResizable)
{
#if USE_MANAGED_DRAG
_managedDrag.BeginResizeDrag(edge, ScreenToClient(MouseDevice.Position.ToPoint(_scaling)));
#else
e.Pointer.Capture(null);
DefWindowProc(_hwnd, (int)WindowsMessage.WM_NCLBUTTONDOWN,
new IntPtr((int)s_edgeLookup[edge]), IntPtr.Zero);
#endif
}
}
public void SetTitle(string? title)
{
SetWindowText(_hwnd, title);
}
public void SetCursor(ICursorImpl? cursor)
{
var impl = cursor as CursorImpl;
var hCursor = impl?.Handle ?? s_defaultCursor;
SetClassLong(_hwnd, ClassLongIndex.GCLP_HCURSOR, hCursor);
if (Owner.IsPointerOver)
{
UnmanagedMethods.SetCursor(hCursor);
}
}
public void SetIcon(IWindowIconImpl? icon)
{
_iconImpl = (IconImpl?)icon;
ClearIconCache();
RefreshIcon();
}
private void ClearIconCache()
{
foreach (var icon in _iconCache.Values)
{
icon.Dispose();
}
_iconCache.Clear();
}
private Win32Icon? LoadIcon(Icons type, uint dpi)
{
if (_iconImpl == null)
{
return null;
}
if (type == Icons.ICON_SMALL2)
{
type = Icons.ICON_SMALL;
}
var iconKey = (type, dpi);
if (!_iconCache.TryGetValue(iconKey, out var icon))
{
var scale = dpi / 96.0;
_iconCache[iconKey] = icon = type switch
{
Icons.ICON_SMALL => _iconImpl.LoadSmallIcon(scale),
Icons.ICON_BIG => _iconImpl.LoadBigIcon(scale),
_ => throw new NotImplementedException(),
};
}
return icon;
}
private void RefreshIcon()
{
SendMessage(_hwnd, (int)WindowsMessage.WM_SETICON, (nint)Icons.ICON_SMALL, LoadIcon(Icons.ICON_SMALL, _dpi)?.Handle ?? default);
SendMessage(_hwnd, (int)WindowsMessage.WM_SETICON, (nint)Icons.ICON_BIG, LoadIcon(Icons.ICON_BIG, _dpi)?.Handle ?? default);
TaskBarList.SetOverlayIcon(_hwnd, default, null); // This will prompt the taskbar to redraw the icon
}
public void ShowTaskbarIcon(bool value)
{
var newWindowProperties = _windowProperties;
newWindowProperties.ShowInTaskbar = value;
UpdateWindowProperties(newWindowProperties);
}
public void CanResize(bool value)
{
var newWindowProperties = _windowProperties;
newWindowProperties.IsResizable = value;
UpdateWindowProperties(newWindowProperties);
}
public void SetSystemDecorations(SystemDecorations value)
{
var newWindowProperties = _windowProperties;
newWindowProperties.Decorations = value;
UpdateWindowProperties(newWindowProperties);
}
public void SetTopmost(bool value)
{
if (value == _topmost)
{
return;
}
IntPtr hWndInsertAfter = value ? WindowPosZOrder.HWND_TOPMOST : WindowPosZOrder.HWND_NOTOPMOST;
SetWindowPos(_hwnd,
hWndInsertAfter,
0, 0, 0, 0,
SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE);
_topmost = value;
}
public unsafe void SetFrameThemeVariant(PlatformThemeVariant themeVariant)
{
_currentThemeVariant = themeVariant;
if (Win32Platform.WindowsVersion.Build >= 22000)
{
var pvUseBackdropBrush = themeVariant == PlatformThemeVariant.Dark ? 1 : 0;
DwmSetWindowAttribute(
_hwnd,
(int)DwmWindowAttribute.DWMWA_USE_IMMERSIVE_DARK_MODE,
&pvUseBackdropBrush,
sizeof(int));
if (TransparencyLevel == WindowTransparencyLevel.Mica)
{
SetTransparencyMica();
}
}
}
protected virtual IntPtr CreateWindowOverride(ushort atom)
{
return CreateWindowEx(
UseRedirectionBitmap ? 0 : (int)WindowStyles.WS_EX_NOREDIRECTIONBITMAP,
atom,
null,
(int)WindowStyles.WS_OVERLAPPEDWINDOW | (int)WindowStyles.WS_CLIPCHILDREN,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
}
[MemberNotNull(nameof(_wndProcDelegate))]
[MemberNotNull(nameof(_className))]
[MemberNotNull(nameof(Handle))]
private void CreateWindow()
{
// Ensure that the delegate doesn't get garbage collected by storing it as a field.
_wndProcDelegate = WndProcMessageHandler;
_className = $"Avalonia-{Guid.NewGuid().ToString()}";
// Unique DC helps with performance when using Gpu based rendering
const ClassStyles windowClassStyle = ClassStyles.CS_OWNDC | ClassStyles.CS_HREDRAW | ClassStyles.CS_VREDRAW;
var wndClassEx = new WNDCLASSEX
{
cbSize = Marshal.SizeOf<WNDCLASSEX>(),
style = (int)windowClassStyle,
lpfnWndProc = _wndProcDelegate,
hInstance = GetModuleHandle(null),
hCursor = s_defaultCursor,
hbrBackground = IntPtr.Zero,
lpszClassName = _className
};
ushort atom = RegisterClassEx(ref wndClassEx);
if (atom == 0)
{
throw new Win32Exception();
}
_hwnd = CreateWindowOverride(atom);
if (_hwnd == IntPtr.Zero)
{
throw new Win32Exception();
}
Handle = new WindowImplPlatformHandle(this);
RegisterTouchWindow(_hwnd, 0);
if (ShCoreAvailable && Win32Platform.WindowsVersion > PlatformConstants.Windows8)
{
var monitor = MonitorFromWindow(
_hwnd,
MONITOR.MONITOR_DEFAULTTONEAREST);
if (GetDpiForMonitor(
monitor,
MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI,
out _dpi,
out _) == 0)
{
_scaling = _dpi / StandardDpi;
}
}
}
private IntPtr WndProcMessageHandler(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
bool handled = false;
IntPtr ret = IntPtr.Zero;
if (WndProcHookCallback is { } callback)
ret = callback(hWnd, msg, wParam, lParam, ref handled);
if (handled)
return ret;
return WndProc(hWnd, msg, wParam, lParam);
}
private void CreateDropTarget(IInputRoot inputRoot)
{
if (AvaloniaLocator.Current.GetService<IDragDropDevice>() is { } dragDropDevice)
{
var odt = new OleDropTarget(this, inputRoot, dragDropDevice);
if (OleContext.Current?.RegisterDragDrop(Handle, odt) ?? false)
{
_dropTarget = odt;
}
}
}
/// <summary>
/// Ported from https://github.com/chromium/chromium/blob/master/ui/views/win/fullscreen_handler.cc
/// Method must only be called from inside UpdateWindowProperties.
/// </summary>
/// <param name="fullscreen"></param>
private void SetFullScreen(bool fullscreen)
{
if (fullscreen)
{
GetWindowRect(_hwnd, out var windowRect);
GetClientRect(_hwnd, out var clientRect);
clientRect.left += windowRect.left;
clientRect.right += windowRect.left;
clientRect.top += windowRect.top;
clientRect.bottom += windowRect.top;