-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathqwindowswindow.cpp
3176 lines (2830 loc) · 115 KB
/
qwindowswindow.cpp
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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#if defined(WINVER) && WINVER < 0x0601
# undef WINVER
#endif
#if !defined(WINVER)
# define WINVER 0x0601 // Enable touch functions for MinGW
#endif
#include "qwindowswindow.h"
#include "qwindowscontext.h"
#if QT_CONFIG(draganddrop)
# include "qwindowsdrag.h"
#endif
#include "qwindowsscreen.h"
#include "qwindowsintegration.h"
#include "qwindowsmenu.h"
#include "qwindowsnativeinterface.h"
#if QT_CONFIG(dynamicgl)
# include "qwindowsglcontext.h"
#else
# include "qwindowsopenglcontext.h"
#endif
#include "qwindowsopengltester.h"
#ifdef QT_NO_CURSOR
# include "qwindowscursor.h"
#endif
#include <QtGui/qguiapplication.h>
#include <QtGui/qscreen.h>
#include <QtGui/qwindow.h>
#include <QtGui/qregion.h>
#include <QtGui/qopenglcontext.h>
#include <private/qsystemlibrary_p.h>
#include <private/qwindow_p.h> // QWINDOWSIZE_MAX
#include <private/qguiapplication_p.h>
#include <private/qhighdpiscaling_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <QtCore/qdebug.h>
#include <QtCore/qlibraryinfo.h>
#include <QtCore/qoperatingsystemversion.h>
#include <dwmapi.h>
#if QT_CONFIG(vulkan)
#include "qwindowsvulkaninstance.h"
#endif
QT_BEGIN_NAMESPACE
using QWindowCreationContextPtr = QSharedPointer<QWindowCreationContext>;
enum {
defaultWindowWidth = 160,
defaultWindowHeight = 160
};
Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &);
static QByteArray debugWinStyle(DWORD style)
{
QByteArray rc = "0x";
rc += QByteArray::number(qulonglong(style), 16);
if (style & WS_POPUP)
rc += " WS_POPUP";
if (style & WS_CHILD)
rc += " WS_CHILD";
if (style & WS_OVERLAPPED)
rc += " WS_OVERLAPPED";
if (style & WS_CLIPSIBLINGS)
rc += " WS_CLIPSIBLINGS";
if (style & WS_CLIPCHILDREN)
rc += " WS_CLIPCHILDREN";
if (style & WS_THICKFRAME)
rc += " WS_THICKFRAME";
if (style & WS_DLGFRAME)
rc += " WS_DLGFRAME";
if (style & WS_SYSMENU)
rc += " WS_SYSMENU";
if (style & WS_MINIMIZEBOX)
rc += " WS_MINIMIZEBOX";
if (style & WS_MAXIMIZEBOX)
rc += " WS_MAXIMIZEBOX";
return rc;
}
static QByteArray debugWinExStyle(DWORD exStyle)
{
QByteArray rc = "0x";
rc += QByteArray::number(qulonglong(exStyle), 16);
if (exStyle & WS_EX_TOOLWINDOW)
rc += " WS_EX_TOOLWINDOW";
if (exStyle & WS_EX_CONTEXTHELP)
rc += " WS_EX_CONTEXTHELP";
if (exStyle & WS_EX_LAYERED)
rc += " WS_EX_LAYERED";
if (exStyle & WS_EX_DLGMODALFRAME)
rc += " WS_EX_DLGMODALFRAME";
if (exStyle & WS_EX_LAYOUTRTL)
rc += " WS_EX_LAYOUTRTL";
if (exStyle & WS_EX_NOINHERITLAYOUT)
rc += " WS_EX_NOINHERITLAYOUT";
return rc;
}
static QByteArray debugWinSwpPos(UINT flags)
{
QByteArray rc = "0x";
rc += QByteArray::number(flags, 16);
if (flags & SWP_FRAMECHANGED)
rc += " SWP_FRAMECHANGED";
if (flags & SWP_HIDEWINDOW)
rc += " SWP_HIDEWINDOW";
if (flags & SWP_NOACTIVATE)
rc += " SWP_NOACTIVATE";
if (flags & SWP_NOCOPYBITS)
rc += " SWP_NOCOPYBITS";
if (flags & SWP_NOMOVE)
rc += " SWP_NOMOVE";
if (flags & SWP_NOOWNERZORDER)
rc += " SWP_NOOWNERZORDER";
if (flags & SWP_NOREDRAW)
rc += " SWP_NOREDRAW";
if (flags & SWP_NOSENDCHANGING)
rc += " SWP_NOSENDCHANGING";
if (flags & SWP_NOSIZE)
rc += " SWP_NOSIZE";
if (flags & SWP_NOZORDER)
rc += " SWP_NOZORDER";
if (flags & SWP_SHOWWINDOW)
rc += " SWP_SHOWWINDOW";
return rc;
}
static inline QSize qSizeOfRect(const RECT &rect)
{
return QSize(rect.right -rect.left, rect.bottom - rect.top);
}
static inline QRect qrectFromRECT(const RECT &rect)
{
return QRect(QPoint(rect.left, rect.top), qSizeOfRect(rect));
}
static inline RECT RECTfromQRect(const QRect &rect)
{
const int x = rect.left();
const int y = rect.top();
RECT result = { x, y, x + rect.width(), y + rect.height() };
return result;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug d, const RECT &r)
{
QDebugStateSaver saver(d);
d.nospace();
d << "RECT(left=" << r.left << ", top=" << r.top
<< ", right=" << r.right << ", bottom=" << r.bottom
<< " (" << r.right - r.left << 'x' << r.bottom - r.top << "))";
return d;
}
QDebug operator<<(QDebug d, const POINT &p)
{
d << p.x << ',' << p.y;
return d;
}
QDebug operator<<(QDebug d, const WINDOWPOS &wp)
{
QDebugStateSaver saver(d);
d.nospace();
d.noquote();
d << "WINDOWPOS(flags=" << debugWinSwpPos(wp.flags) << ", hwnd="
<< wp.hwnd << ", hwndInsertAfter=" << wp.hwndInsertAfter << ", x=" << wp.x
<< ", y=" << wp.y << ", cx=" << wp.cx << ", cy=" << wp.cy << ')';
return d;
}
QDebug operator<<(QDebug d, const NCCALCSIZE_PARAMS &p)
{
QDebugStateSaver saver(d);
d.nospace();
d << "NCCALCSIZE_PARAMS(rgrc=[" << p.rgrc[0] << ' ' << p.rgrc[1] << ' '
<< p.rgrc[2] << "], lppos=" << *p.lppos << ')';
return d;
}
QDebug operator<<(QDebug d, const MINMAXINFO &i)
{
QDebugStateSaver saver(d);
d.nospace();
d << "MINMAXINFO maxSize=" << i.ptMaxSize.x << ','
<< i.ptMaxSize.y << " maxpos=" << i.ptMaxPosition.x
<< ',' << i.ptMaxPosition.y << " mintrack="
<< i.ptMinTrackSize.x << ',' << i.ptMinTrackSize.y
<< " maxtrack=" << i.ptMaxTrackSize.x << ',' << i.ptMaxTrackSize.y;
return d;
}
QDebug operator<<(QDebug d, const WINDOWPLACEMENT &wp)
{
QDebugStateSaver saver(d);
d.nospace();
d.noquote();
d << "WINDOWPLACEMENT(flags=0x" << Qt::hex << wp.flags << Qt::dec << ", showCmd="
<< wp.showCmd << ", ptMinPosition=" << wp.ptMinPosition << ", ptMaxPosition=" << wp.ptMaxPosition
<< ", rcNormalPosition=" << wp.rcNormalPosition;
return d;
}
QDebug operator<<(QDebug d, const GUID &guid)
{
QDebugStateSaver saver(d);
d.nospace();
d << '{' << Qt::hex << Qt::uppercasedigits << qSetPadChar(u'0')
<< qSetFieldWidth(8) << guid.Data1
<< qSetFieldWidth(0) << '-' << qSetFieldWidth(4)
<< guid.Data2 << qSetFieldWidth(0) << '-' << qSetFieldWidth(4)
<< guid.Data3 << qSetFieldWidth(0) << '-' << qSetFieldWidth(4)
<< qSetFieldWidth(2) << guid.Data4[0] << guid.Data4[1]
<< qSetFieldWidth(0) << '-' << qSetFieldWidth(2);
for (int i = 2; i < 8; ++i)
d << guid.Data4[i];
d << qSetFieldWidth(0) << '}';
return d;
}
#endif // !QT_NO_DEBUG_STREAM
static void formatBriefRectangle(QDebug &d, const QRect &r)
{
d << r.width() << 'x' << r.height() << Qt::forcesign << r.x() << r.y() << Qt::noforcesign;
}
static void formatBriefMargins(QDebug &d, const QMargins &m)
{
d << m.left() << ", " << m.top() << ", " << m.right() << ", " << m.bottom();
}
// QTBUG-43872, for windows that do not have WS_EX_TOOLWINDOW set, WINDOWPLACEMENT
// is in workspace/available area coordinates.
static QPoint windowPlacementOffset(HWND hwnd, const QPoint &point)
{
if (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)
return QPoint(0, 0);
const QWindowsScreenManager &screenManager = QWindowsContext::instance()->screenManager();
const QWindowsScreen *screen = screenManager.screens().size() == 1
? screenManager.screens().constFirst() : screenManager.screenAtDp(point);
if (screen)
return screen->availableGeometry().topLeft() - screen->geometry().topLeft();
return QPoint(0, 0);
}
// Return the frame geometry relative to the parent
// if there is one.
static inline QRect frameGeometry(HWND hwnd, bool topLevel)
{
RECT rect = { 0, 0, 0, 0 };
if (topLevel) {
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(hwnd, &windowPlacement);
if (windowPlacement.showCmd == SW_SHOWMINIMIZED) {
const QRect result = qrectFromRECT(windowPlacement.rcNormalPosition);
return result.translated(windowPlacementOffset(hwnd, result.topLeft()));
}
}
GetWindowRect(hwnd, &rect); // Screen coordinates.
const HWND parent = GetParent(hwnd);
if (parent && !topLevel) {
const int width = rect.right - rect.left;
const int height = rect.bottom - rect.top;
POINT leftTop = { rect.left, rect.top };
screenToClient(parent, &leftTop);
rect.left = leftTop.x;
rect.top = leftTop.y;
rect.right = leftTop.x + width;
rect.bottom = leftTop.y + height;
}
return qrectFromRECT(rect);
}
// Return the visibility of the Window (except full screen since it is not a window state).
static QWindow::Visibility windowVisibility_sys(HWND hwnd)
{
if (!IsWindowVisible(hwnd))
return QWindow::Hidden;
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(WINDOWPLACEMENT);
if (GetWindowPlacement(hwnd, &windowPlacement)) {
switch (windowPlacement.showCmd) {
case SW_SHOWMINIMIZED:
case SW_MINIMIZE:
case SW_FORCEMINIMIZE:
return QWindow::Minimized;
case SW_SHOWMAXIMIZED:
return QWindow::Maximized;
default:
break;
}
}
return QWindow::Windowed;
}
static inline bool windowIsAccelerated(const QWindow *w)
{
switch (w->surfaceType()) {
case QSurface::OpenGLSurface:
return true;
case QSurface::RasterGLSurface:
return qt_window_private(const_cast<QWindow *>(w))->compositing;
case QSurface::VulkanSurface:
return true;
case QSurface::Direct3DSurface:
return true;
default:
return false;
}
}
static bool applyBlurBehindWindow(HWND hwnd)
{
BOOL compositionEnabled;
if (DwmIsCompositionEnabled(&compositionEnabled) != S_OK)
return false;
DWM_BLURBEHIND blurBehind = {0, 0, nullptr, 0};
if (compositionEnabled) {
blurBehind.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
blurBehind.fEnable = TRUE;
blurBehind.hRgnBlur = CreateRectRgn(0, 0, -1, -1);
} else {
blurBehind.dwFlags = DWM_BB_ENABLE;
blurBehind.fEnable = FALSE;
}
const bool result = DwmEnableBlurBehindWindow(hwnd, &blurBehind) == S_OK;
if (blurBehind.hRgnBlur)
DeleteObject(blurBehind.hRgnBlur);
return result;
}
// from qwidget_win.cpp, pass flags separately in case they have been "autofixed".
static bool shouldShowMaximizeButton(const QWindow *w, Qt::WindowFlags flags)
{
if ((flags & Qt::MSWindowsFixedSizeDialogHint) || !(flags & Qt::WindowMaximizeButtonHint))
return false;
// if the user explicitly asked for the maximize button, we try to add
// it even if the window has fixed size.
return (flags & Qt::CustomizeWindowHint) ||
w->maximumSize() == QSize(QWINDOWSIZE_MAX, QWINDOWSIZE_MAX);
}
// Set the WS_EX_LAYERED flag on a HWND if required. This is required for
// translucent backgrounds, not fully opaque windows and for
// Qt::WindowTransparentForInput (in combination with WS_EX_TRANSPARENT).
bool QWindowsWindow::setWindowLayered(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, qreal opacity)
{
const LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
const bool needsLayered = (flags & Qt::WindowTransparentForInput)
|| (hasAlpha && (flags & Qt::FramelessWindowHint)) || opacity < 1.0;
const bool isLayered = (exStyle & WS_EX_LAYERED);
if (needsLayered != isLayered) {
if (needsLayered) {
SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED);
} else {
SetWindowLong(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED);
}
}
return needsLayered;
}
static void setWindowOpacity(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, bool accelerated, qreal level)
{
if (QWindowsWindow::setWindowLayered(hwnd, flags, hasAlpha, level)) {
const BYTE alpha = BYTE(qRound(255.0 * level));
if (hasAlpha && !accelerated && (flags & Qt::FramelessWindowHint)) {
// Non-GL windows with alpha: Use blend function to update.
BLENDFUNCTION blend = {AC_SRC_OVER, 0, alpha, AC_SRC_ALPHA};
UpdateLayeredWindow(hwnd, nullptr, nullptr, nullptr, nullptr, nullptr, 0, &blend, ULW_ALPHA);
} else {
SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA);
}
} else if (IsWindowVisible(hwnd)) { // Repaint when switching from layered.
InvalidateRect(hwnd, nullptr, TRUE);
}
}
static inline void updateGLWindowSettings(const QWindow *w, HWND hwnd, Qt::WindowFlags flags, qreal opacity)
{
const bool isAccelerated = windowIsAccelerated(w);
const bool hasAlpha = w->format().hasAlpha();
if (isAccelerated && hasAlpha)
applyBlurBehindWindow(hwnd);
setWindowOpacity(hwnd, flags, hasAlpha, isAccelerated, opacity);
}
/*!
Calculates the dimensions of the invisible borders within the
window frames in Windows 10, using an empirical expression that
reproduces the measured values for standard DPI settings.
*/
static QMargins invisibleMargins(QPoint screenPoint)
{
if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows10) {
POINT pt = {screenPoint.x(), screenPoint.y()};
if (HMONITOR hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL)) {
if (QWindowsContext::shcoredll.isValid()) {
UINT dpiX;
UINT dpiY;
if (SUCCEEDED(QWindowsContext::shcoredll.getDpiForMonitor(hMonitor, 0, &dpiX, &dpiY))) {
const qreal sc = (dpiX - 96) / 96.0;
const int gap = 7 + qRound(5*sc) - int(sc);
return QMargins(gap, 0, gap, gap);
}
}
}
}
return QMargins();
}
/*!
\class WindowCreationData
\brief Window creation code.
This struct gathers all information required to create a window.
Window creation is split in 3 steps:
\list
\li fromWindow() Gather all required information
\li create() Create the system handle.
\li initialize() Post creation initialization steps.
\endlist
The reason for this split is to also enable changing the QWindowFlags
by calling:
\list
\li fromWindow() Gather information and determine new system styles
\li applyWindowFlags() to apply the new window system styles.
\li initialize() Post creation initialization steps.
\endlist
Contains the window creation code formerly in qwidget_win.cpp.
\sa QWindowCreationContext
\internal
*/
struct WindowCreationData
{
using WindowData = QWindowsWindowData;
enum Flags { ForceChild = 0x1, ForceTopLevel = 0x2 };
void fromWindow(const QWindow *w, const Qt::WindowFlags flags, unsigned creationFlags = 0);
inline WindowData create(const QWindow *w, const WindowData &data, QString title) const;
inline void applyWindowFlags(HWND hwnd) const;
void initialize(const QWindow *w, HWND h, bool frameChange, qreal opacityLevel) const;
Qt::WindowFlags flags;
HWND parentHandle = nullptr;
Qt::WindowType type = Qt::Widget;
unsigned style = 0;
unsigned exStyle = 0;
bool topLevel = false;
bool popup = false;
bool dialog = false;
bool tool = false;
bool embedded = false;
bool hasAlpha = false;
};
QDebug operator<<(QDebug debug, const WindowCreationData &d)
{
QDebugStateSaver saver(debug);
debug.nospace();
debug.noquote();
debug << "WindowCreationData: " << d.flags
<< "\n topLevel=" << d.topLevel;
if (d.parentHandle)
debug << " parent=" << d.parentHandle;
debug << " popup=" << d.popup << " dialog=" << d.dialog
<< " embedded=" << d.embedded << " tool=" << d.tool
<< "\n style=" << debugWinStyle(d.style);
if (d.exStyle)
debug << "\n exStyle=" << debugWinExStyle(d.exStyle);
return debug;
}
// Fix top level window flags in case only the type flags are passed.
static inline void fixTopLevelWindowFlags(Qt::WindowFlags &flags)
{
// Not supported on Windows, also do correction when it is set.
flags &= ~Qt::WindowFullscreenButtonHint;
switch (flags) {
case Qt::Window:
flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint
|Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint;
break;
case Qt::Dialog:
case Qt::Tool:
flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
break;
default:
break;
}
if ((flags & Qt::WindowType_Mask) == Qt::SplashScreen)
flags |= Qt::FramelessWindowHint;
}
static QScreen *screenForName(const QWindow *w, const QString &name)
{
QScreen *winScreen = w ? w->screen() : QGuiApplication::primaryScreen();
if (winScreen && winScreen->name() != name) {
const auto screens = winScreen->virtualSiblings();
for (QScreen *screen : screens) {
if (screen->name() == name)
return screen;
}
}
return winScreen;
}
static QPoint calcPosition(const QWindow *w, const QWindowCreationContextPtr &context, const QMargins &invMargins)
{
const QPoint orgPos(context->frameX - invMargins.left(), context->frameY - invMargins.top());
if (!w || (!w->isTopLevel() && w->surfaceType() != QWindow::OpenGLSurface))
return orgPos;
// Workaround for QTBUG-50371
const QScreen *screenForGL = QWindowsWindow::forcedScreenForGLWindow(w);
if (!screenForGL)
return orgPos;
const QPoint posFrame(context->frameX, context->frameY);
const QMargins margins = context->margins;
const QRect scrGeo = screenForGL->handle()->availableGeometry();
// Point is already in the required screen.
if (scrGeo.contains(orgPos))
return orgPos;
// If the visible part of the window is already in the
// required screen, just ignore the invisible offset.
if (scrGeo.contains(posFrame))
return posFrame;
// Find the original screen containing the coordinates.
const auto screens = screenForGL->virtualSiblings();
const QScreen *orgScreen = nullptr;
for (QScreen *screen : screens) {
if (screen->handle()->availableGeometry().contains(posFrame)) {
orgScreen = screen;
break;
}
}
const QPoint ctPos = QPoint(qMax(scrGeo.left(), scrGeo.center().x()
+ (margins.right() - margins.left() - context->frameWidth)/2),
qMax(scrGeo.top(), scrGeo.center().y()
+ (margins.bottom() - margins.top() - context->frameHeight)/2));
// If initial coordinates were outside all screens, center the window on the required screen.
if (!orgScreen)
return ctPos;
const QRect orgGeo = orgScreen->handle()->availableGeometry();
const QRect orgFrame(QPoint(context->frameX, context->frameY),
QSize(context->frameWidth, context->frameHeight));
// Window would be centered on orgScreen. Center it on the required screen.
if (orgGeo.center() == (orgFrame - margins).center())
return ctPos;
// Transform the coordinates to map them into the required screen.
const QPoint newPos(scrGeo.left() + ((posFrame.x() - orgGeo.left()) * scrGeo.width()) / orgGeo.width(),
scrGeo.top() + ((posFrame.y() - orgGeo.top()) * scrGeo.height()) / orgGeo.height());
const QPoint newPosNoMargin(newPos.x() - invMargins.left(), newPos.y() - invMargins.top());
return scrGeo.contains(newPosNoMargin) ? newPosNoMargin : newPos;
}
void WindowCreationData::fromWindow(const QWindow *w, const Qt::WindowFlags flagsIn,
unsigned creationFlags)
{
flags = flagsIn;
// Sometimes QWindow doesn't have a QWindow parent but does have a native parent window,
// e.g. in case of embedded ActiveQt servers. They should not be considered a top-level
// windows in such cases.
QVariant prop = w->property(QWindowsWindow::embeddedNativeParentHandleProperty);
if (prop.isValid()) {
embedded = true;
parentHandle = reinterpret_cast<HWND>(prop.value<WId>());
}
if (creationFlags & ForceChild) {
topLevel = false;
} else if (embedded) {
// Embedded native windows (for example Active X server windows) are by
// definition never toplevel, even though they do not have QWindow parents.
topLevel = false;
} else {
topLevel = (creationFlags & ForceTopLevel) ? true : w->isTopLevel();
}
if (topLevel)
fixTopLevelWindowFlags(flags);
type = static_cast<Qt::WindowType>(int(flags) & Qt::WindowType_Mask);
switch (type) {
case Qt::Dialog:
case Qt::Sheet:
dialog = true;
break;
case Qt::Drawer:
case Qt::Tool:
tool = true;
break;
case Qt::Popup:
popup = true;
break;
default:
break;
}
if ((flags & Qt::MSWindowsFixedSizeDialogHint))
dialog = true;
// This causes the title bar to drawn RTL and the close button
// to be left. Note that this causes:
// - All DCs created on the Window to have RTL layout (see SetLayout)
// - ClientToScreen() and ScreenToClient() to work in reverse as well.
// - Mouse event coordinates to be mirrored.
// - Positioning of child Windows.
if (QGuiApplication::layoutDirection() == Qt::RightToLeft
&& (QWindowsIntegration::instance()->options() & QWindowsIntegration::RtlEnabled) != 0) {
exStyle |= WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT;
}
// Parent: Use transient parent for top levels.
if (popup) {
flags |= Qt::WindowStaysOnTopHint; // a popup stays on top, no parent.
} else if (!embedded) {
if (const QWindow *parentWindow = topLevel ? w->transientParent() : w->parent())
parentHandle = QWindowsWindow::handleOf(parentWindow);
}
if (popup || (type == Qt::ToolTip) || (type == Qt::SplashScreen)) {
style = WS_POPUP;
} else if (topLevel) {
if (flags & Qt::FramelessWindowHint)
style = WS_POPUP; // no border
else if (flags & Qt::WindowTitleHint)
style = WS_OVERLAPPED;
else
style = 0;
} else {
style = WS_CHILD;
}
// if (!testAttribute(Qt::WA_PaintUnclipped))
// ### Commented out for now as it causes some problems, but
// this should be correct anyway, so dig some more into this
#ifdef Q_FLATTEN_EXPOSE
if (windowIsOpenGL(w)) // a bit incorrect since the is-opengl status may change from false to true at any time later on
style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN; // see SetPixelFormat
#else
style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN ;
#endif
if (topLevel) {
if ((type == Qt::Window || dialog || tool)) {
if (!(flags & Qt::FramelessWindowHint)) {
style |= WS_POPUP;
if (flags & Qt::MSWindowsFixedSizeDialogHint) {
style |= WS_DLGFRAME;
} else {
style |= WS_THICKFRAME;
}
if (flags & Qt::WindowTitleHint)
style |= WS_CAPTION; // Contains WS_DLGFRAME
}
if (flags & Qt::WindowSystemMenuHint)
style |= WS_SYSMENU;
else if (dialog && (flags & Qt::WindowCloseButtonHint) && !(flags & Qt::FramelessWindowHint)) {
style |= WS_SYSMENU | WS_BORDER; // QTBUG-2027, dialogs without system menu.
exStyle |= WS_EX_DLGMODALFRAME;
}
if (flags & Qt::WindowMinimizeButtonHint)
style |= WS_MINIMIZEBOX;
if (shouldShowMaximizeButton(w, flags))
style |= WS_MAXIMIZEBOX;
if (tool)
exStyle |= WS_EX_TOOLWINDOW;
if (flags & Qt::WindowContextHelpButtonHint)
exStyle |= WS_EX_CONTEXTHELP;
} else {
exStyle |= WS_EX_TOOLWINDOW;
}
// make mouse events fall through this window
// NOTE: WS_EX_TRANSPARENT flag can make mouse inputs fall through a layered window
if (flagsIn & Qt::WindowTransparentForInput)
exStyle |= WS_EX_LAYERED | WS_EX_TRANSPARENT;
}
}
static inline bool shouldApplyDarkFrame(const QWindow *w)
{
return w->isTopLevel() && !w->flags().testFlag(Qt::FramelessWindowHint);
}
QWindowsWindowData
WindowCreationData::create(const QWindow *w, const WindowData &data, QString title) const
{
WindowData result;
result.flags = flags;
const auto appinst = reinterpret_cast<HINSTANCE>(GetModuleHandle(nullptr));
const QString windowClassName = QWindowsContext::instance()->registerWindowClass(w);
const QScreen *screen{};
const QRect rect = QPlatformWindow::initialGeometry(w, data.geometry,
defaultWindowWidth, defaultWindowHeight,
&screen);
if (title.isEmpty() && (result.flags & Qt::WindowTitleHint))
title = topLevel ? qAppName() : w->objectName();
const auto *titleUtf16 = reinterpret_cast<const wchar_t *>(title.utf16());
const auto *classNameUtf16 = reinterpret_cast<const wchar_t *>(windowClassName.utf16());
// Capture events before CreateWindowEx() returns. The context is cleared in
// the QWindowsWindow constructor.
const QWindowCreationContextPtr context(new QWindowCreationContext(w, screen, data.geometry,
rect, data.customMargins,
style, exStyle));
QWindowsContext::instance()->setWindowCreationContext(context);
const bool hasFrame = (style & (WS_DLGFRAME | WS_THICKFRAME));
QMargins invMargins = topLevel && hasFrame && QWindowsGeometryHint::positionIncludesFrame(w)
? invisibleMargins(QPoint(context->frameX, context->frameY)) : QMargins();
qCDebug(lcQpaWindows).nospace()
<< "CreateWindowEx: " << w << " class=" << windowClassName << " title=" << title
<< '\n' << *this << "\nrequested: " << rect << ": "
<< context->frameWidth << 'x' << context->frameHeight
<< '+' << context->frameX << '+' << context->frameY
<< " custom margins: " << context->customMargins
<< " invisible margins: " << invMargins;
QPoint pos = calcPosition(w, context, invMargins);
// Mirror the position when creating on a parent in RTL mode, ditto for the obtained geometry.
int mirrorParentWidth = 0;
if (!w->isTopLevel() && QWindowsBaseWindow::isRtlLayout(parentHandle)) {
RECT rect;
GetClientRect(parentHandle, &rect);
mirrorParentWidth = rect.right;
}
if (mirrorParentWidth != 0 && pos.x() != CW_USEDEFAULT && context->frameWidth != CW_USEDEFAULT)
pos.setX(mirrorParentWidth - context->frameWidth - pos.x());
result.hwnd = CreateWindowEx(exStyle, classNameUtf16, titleUtf16,
style,
pos.x(), pos.y(),
context->frameWidth, context->frameHeight,
parentHandle, nullptr, appinst, nullptr);
qCDebug(lcQpaWindows).nospace()
<< "CreateWindowEx: returns " << w << ' ' << result.hwnd << " obtained geometry: "
<< context->obtainedPos << context->obtainedSize << ' ' << context->margins;
if (!result.hwnd) {
qErrnoWarning("%s: CreateWindowEx failed", __FUNCTION__);
return result;
}
if (QWindowsContext::isDarkMode()
&& QWindowsIntegration::instance()->darkModeHandling().testFlag(QWindowsApplication::DarkModeWindowFrames)
&& shouldApplyDarkFrame(w)) {
QWindowsWindow::setDarkBorderToWindow(result.hwnd, true);
}
if (mirrorParentWidth != 0) {
context->obtainedPos.setX(mirrorParentWidth - context->obtainedSize.width()
- context->obtainedPos.x());
}
QRect obtainedGeometry(context->obtainedPos, context->obtainedSize);
result.geometry = obtainedGeometry;
result.fullFrameMargins = context->margins;
result.embedded = embedded;
result.hasFrame = hasFrame;
result.customMargins = context->customMargins;
return result;
}
void WindowCreationData::applyWindowFlags(HWND hwnd) const
{
// Keep enabled and visible from the current style.
const LONG_PTR oldStyle = GetWindowLongPtr(hwnd, GWL_STYLE);
const LONG_PTR oldExStyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
const LONG_PTR newStyle = style | (oldStyle & (WS_DISABLED|WS_VISIBLE));
if (oldStyle != newStyle)
SetWindowLongPtr(hwnd, GWL_STYLE, newStyle);
const LONG_PTR newExStyle = exStyle;
if (newExStyle != oldExStyle)
SetWindowLongPtr(hwnd, GWL_EXSTYLE, newExStyle);
qCDebug(lcQpaWindows).nospace() << __FUNCTION__ << hwnd << *this
<< "\n Style from " << debugWinStyle(DWORD(oldStyle)) << "\n to "
<< debugWinStyle(DWORD(newStyle)) << "\n ExStyle from "
<< debugWinExStyle(DWORD(oldExStyle)) << " to "
<< debugWinExStyle(DWORD(newExStyle));
}
void WindowCreationData::initialize(const QWindow *w, HWND hwnd, bool frameChange, qreal opacityLevel) const
{
if (!hwnd)
return;
UINT swpFlags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER;
if (frameChange)
swpFlags |= SWP_FRAMECHANGED;
if (topLevel) {
swpFlags |= SWP_NOACTIVATE;
if ((flags & Qt::WindowStaysOnTopHint) || (type == Qt::ToolTip)) {
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, swpFlags);
if (flags & Qt::WindowStaysOnBottomHint)
qWarning("QWidget: Incompatible window flags: the window can't be on top and on bottom at the same time");
} else if (flags & Qt::WindowStaysOnBottomHint) {
SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, swpFlags);
} else if (frameChange) { // Force WM_NCCALCSIZE with wParam=1 in case of custom margins.
SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, swpFlags);
}
if (flags & (Qt::CustomizeWindowHint|Qt::WindowTitleHint)) {
HMENU systemMenu = GetSystemMenu(hwnd, FALSE);
if (flags & Qt::WindowCloseButtonHint)
EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_ENABLED);
else
EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_GRAYED);
}
updateGLWindowSettings(w, hwnd, flags, opacityLevel);
} else { // child.
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, swpFlags);
}
}
// Scaling helpers for size constraints.
static QSize toNativeSizeConstrained(QSize dip, const QScreen *s)
{
if (QHighDpiScaling::isActive()) {
const qreal factor = QHighDpiScaling::factor(s);
if (!qFuzzyCompare(factor, qreal(1))) {
if (dip.width() > 0 && dip.width() < QWINDOWSIZE_MAX)
dip.setWidth(qRound(qreal(dip.width()) * factor));
if (dip.height() > 0 && dip.height() < QWINDOWSIZE_MAX)
dip.setHeight(qRound(qreal(dip.height()) * factor));
}
}
return dip;
}
/*!
\class QWindowsGeometryHint
\brief Stores geometry constraints and provides utility functions.
Geometry constraints ready to apply to a MINMAXINFO taking frame
into account.
\internal
*/
QMargins QWindowsGeometryHint::frameOnPrimaryScreen(DWORD style, DWORD exStyle)
{
RECT rect = {0,0,0,0};
style &= ~DWORD(WS_OVERLAPPED); // Not permitted, see docs.
if (AdjustWindowRectEx(&rect, style, FALSE, exStyle) == FALSE)
qErrnoWarning("%s: AdjustWindowRectEx failed", __FUNCTION__);
const QMargins result(qAbs(rect.left), qAbs(rect.top),
qAbs(rect.right), qAbs(rect.bottom));
qCDebug(lcQpaWindows).nospace() << __FUNCTION__ << " style="
<< Qt::showbase << Qt::hex << style << " exStyle=" << exStyle << Qt::dec << Qt::noshowbase
<< ' ' << rect << ' ' << result;
return result;
}
QMargins QWindowsGeometryHint::frameOnPrimaryScreen(HWND hwnd)
{
return frameOnPrimaryScreen(DWORD(GetWindowLongPtr(hwnd, GWL_STYLE)),
DWORD(GetWindowLongPtr(hwnd, GWL_EXSTYLE)));
}
QMargins QWindowsGeometryHint::frame(DWORD style, DWORD exStyle, qreal dpi)
{
if (QWindowsContext::user32dll.adjustWindowRectExForDpi == nullptr)
return frameOnPrimaryScreen(style, exStyle);
RECT rect = {0,0,0,0};
style &= ~DWORD(WS_OVERLAPPED); // Not permitted, see docs.
if (QWindowsContext::user32dll.adjustWindowRectExForDpi(&rect, style, FALSE, exStyle,
unsigned(qRound(dpi))) == FALSE) {
qErrnoWarning("%s: AdjustWindowRectExForDpi failed", __FUNCTION__);
}
const QMargins result(qAbs(rect.left), qAbs(rect.top),
qAbs(rect.right), qAbs(rect.bottom));
qCDebug(lcQpaWindows).nospace() << __FUNCTION__ << " style="
<< Qt::showbase << Qt::hex << style << " exStyle=" << exStyle << Qt::dec << Qt::noshowbase
<< " dpi=" << dpi
<< ' ' << rect << ' ' << result;
return result;
}
QMargins QWindowsGeometryHint::frame(HWND hwnd, DWORD style, DWORD exStyle)
{
if (QWindowsScreenManager::isSingleScreen())
return frameOnPrimaryScreen(style, exStyle);
auto screenManager = QWindowsContext::instance()->screenManager();
auto screen = screenManager.screenForHwnd(hwnd);
if (!screen)
screen = screenManager.screens().value(0);
const auto dpi = screen ? screen->logicalDpi().first : qreal(96);
return frame(style, exStyle, dpi);
}
// For newly created windows.
QMargins QWindowsGeometryHint::frame(const QWindow *w, const QRect &geometry,
DWORD style, DWORD exStyle)
{
if (!w->isTopLevel() || w->flags().testFlag(Qt::FramelessWindowHint))
return {};
if (!QWindowsContext::user32dll.adjustWindowRectExForDpi
|| QWindowsScreenManager::isSingleScreen()
|| !QWindowsContext::shouldHaveNonClientDpiScaling(w)) {
return frameOnPrimaryScreen(style, exStyle);
}
qreal dpi = 96;
auto screenManager = QWindowsContext::instance()->screenManager();
auto screen = screenManager.screenAtDp(geometry.center());
if (!screen)
screen = screenManager.screens().value(0);
if (screen)
dpi = screen->logicalDpi().first;
return QWindowsGeometryHint::frame(style, exStyle, dpi);
}
bool QWindowsGeometryHint::handleCalculateSize(const QMargins &customMargins, const MSG &msg, LRESULT *result)
{
// NCCALCSIZE_PARAMS structure if wParam==TRUE
if (!msg.wParam || customMargins.isNull())
return false;
*result = DefWindowProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);