Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwindowswindow.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <QtCore/qt_windows.h>
6#include <QtGui/qpainter.h>
7#include <QtGui/qpen.h>
8#include <QtGui/qstylehints.h>
9#include <QtGui/qtextoption.h>
10
11#include "qwindowswindow.h"
13#if QT_CONFIG(directmanipulation)
14# include "qwindowsdirectmanipulation.h"
15#endif
16#include "qwindowstheme.h"
17#if QT_CONFIG(draganddrop)
18# include "qwindowsdrag.h"
19#endif
20#include "qwindowsscreen.h"
22#include "qwindowsmenu.h"
24#if QT_CONFIG(dynamicgl)
25# include "qwindowsglcontext.h"
26#else
28#endif
30#ifdef QT_NO_CURSOR
31# include "qwindowscursor.h"
32#endif
35
36#include <QtGui/qguiapplication.h>
37#include <QtGui/qscreen.h>
38#include <QtGui/qwindow.h>
39#include <QtGui/qregion.h>
40#include <QtGui/qopenglcontext.h>
41#include <QtGui/qpainterpath.h>
42#include <QtGui/private/qwindowsthemecache_p.h>
43#include <private/qwindow_p.h> // QWINDOWSIZE_MAX
44#include <private/qguiapplication_p.h>
45#include <private/qhighdpiscaling_p.h>
46#include <qpa/qwindowsysteminterface.h>
47#include <private/qsystemlibrary_p.h>
48#include <private/qwinregistry_p.h>
49
50
51#include <QtCore/qdebug.h>
52#include <QtCore/qlibraryinfo.h>
53#include <QtCore/qoperatingsystemversion.h>
54
55#include <dwmapi.h>
56
57#if QT_CONFIG(vulkan)
58#include "qwindowsvulkaninstance.h"
59#endif
60
61#include <shellscalingapi.h>
62
63#include <private/qdxgivsyncservice_p.h>
64
65#ifndef GWL_HWNDPARENT
66# define GWL_HWNDPARENT (-8)
67#endif
68
70
71using namespace Qt::StringLiterals;
72
73using QWindowCreationContextPtr = QSharedPointer<QWindowCreationContext>;
74
75enum {
78};
79
80Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &);
81
82static QByteArray debugWinStyle(DWORD style)
83{
84 QByteArray rc = "0x";
85 rc += QByteArray::number(qulonglong(style), 16);
86 if (style & WS_POPUP)
87 rc += " WS_POPUP";
88 if (style & WS_CHILD)
89 rc += " WS_CHILD";
90 if (style & WS_OVERLAPPED)
91 rc += " WS_OVERLAPPED";
92 if (style & WS_CLIPSIBLINGS)
93 rc += " WS_CLIPSIBLINGS";
94 if (style & WS_CLIPCHILDREN)
95 rc += " WS_CLIPCHILDREN";
96 if (style & WS_THICKFRAME)
97 rc += " WS_THICKFRAME";
98 if (style & WS_DLGFRAME)
99 rc += " WS_DLGFRAME";
100 if (style & WS_SYSMENU)
101 rc += " WS_SYSMENU";
102 if (style & WS_MINIMIZEBOX)
103 rc += " WS_MINIMIZEBOX";
104 if (style & WS_MAXIMIZEBOX)
105 rc += " WS_MAXIMIZEBOX";
106 if (style & WS_BORDER)
107 rc += " WS_BORDER";
108 if (style & WS_CAPTION)
109 rc += " WS_CAPTION";
110 if (style & WS_CHILDWINDOW)
111 rc += " WS_CHILDWINDOW";
112 if (style & WS_DISABLED)
113 rc += " WS_DISABLED";
114 if (style & WS_GROUP)
115 rc += " WS_GROUP";
116 if (style & WS_HSCROLL)
117 rc += " WS_HSCROLL";
118 if (style & WS_ICONIC)
119 rc += " WS_ICONIC";
120 if (style & WS_MAXIMIZE)
121 rc += " WS_MAXIMIZE";
122 if (style & WS_MINIMIZE)
123 rc += " WS_MINIMIZE";
124 if (style & WS_SIZEBOX)
125 rc += " WS_SIZEBOX";
126 if (style & WS_TABSTOP)
127 rc += " WS_TABSTOP";
128 if (style & WS_TILED)
129 rc += " WS_TILED";
130 if (style & WS_VISIBLE)
131 rc += " WS_VISIBLE";
132 if (style & WS_VSCROLL)
133 rc += " WS_VSCROLL";
134 return rc;
135}
136
137static QByteArray debugWinExStyle(DWORD exStyle)
138{
139 QByteArray rc = "0x";
140 rc += QByteArray::number(qulonglong(exStyle), 16);
141 if (exStyle & WS_EX_TOOLWINDOW)
142 rc += " WS_EX_TOOLWINDOW";
143 if (exStyle & WS_EX_CONTEXTHELP)
144 rc += " WS_EX_CONTEXTHELP";
145 if (exStyle & WS_EX_LAYERED)
146 rc += " WS_EX_LAYERED";
147 if (exStyle & WS_EX_DLGMODALFRAME)
148 rc += " WS_EX_DLGMODALFRAME";
149 if (exStyle & WS_EX_LAYOUTRTL)
150 rc += " WS_EX_LAYOUTRTL";
151 if (exStyle & WS_EX_NOINHERITLAYOUT)
152 rc += " WS_EX_NOINHERITLAYOUT";
153 if (exStyle & WS_EX_ACCEPTFILES)
154 rc += " WS_EX_ACCEPTFILES";
155 if (exStyle & WS_EX_APPWINDOW)
156 rc += " WS_EX_APPWINDOW";
157 if (exStyle & WS_EX_CLIENTEDGE)
158 rc += " WS_EX_CLIENTEDGE";
159 if (exStyle & WS_EX_COMPOSITED)
160 rc += " WS_EX_COMPOSITED";
161 if (exStyle & WS_EX_CONTROLPARENT)
162 rc += " WS_EX_CONTROLPARENT";
163 if (exStyle & WS_EX_LEFT)
164 rc += " WS_EX_LEFT";
165 if (exStyle & WS_EX_LEFTSCROLLBAR)
166 rc += " WS_EX_LEFTSCROLLBAR";
167 if (exStyle & WS_EX_LTRREADING)
168 rc += " WS_EX_LTRREADING";
169 if (exStyle & WS_EX_MDICHILD)
170 rc += " WS_EX_MDICHILD";
171 if (exStyle & WS_EX_NOACTIVATE)
172 rc += " WS_EX_NOACTIVATE";
173 if (exStyle & WS_EX_NOPARENTNOTIFY)
174 rc += " WS_EX_NOPARENTNOTIFY";
175 if (exStyle & WS_EX_NOREDIRECTIONBITMAP)
176 rc += " WS_EX_NOREDIRECTIONBITMAP";
177 if (exStyle & WS_EX_RIGHT)
178 rc += " WS_EX_RIGHT";
179 if (exStyle & WS_EX_RIGHTSCROLLBAR)
180 rc += " WS_EX_RIGHTSCROLLBAR";
181 if (exStyle & WS_EX_RTLREADING)
182 rc += " WS_EX_RTLREADING";
183 if (exStyle & WS_EX_STATICEDGE)
184 rc += " WS_EX_STATICEDGE";
185 if (exStyle & WS_EX_TOPMOST)
186 rc += " WS_EX_TOPMOST";
187 if (exStyle & WS_EX_TRANSPARENT)
188 rc += " WS_EX_TRANSPARENT";
189 if (exStyle & WS_EX_WINDOWEDGE)
190 rc += " WS_EX_WINDOWEDGE";
191 return rc;
192}
193
194static QByteArray debugWinSwpPos(UINT flags)
195{
196 QByteArray rc = "0x";
197 rc += QByteArray::number(flags, 16);
198 if (flags & SWP_FRAMECHANGED)
199 rc += " SWP_FRAMECHANGED";
200 if (flags & SWP_HIDEWINDOW)
201 rc += " SWP_HIDEWINDOW";
202 if (flags & SWP_NOACTIVATE)
203 rc += " SWP_NOACTIVATE";
204 if (flags & SWP_NOCOPYBITS)
205 rc += " SWP_NOCOPYBITS";
206 if (flags & SWP_NOMOVE)
207 rc += " SWP_NOMOVE";
208 if (flags & SWP_NOOWNERZORDER)
209 rc += " SWP_NOOWNERZORDER";
210 if (flags & SWP_NOREDRAW)
211 rc += " SWP_NOREDRAW";
212 if (flags & SWP_NOSENDCHANGING)
213 rc += " SWP_NOSENDCHANGING";
214 if (flags & SWP_NOSIZE)
215 rc += " SWP_NOSIZE";
216 if (flags & SWP_NOZORDER)
217 rc += " SWP_NOZORDER";
218 if (flags & SWP_SHOWWINDOW)
219 rc += " SWP_SHOWWINDOW";
220 if (flags & SWP_ASYNCWINDOWPOS)
221 rc += " SWP_ASYNCWINDOWPOS";
222 if (flags & SWP_DEFERERASE)
223 rc += " SWP_DEFERERASE";
224 if (flags & SWP_DRAWFRAME)
225 rc += " SWP_DRAWFRAME";
226 if (flags & SWP_NOREPOSITION)
227 rc += " SWP_NOREPOSITION";
228 return rc;
229}
230
231[[nodiscard]] static inline QByteArray debugWindowPlacementFlags(const UINT flags)
232{
233 QByteArray rc = "0x";
234 rc += QByteArray::number(flags, 16);
235 if (flags & WPF_SETMINPOSITION)
236 rc += " WPF_SETMINPOSITION";
237 if (flags & WPF_RESTORETOMAXIMIZED)
238 rc += " WPF_RESTORETOMAXIMIZED";
239 if (flags & WPF_ASYNCWINDOWPLACEMENT)
240 rc += " WPF_ASYNCWINDOWPLACEMENT";
241 return rc;
242}
243
244[[nodiscard]] static inline QByteArray debugShowWindowCmd(const UINT cmd)
245{
246 QByteArray rc = {};
247 rc += QByteArray::number(cmd);
248 if (cmd == SW_HIDE)
249 rc += " SW_HIDE";
250 if (cmd == SW_SHOWNORMAL)
251 rc += " SW_SHOWNORMAL";
252 if (cmd == SW_NORMAL)
253 rc += " SW_NORMAL";
254 if (cmd == SW_SHOWMINIMIZED)
255 rc += " SW_SHOWMINIMIZED";
256 if (cmd == SW_SHOWMAXIMIZED)
257 rc += " SW_SHOWMAXIMIZED";
258 if (cmd == SW_MAXIMIZE)
259 rc += " SW_MAXIMIZE";
260 if (cmd == SW_SHOWNOACTIVATE)
261 rc += " SW_SHOWNOACTIVATE";
262 if (cmd == SW_SHOW)
263 rc += " SW_SHOW";
264 if (cmd == SW_MINIMIZE)
265 rc += " SW_MINIMIZE";
266 if (cmd == SW_SHOWMINNOACTIVE)
267 rc += " SW_SHOWMINNOACTIVE";
268 if (cmd == SW_SHOWNA)
269 rc += " SW_SHOWNA";
270 if (cmd == SW_RESTORE)
271 rc += " SW_RESTORE";
272 if (cmd == SW_SHOWDEFAULT)
273 rc += " SW_SHOWDEFAULT";
274 if (cmd == SW_FORCEMINIMIZE)
275 rc += " SW_FORCEMINIMIZE";
276 return rc;
277}
278
279static inline QSize qSizeOfRect(const RECT &rect)
280{
281 return QSize(rect.right -rect.left, rect.bottom - rect.top);
282}
283
284static inline QRect qrectFromRECT(const RECT &rect)
285{
286 return QRect(QPoint(rect.left, rect.top), qSizeOfRect(rect));
287}
288
289static inline RECT RECTfromQRect(const QRect &rect)
290{
291 const int x = rect.left();
292 const int y = rect.top();
293 RECT result = { x, y, x + rect.width(), y + rect.height() };
294 return result;
295}
296
297#ifndef QT_NO_DEBUG_STREAM
298QDebug operator<<(QDebug d, const RECT &r)
299{
300 QDebugStateSaver saver(d);
301 d.nospace();
302 d << "RECT(left=" << r.left << ", top=" << r.top
303 << ", right=" << r.right << ", bottom=" << r.bottom
304 << " (" << r.right - r.left << 'x' << r.bottom - r.top << "))";
305 return d;
306}
307
308QDebug operator<<(QDebug d, const POINT &p)
309{
310 QDebugStateSaver saver(d);
311 d.nospace();
312 d << "POINT(x=" << p.x << ", y=" << p.y << ')';
313 return d;
314}
315
316QDebug operator<<(QDebug d, const WINDOWPOS &wp)
317{
318 QDebugStateSaver saver(d);
319 d.nospace();
320 d.noquote();
321 d << "WINDOWPOS(flags=" << debugWinSwpPos(wp.flags) << ", hwnd="
322 << wp.hwnd << ", hwndInsertAfter=" << wp.hwndInsertAfter << ", x=" << wp.x
323 << ", y=" << wp.y << ", cx=" << wp.cx << ", cy=" << wp.cy << ')';
324 return d;
325}
326
327QDebug operator<<(QDebug d, const NCCALCSIZE_PARAMS &p)
328{
329 QDebugStateSaver saver(d);
330 d.nospace();
331 d << "NCCALCSIZE_PARAMS(rgrc=[" << p.rgrc[0] << ", " << p.rgrc[1] << ", "
332 << p.rgrc[2] << "], lppos=" << *p.lppos << ')';
333 return d;
334}
335
336QDebug operator<<(QDebug d, const MINMAXINFO &i)
337{
338 QDebugStateSaver saver(d);
339 d.nospace();
340 d << "MINMAXINFO(maxSize=" << i.ptMaxSize << ", "
341 << "maxpos=" << i.ptMaxPosition << ", "
342 << "maxtrack=" << i.ptMaxTrackSize << ", "
343 << "mintrack=" << i.ptMinTrackSize << ')';
344 return d;
345}
346
347QDebug operator<<(QDebug d, const WINDOWPLACEMENT &wp)
348{
349 QDebugStateSaver saver(d);
350 d.nospace();
351 d.noquote();
352 d << "WINDOWPLACEMENT(flags=" << debugWindowPlacementFlags(wp.flags) << ", showCmd="
353 << debugShowWindowCmd(wp.showCmd) << ", ptMinPosition=" << wp.ptMinPosition
354 << ", ptMaxPosition=" << wp.ptMaxPosition << ", rcNormalPosition="
355 << wp.rcNormalPosition << ')';
356 return d;
357}
358
359QDebug operator<<(QDebug d, const GUID &guid)
360{
361 QDebugStateSaver saver(d);
362 d.nospace();
363 d << '{' << Qt::hex << Qt::uppercasedigits << qSetPadChar(u'0')
364 << qSetFieldWidth(8) << guid.Data1
365 << qSetFieldWidth(0) << '-' << qSetFieldWidth(4)
366 << guid.Data2 << qSetFieldWidth(0) << '-' << qSetFieldWidth(4)
367 << guid.Data3 << qSetFieldWidth(0) << '-' << qSetFieldWidth(4)
368 << qSetFieldWidth(2) << guid.Data4[0] << guid.Data4[1]
369 << qSetFieldWidth(0) << '-' << qSetFieldWidth(2);
370 for (int i = 2; i < 8; ++i)
371 d << guid.Data4[i];
372 d << qSetFieldWidth(0) << '}';
373 return d;
374}
375#endif // !QT_NO_DEBUG_STREAM
376
377static void formatBriefRectangle(QDebug &d, const QRect &r)
378{
379 d << r.width() << 'x' << r.height() << Qt::forcesign << r.x() << r.y() << Qt::noforcesign;
380}
381
382static void formatBriefMargins(QDebug &d, const QMargins &m)
383{
384 d << m.left() << ", " << m.top() << ", " << m.right() << ", " << m.bottom();
385}
386
387// QTBUG-43872, for windows that do not have WS_EX_TOOLWINDOW set, WINDOWPLACEMENT
388// is in workspace/available area coordinates.
389static QPoint windowPlacementOffset(HWND hwnd, const QPoint &point)
390{
391 if (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)
392 return QPoint(0, 0);
394 const QWindowsScreen *screen = screenManager.screens().size() == 1
395 ? screenManager.screens().constFirst() : screenManager.screenAtDp(point);
396 if (screen)
397 return screen->availableGeometry().topLeft() - screen->geometry().topLeft();
398 return QPoint(0, 0);
399}
400
401// Return the frame geometry relative to the parent
402// if there is one.
403static inline QRect frameGeometry(HWND hwnd, bool topLevel)
404{
405 RECT rect = { 0, 0, 0, 0 };
406 if (topLevel) {
407 WINDOWPLACEMENT windowPlacement;
408 windowPlacement.length = sizeof(WINDOWPLACEMENT);
409 GetWindowPlacement(hwnd, &windowPlacement);
410 if (windowPlacement.showCmd == SW_SHOWMINIMIZED) {
411 const QRect result = qrectFromRECT(windowPlacement.rcNormalPosition);
412 return result.translated(windowPlacementOffset(hwnd, result.topLeft()));
413 }
414 }
415 GetWindowRect(hwnd, &rect); // Screen coordinates.
416 const HWND parent = GetParent(hwnd);
417 if (parent && !topLevel) {
418 const int width = rect.right - rect.left;
419 const int height = rect.bottom - rect.top;
420 POINT leftTop = { rect.left, rect.top };
421 screenToClient(parent, &leftTop);
422 rect.left = leftTop.x;
423 rect.top = leftTop.y;
424 rect.right = leftTop.x + width;
425 rect.bottom = leftTop.y + height;
426 }
427 return qrectFromRECT(rect);
428}
429
430// Return the visibility of the Window (except full screen since it is not a window state).
432{
433 if (!IsWindowVisible(hwnd))
434 return QWindow::Hidden;
435 WINDOWPLACEMENT windowPlacement;
436 windowPlacement.length = sizeof(WINDOWPLACEMENT);
437 if (GetWindowPlacement(hwnd, &windowPlacement)) {
438 switch (windowPlacement.showCmd) {
439 case SW_SHOWMINIMIZED:
440 case SW_MINIMIZE:
441 case SW_FORCEMINIMIZE:
442 return QWindow::Minimized;
443 case SW_SHOWMAXIMIZED:
444 return QWindow::Maximized;
445 default:
446 break;
447 }
448 }
449 return QWindow::Windowed;
450}
451
452static inline bool windowIsAccelerated(const QWindow *w)
453{
454 switch (w->surfaceType()) {
455 case QSurface::OpenGLSurface:
456 case QSurface::VulkanSurface:
457 case QSurface::Direct3DSurface:
458 return true;
459 default:
460 return false;
461 }
462}
463
464static bool applyBlurBehindWindow(HWND hwnd)
465{
466 DWM_BLURBEHIND blurBehind = {0, 0, nullptr, 0};
467
468 blurBehind.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
469 blurBehind.fEnable = TRUE;
470 blurBehind.hRgnBlur = CreateRectRgn(0, 0, -1, -1);
471
472 const bool result = DwmEnableBlurBehindWindow(hwnd, &blurBehind) == S_OK;
473
474 if (blurBehind.hRgnBlur)
475 DeleteObject(blurBehind.hRgnBlur);
476
477 return result;
478}
479
480// from qwidget_win.cpp, pass flags separately in case they have been "autofixed".
481static bool shouldShowMaximizeButton(const QWindow *w, Qt::WindowFlags flags)
482{
483 if ((flags & Qt::MSWindowsFixedSizeDialogHint) || !(flags & Qt::WindowMaximizeButtonHint))
484 return false;
485 // if the user explicitly asked for the maximize button, we try to add
486 // it even if the window has fixed size.
487 return (flags & Qt::CustomizeWindowHint) ||
488 w->maximumSize() == QSize(QWINDOWSIZE_MAX, QWINDOWSIZE_MAX);
489}
490
491bool QWindowsWindow::hasNoNativeFrame(HWND hwnd, Qt::WindowFlags flags)
492{
493 const LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE);
494 return (style & WS_CHILD) || (flags & Qt::FramelessWindowHint);
495}
496
497// Set the WS_EX_LAYERED flag on a HWND if required. This is required for
498// translucent backgrounds, not fully opaque windows and for
499// Qt::WindowTransparentForInput (in combination with WS_EX_TRANSPARENT).
500bool QWindowsWindow::setWindowLayered(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, qreal opacity)
501{
502 const LONG_PTR exStyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
503 // Native children are frameless by nature, so check for that as well.
504 const bool needsLayered = (flags & Qt::WindowTransparentForInput)
505 || (hasAlpha && hasNoNativeFrame(hwnd, flags)) || opacity < 1.0;
506 const bool isLayered = (exStyle & WS_EX_LAYERED);
507 if (needsLayered != isLayered) {
508 if (needsLayered) {
509 SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED);
510 } else {
511 SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED);
512 }
513 }
514 return needsLayered;
515}
516
517static void setWindowOpacity(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, bool accelerated, qreal level)
518{
519 if (QWindowsWindow::setWindowLayered(hwnd, flags, hasAlpha, level)) {
520 const BYTE alpha = BYTE(qRound(255.0 * level));
521 if (hasAlpha && !accelerated && QWindowsWindow::hasNoNativeFrame(hwnd, flags)) {
522 // Non-GL windows with alpha: Use blend function to update.
523 BLENDFUNCTION blend = {AC_SRC_OVER, 0, alpha, AC_SRC_ALPHA};
524 UpdateLayeredWindow(hwnd, nullptr, nullptr, nullptr, nullptr, nullptr, 0, &blend, ULW_ALPHA);
525 } else {
526 SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA);
527 }
528 } else if (IsWindowVisible(hwnd)) { // Repaint when switching from layered.
529 InvalidateRect(hwnd, nullptr, TRUE);
530 }
531}
532
533[[nodiscard]] static inline int getResizeBorderThickness(const UINT dpi)
534{
535 // The width of the padded border will always be 0 if DWM composition is
536 // disabled, but since it will always be enabled and can't be programtically
537 // disabled from Windows 8, we are safe to go.
538 return GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi)
539 + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
540}
541
542/*!
543 Calculates the dimensions of the invisible borders within the
544 window frames which only exist on Windows 10 and onwards.
545*/
546
548{
549 POINT pt = {screenPoint.x(), screenPoint.y()};
550 if (HMONITOR hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL)) {
551 UINT dpiX;
552 UINT dpiY;
553 if (SUCCEEDED(GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY))) {
554 const int gap = getResizeBorderThickness(dpiX);
555 return QMargins(gap, 0, gap, gap);
556 }
557 }
558 return QMargins();
559}
560
561[[nodiscard]] static inline QMargins invisibleMargins(const HWND hwnd)
562{
563 const UINT dpi = GetDpiForWindow(hwnd);
564 const int gap = getResizeBorderThickness(dpi);
565 return QMargins(gap, 0, gap, gap);
566}
567
568/*!
569 \class WindowCreationData
570 \brief Window creation code.
571
572 This struct gathers all information required to create a window.
573 Window creation is split in 3 steps:
574
575 \list
576 \li fromWindow() Gather all required information
577 \li create() Create the system handle.
578 \li initialize() Post creation initialization steps.
579 \endlist
580
581 The reason for this split is to also enable changing the QWindowFlags
582 by calling:
583
584 \list
585 \li fromWindow() Gather information and determine new system styles
586 \li applyWindowFlags() to apply the new window system styles.
587 \li initialize() Post creation initialization steps.
588 \endlist
589
590 Contains the window creation code formerly in qwidget_win.cpp.
591
592 \sa QWindowCreationContext
593 \internal
594*/
595
597{
599 enum Flags { ForceChild = 0x1, ForceTopLevel = 0x2 };
600
601 void fromWindow(const QWindow *w, const Qt::WindowFlags flags, unsigned creationFlags = 0);
602 inline WindowData create(const QWindow *w, const WindowData &data, QString title) const;
603 inline void applyWindowFlags(HWND hwnd) const;
604 void initialize(const QWindow *w, HWND h, bool frameChange, qreal opacityLevel) const;
605
609 unsigned style = 0;
610 unsigned exStyle = 0;
611 bool topLevel = false;
612 bool popup = false;
613 bool dialog = false;
614 bool tool = false;
615 bool embedded = false;
616 bool hasAlpha = false;
617};
618
619QDebug operator<<(QDebug debug, const WindowCreationData &d)
620{
621 QDebugStateSaver saver(debug);
622 debug.nospace();
623 debug.noquote();
624 debug << "WindowCreationData: " << d.flags
625 << "\n topLevel=" << d.topLevel;
626 if (d.parentHandle)
627 debug << " parent=" << d.parentHandle;
628 debug << " popup=" << d.popup << " dialog=" << d.dialog
629 << " embedded=" << d.embedded << " tool=" << d.tool
630 << "\n style=" << debugWinStyle(d.style);
631 if (d.exStyle)
632 debug << "\n exStyle=" << debugWinExStyle(d.exStyle);
633 return debug;
634}
635
636// Fix top level window flags in case only the type flags are passed.
637static inline void fixTopLevelWindowFlags(Qt::WindowFlags &flags)
638{
639 // Not supported on Windows, also do correction when it is set.
640 flags &= ~Qt::WindowFullscreenButtonHint;
641 // Qt::ExpandedClientAreaHint / Qt::NoTitleBarBackgroundHint customize the client
642 // area, not the decoration set, so ignore them when matching a bare window type.
643 // NOTE: keep exact equality otherwise - a loose testFlag(Qt::Window) check
644 // regressed Qt::CustomizeWindowHint (QTBUG-133940) and was reverted.
645 constexpr Qt::WindowFlags clientAreaHints =
646 Qt::ExpandedClientAreaHint | Qt::NoTitleBarBackgroundHint;
647 switch (flags & ~clientAreaHints) {
648 case Qt::Window:
649 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint
650 |Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint;
651 break;
652 case Qt::Dialog:
653 case Qt::Tool:
654 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
655 break;
656 default:
657 break;
658 }
659 if ((flags & Qt::WindowType_Mask) == Qt::SplashScreen)
660 flags |= Qt::FramelessWindowHint;
661}
662
663static QScreen *screenForDeviceName(const QWindow *w, const QString &name)
664{
665 const auto getDeviceName = [](const QScreen *screen) -> QString {
666 if (const auto s = static_cast<const QWindowsScreen *>(screen->handle()))
667 return s->data().deviceName;
668 return {};
669 };
670 QScreen *winScreen = w ? w->screen() : QGuiApplication::primaryScreen();
671 if (winScreen && getDeviceName(winScreen) != name) {
672 const auto screens = winScreen->virtualSiblings();
673 for (QScreen *screen : screens) {
674 if (getDeviceName(screen) == name)
675 return screen;
676 }
677 }
678 return winScreen;
679}
680
681static QPoint calcPosition(const QWindow *w, const QWindowCreationContextPtr &context, const QMargins &invMargins)
682{
683 const QPoint orgPos(context->frameX - invMargins.left(), context->frameY - invMargins.top());
684
685 if (!w || w->type() != Qt::Window)
686 return orgPos;
687
688 // Workaround for QTBUG-50371
689 const QScreen *screenForGL = QWindowsWindow::forcedScreenForGLWindow(w);
690 if (!screenForGL)
691 return orgPos;
692
693 const QPoint posFrame(context->frameX, context->frameY);
694 const QMargins margins = context->margins;
695 const QRect scrGeo = screenForGL->handle()->availableGeometry();
696
697 // Point is already in the required screen.
698 if (scrGeo.contains(orgPos))
699 return orgPos;
700
701 // If the visible part of the window is already in the
702 // required screen, just ignore the invisible offset.
703 if (scrGeo.contains(posFrame))
704 return posFrame;
705
706 // Find the original screen containing the coordinates.
707 const auto screens = screenForGL->virtualSiblings();
708 const QScreen *orgScreen = nullptr;
709 for (QScreen *screen : screens) {
710 if (screen->handle()->availableGeometry().contains(posFrame)) {
711 orgScreen = screen;
712 break;
713 }
714 }
715 const QPoint ctPos = QPoint(qMax(scrGeo.left(), scrGeo.center().x()
716 + (margins.right() - margins.left() - context->frameWidth)/2),
717 qMax(scrGeo.top(), scrGeo.center().y()
718 + (margins.bottom() - margins.top() - context->frameHeight)/2));
719
720 // If initial coordinates were outside all screens, center the window on the required screen.
721 if (!orgScreen)
722 return ctPos;
723
724 const QRect orgGeo = orgScreen->handle()->availableGeometry();
725 const QRect orgFrame(QPoint(context->frameX, context->frameY),
726 QSize(context->frameWidth, context->frameHeight));
727
728 // Window would be centered on orgScreen. Center it on the required screen.
729 if (orgGeo.center() == (orgFrame - margins).center())
730 return ctPos;
731
732 // Transform the coordinates to map them into the required screen.
733 const QPoint newPos(scrGeo.left() + ((posFrame.x() - orgGeo.left()) * scrGeo.width()) / orgGeo.width(),
734 scrGeo.top() + ((posFrame.y() - orgGeo.top()) * scrGeo.height()) / orgGeo.height());
735 const QPoint newPosNoMargin(newPos.x() - invMargins.left(), newPos.y() - invMargins.top());
736
737 return scrGeo.contains(newPosNoMargin) ? newPosNoMargin : newPos;
738}
739
740void WindowCreationData::fromWindow(const QWindow *w, const Qt::WindowFlags flagsIn,
741 unsigned creationFlags)
742{
743 flags = flagsIn;
744
745 // Sometimes QWindow doesn't have a QWindow parent but does have a native parent window,
746 // e.g. in case of embedded ActiveQt servers. They should not be considered a top-level
747 // windows in such cases.
748 QVariant prop = w->property(QWindowsWindow::embeddedNativeParentHandleProperty);
749 if (prop.isValid()) {
750 embedded = true;
751 parentHandle = reinterpret_cast<HWND>(prop.value<WId>());
752 }
753
754 if (creationFlags & ForceChild) {
755 topLevel = false;
756 } else if (embedded) {
757 // Embedded native windows (for example Active X server windows) are by
758 // definition never toplevel, even though they do not have QWindow parents.
759 topLevel = false;
760 } else {
761 topLevel = (creationFlags & ForceTopLevel) ? true : w->isTopLevel();
762 }
763
764 if (topLevel)
765 fixTopLevelWindowFlags(flags);
766
767 type = static_cast<Qt::WindowType>(int(flags) & Qt::WindowType_Mask);
768 switch (type) {
769 case Qt::Dialog:
770 case Qt::Sheet:
771 dialog = true;
772 break;
773 case Qt::Drawer:
774 case Qt::Tool:
775 tool = true;
776 break;
777 case Qt::Popup:
778 popup = true;
779 break;
780 default:
781 break;
782 }
783 if ((flags & Qt::MSWindowsFixedSizeDialogHint))
784 dialog = true;
785
786 // This causes the title bar to drawn RTL and the close button
787 // to be left. Note that this causes:
788 // - All DCs created on the Window to have RTL layout (see SetLayout)
789 // - ClientToScreen() and ScreenToClient() to work in reverse as well.
790 // - Mouse event coordinates to be mirrored.
791 // - Positioning of child Windows.
792 if (QGuiApplication::layoutDirection() == Qt::RightToLeft
793 && (QWindowsIntegration::instance()->options() & QWindowsIntegration::RtlEnabled) != 0) {
794 exStyle |= WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT;
795 }
796
797 // Parent: Use transient parent for top levels.
798 if (popup) {
799 flags |= Qt::WindowStaysOnTopHint; // a popup stays on top, no parent.
800 } else if (!embedded) {
801 if (const QWindow *parentWindow = topLevel ? w->transientParent() : w->parent())
802 parentHandle = QWindowsWindow::handleOf(parentWindow);
803 }
804
805 if (popup || (type == Qt::ToolTip) || (type == Qt::SplashScreen)) {
806 style = WS_POPUP;
807 } else if (topLevel) {
808 if (flags & Qt::FramelessWindowHint)
809 style = WS_POPUP; // no border
810 else if (flags & Qt::WindowTitleHint)
811 style = WS_OVERLAPPED;
812 else
813 style = 0;
814 } else {
815 style = WS_CHILD;
816 }
817
818 style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN ;
819
820 if (flags & Qt::WindowDoesNotAcceptFocus)
821 exStyle |= WS_EX_NOACTIVATE;
822
823 if (topLevel) {
824 if ((type == Qt::Window || dialog || tool)) {
825 if (!(flags & Qt::FramelessWindowHint)) {
826 style |= WS_POPUP;
827 if (flags & Qt::MSWindowsFixedSizeDialogHint) {
828 style |= WS_DLGFRAME;
829 } else {
830 style |= WS_THICKFRAME;
831 }
832 if (flags & Qt::WindowTitleHint)
833 style |= WS_CAPTION; // Contains WS_DLGFRAME
834 }
835 if (flags & Qt::WindowSystemMenuHint)
836 style |= WS_SYSMENU;
837 else if (dialog && (flags & Qt::WindowCloseButtonHint) && !(flags & Qt::FramelessWindowHint)) {
838 style |= WS_SYSMENU | WS_BORDER; // QTBUG-2027, dialogs without system menu.
839 exStyle |= WS_EX_DLGMODALFRAME;
840 }
841 const bool showMinimizeButton = flags & Qt::WindowMinimizeButtonHint;
842 if (showMinimizeButton)
843 style |= WS_MINIMIZEBOX;
844 const bool showMaximizeButton = shouldShowMaximizeButton(w, flags);
845 if (showMaximizeButton)
846 style |= WS_MAXIMIZEBOX;
847 if (showMinimizeButton || showMaximizeButton)
848 style |= WS_SYSMENU;
849 if (tool)
850 exStyle |= WS_EX_TOOLWINDOW;
851 if ((flags & Qt::WindowContextHelpButtonHint) && !showMinimizeButton
852 && !showMaximizeButton)
853 exStyle |= WS_EX_CONTEXTHELP;
854 } else {
855 exStyle |= WS_EX_TOOLWINDOW;
856 }
857
858 // make mouse events fall through this window
859 // NOTE: WS_EX_TRANSPARENT flag can make mouse inputs fall through a layered window
860 if (flagsIn & Qt::WindowTransparentForInput)
861 exStyle |= WS_EX_TRANSPARENT;
862
863 // Currently only compatible with D3D surfaces, use it with care.
864 if (qEnvironmentVariableIntValue("QT_QPA_DISABLE_REDIRECTION_SURFACE"))
865 exStyle |= WS_EX_NOREDIRECTIONBITMAP;
866 }
867}
868
869static inline bool shouldApplyDarkFrame(const QWindow *w)
870{
871 if (!w->isTopLevel() || w->flags().testFlag(Qt::FramelessWindowHint))
872 return false;
873
874 // the user of the application has explicitly opted out of dark frames
875 if (!QWindowsIntegration::instance()->darkModeHandling().testFlag(QWindowsApplication::DarkModeWindowFrames))
876 return false;
877
878 // if the application supports a dark border, and the palette is dark (window background color
879 // is darker than the text), then turn dark-border support on, otherwise use a light border.
880 auto *dWindow = QWindowPrivate::get(const_cast<QWindow*>(w));
881 const QPalette windowPal = dWindow->windowPalette();
882 return windowPal.color(QPalette::WindowText).lightness()
883 > windowPal.color(QPalette::Window).lightness();
884}
885
886static inline int getTitleBarHeight_sys(const UINT dpi)
887{
888 // According to MS design manual, it should be 32px when DPI is 96.
889 return getResizeBorderThickness(dpi) +
890 ::GetSystemMetricsForDpi(SM_CYCAPTION, dpi);
891}
892
894 WindowCreationData::create(const QWindow *w, const WindowData &data, QString title) const
895{
896 WindowData result;
897 result.flags = flags;
898
899 const auto appinst = reinterpret_cast<HINSTANCE>(GetModuleHandle(nullptr));
900
901 const QString windowClassName = QWindowsWindowClassRegistry::instance()->registerWindowClass(w);
902
903 QWindowsWindowClassDescription windowTitlebarDescription;
904 windowTitlebarDescription.name = "_q_titlebar"_L1;
905 windowTitlebarDescription.style = CS_VREDRAW | CS_HREDRAW;
906 windowTitlebarDescription.shouldAddPrefix = false;
907 const QString windowTitlebarName = QWindowsWindowClassRegistry::instance()->registerWindowClass(windowTitlebarDescription);
908
909 const QScreen *screen{};
910 const QRect rect = QPlatformWindow::initialGeometry(w, data.geometry,
911 defaultWindowWidth, defaultWindowHeight,
912 &screen);
913
914 if (title.isEmpty() && (result.flags & Qt::WindowTitleHint))
915 title = topLevel ? qAppName() : w->objectName();
916
917 const auto *titleUtf16 = reinterpret_cast<const wchar_t *>(title.utf16());
918 const auto *classNameUtf16 = reinterpret_cast<const wchar_t *>(windowClassName.utf16());
919 const auto *classTitleBarNameUtf16 = reinterpret_cast<const wchar_t *>(windowTitlebarName.utf16());
920
921 // Capture events before CreateWindowEx() returns. The context is cleared in
922 // the QWindowsWindow constructor.
923 const QWindowCreationContextPtr context(new QWindowCreationContext(w, screen, data.geometry,
924 rect, data.customMargins,
925 style, exStyle));
926 QWindowsContext::instance()->setWindowCreationContext(context);
927
928 const bool hasFrame = (style & (WS_DLGFRAME | WS_THICKFRAME))
929 && !(result.flags & Qt::FramelessWindowHint);
930 QMargins invMargins = topLevel && hasFrame && QWindowsGeometryHint::positionIncludesFrame(w)
931 ? invisibleMargins(QPoint(context->frameX, context->frameY)) : QMargins();
932
933 qCDebug(lcQpaWindow).nospace()
934 << "CreateWindowEx: " << w << " class=" << windowClassName << " title=" << title
935 << '\n' << *this << "\nrequested: " << rect << ": "
936 << context->frameWidth << 'x' << context->frameHeight
937 << '+' << context->frameX << '+' << context->frameY
938 << " custom margins: " << context->customMargins
939 << " invisible margins: " << invMargins;
940
941
942 QPoint pos = calcPosition(w, context, invMargins);
943
944 // Mirror the position when creating on a parent in RTL mode, ditto for the obtained geometry.
945 int mirrorParentWidth = 0;
946 if (!w->isTopLevel() && QWindowsBaseWindow::isRtlLayout(parentHandle)) {
947 RECT rect;
948 GetClientRect(parentHandle, &rect);
949 mirrorParentWidth = rect.right;
950 }
951 if (mirrorParentWidth != 0 && pos.x() != CW_USEDEFAULT && context->frameWidth != CW_USEDEFAULT)
952 pos.setX(mirrorParentWidth - context->frameWidth - pos.x());
953
954 result.hwnd = CreateWindowEx(exStyle, classNameUtf16, titleUtf16,
955 style,
956 pos.x(), pos.y(),
957 context->frameWidth, context->frameHeight,
958 parentHandle, nullptr, appinst, nullptr);
959
960 const UINT dpi = ::GetDpiForWindow(result.hwnd);
961 const int titleBarHeight = getTitleBarHeight_sys(dpi);
962 result.hwndTitlebar = CreateWindowEx(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE,
963 classTitleBarNameUtf16, classTitleBarNameUtf16,
964 0, 0, 0,
965 context->frameWidth, titleBarHeight,
966 nullptr, nullptr, appinst, nullptr);
967
968 qCDebug(lcQpaWindow).nospace()
969 << "CreateWindowEx: returns " << w << ' ' << result.hwnd << " obtained geometry: "
970 << context->obtainedPos << context->obtainedSize << ' ' << context->margins;
971
972 if (!result.hwnd) {
973 qErrnoWarning("%s: CreateWindowEx failed", __FUNCTION__);
974 return result;
975 }
976
977 if (QWindowsTheme::instance()->colorScheme() == Qt::ColorScheme::Dark && shouldApplyDarkFrame(w))
978 QWindowsWindow::setDarkBorderToWindow(result.hwnd, true);
979
980 if (mirrorParentWidth != 0) {
981 context->obtainedPos.setX(mirrorParentWidth - context->obtainedSize.width()
982 - context->obtainedPos.x());
983 }
984
985 QRect obtainedGeometry(context->obtainedPos, context->obtainedSize);
986
987 result.geometry = obtainedGeometry;
988 result.restoreGeometry = frameGeometry(result.hwnd, topLevel);
989 result.fullFrameMargins = context->margins;
990 result.embedded = embedded;
991 result.hasFrame = hasFrame;
992 result.customMargins = context->customMargins;
993
994 return result;
995}
996
998{
999 // Keep enabled and visible from the current style.
1000 const LONG_PTR oldStyle = GetWindowLongPtr(hwnd, GWL_STYLE);
1001 const LONG_PTR oldExStyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
1002
1003 const LONG_PTR newStyle = style | (oldStyle & (WS_DISABLED|WS_VISIBLE));
1004 if (oldStyle != newStyle)
1005 SetWindowLongPtr(hwnd, GWL_STYLE, newStyle);
1006 const LONG_PTR newExStyle = exStyle;
1007 if (newExStyle != oldExStyle)
1008 SetWindowLongPtr(hwnd, GWL_EXSTYLE, newExStyle);
1009 qCDebug(lcQpaWindow).nospace() << __FUNCTION__ << hwnd << *this
1010 << "\n Style from " << debugWinStyle(DWORD(oldStyle)) << "\n to "
1011 << debugWinStyle(DWORD(newStyle)) << "\n ExStyle from "
1012 << debugWinExStyle(DWORD(oldExStyle)) << " to "
1013 << debugWinExStyle(DWORD(newExStyle));
1014}
1015
1016void WindowCreationData::initialize(const QWindow *w, HWND hwnd, bool frameChange, qreal opacityLevel) const
1017{
1018 if (!hwnd)
1019 return;
1020 UINT swpFlags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER;
1021 if (frameChange)
1022 swpFlags |= SWP_FRAMECHANGED;
1023 if (topLevel) {
1024 swpFlags |= SWP_NOACTIVATE;
1025 if ((flags & Qt::WindowStaysOnTopHint) || (type == Qt::ToolTip)) {
1026 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, swpFlags);
1027 if (flags & Qt::WindowStaysOnBottomHint)
1028 qWarning("QWidget: Incompatible window flags: the window can't be on top and on bottom at the same time");
1029 } else if (flags & Qt::WindowStaysOnBottomHint) {
1030 SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, swpFlags);
1031 } else if (frameChange) { // Force WM_NCCALCSIZE with wParam=1 in case of custom margins.
1032 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, swpFlags);
1033 }
1034 if (flags & (Qt::CustomizeWindowHint|Qt::WindowTitleHint)) {
1035 HMENU systemMenu = GetSystemMenu(hwnd, FALSE);
1036 if (flags & Qt::WindowCloseButtonHint)
1037 EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_ENABLED);
1038 else
1039 EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_GRAYED);
1040 }
1041 if (flags & Qt::ExpandedClientAreaHint) { // Gives us the rounded corners looks and the frame shadow
1042 MARGINS margins = { -1, -1, -1, -1 };
1043 DwmExtendFrameIntoClientArea(hwnd, &margins);
1044 } else {
1045 MARGINS margins = { 0, 0, 0, 0 };
1046 DwmExtendFrameIntoClientArea(hwnd, &margins);
1047 }
1048 } else { // child.
1049 SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, swpFlags);
1050 }
1051
1052 const bool isAccelerated = windowIsAccelerated(w);
1053 const bool hasAlpha = w->format().hasAlpha();
1054 if (isAccelerated && hasAlpha)
1055 applyBlurBehindWindow(hwnd);
1056 setWindowOpacity(hwnd, flags, hasAlpha, isAccelerated, opacityLevel);
1057}
1058
1059
1060// Scaling helpers for size constraints.
1061static QSize toNativeSizeConstrained(QSize dip, const QScreen *s)
1062{
1063 if (QHighDpiScaling::isActive()) {
1064 const qreal factor = QHighDpiScaling::factor(s);
1065 if (!qFuzzyCompare(factor, qreal(1))) {
1066 if (dip.width() > 0 && dip.width() < QWINDOWSIZE_MAX)
1067 dip.setWidth(qRound(qreal(dip.width()) * factor));
1068 if (dip.height() > 0 && dip.height() < QWINDOWSIZE_MAX)
1069 dip.setHeight(qRound(qreal(dip.height()) * factor));
1070 }
1071 }
1072 return dip;
1073}
1074
1075// Helper for checking if frame adjustment needs to be skipped
1076// NOTE: Unmaximized frameless windows will skip margins calculation
1077static bool shouldOmitFrameAdjustment(const Qt::WindowFlags flags, DWORD style)
1078{
1079 return flags.testFlag(Qt::FramelessWindowHint) && !(style & WS_MAXIMIZE);
1080}
1081
1082// Helper for checking if frame adjustment needs to be skipped
1083// NOTE: Unmaximized frameless windows will skip margins calculation
1084static bool shouldOmitFrameAdjustment(const Qt::WindowFlags flags, HWND hwnd)
1085{
1086 DWORD style = hwnd != nullptr ? DWORD(GetWindowLongPtr(hwnd, GWL_STYLE)) : 0;
1087 return flags.testFlag(Qt::FramelessWindowHint) && !(style & WS_MAXIMIZE);
1088}
1089
1090/*!
1091 \class QWindowsGeometryHint
1092 \brief Stores geometry constraints and provides utility functions.
1093
1094 Geometry constraints ready to apply to a MINMAXINFO taking frame
1095 into account.
1096
1097 \internal
1098*/
1099
1100QMargins QWindowsGeometryHint::frameOnPrimaryScreen(const QWindow *w, DWORD style, DWORD exStyle)
1101{
1102 if (!w->isTopLevel() || shouldOmitFrameAdjustment(w->flags(), style))
1103 return {};
1104 RECT rect = {0,0,0,0};
1105 style &= ~DWORD(WS_OVERLAPPED); // Not permitted, see docs.
1106 if (AdjustWindowRectEx(&rect, style, FALSE, exStyle) == FALSE)
1107 qErrnoWarning("%s: AdjustWindowRectEx failed", __FUNCTION__);
1108 const QMargins result(qAbs(rect.left), qAbs(rect.top),
1109 qAbs(rect.right), qAbs(rect.bottom));
1110 qCDebug(lcQpaWindow).nospace() << __FUNCTION__ << " style="
1111 << Qt::showbase << Qt::hex << style << " exStyle=" << exStyle << Qt::dec << Qt::noshowbase
1112 << ' ' << rect << ' ' << result;
1113 return result;
1114}
1115
1116QMargins QWindowsGeometryHint::frameOnPrimaryScreen(const QWindow *w, HWND hwnd)
1117{
1118 return frameOnPrimaryScreen(w, DWORD(GetWindowLongPtr(hwnd, GWL_STYLE)),
1119 DWORD(GetWindowLongPtr(hwnd, GWL_EXSTYLE)));
1120}
1121
1122QMargins QWindowsGeometryHint::frame(const QWindow *w, DWORD style, DWORD exStyle, qreal dpi)
1123{
1124 if (!w->isTopLevel() || shouldOmitFrameAdjustment(w->flags(), style))
1125 return {};
1126 RECT rect = {0,0,0,0};
1127 style &= ~DWORD(WS_OVERLAPPED); // Not permitted, see docs.
1128 if (AdjustWindowRectExForDpi(&rect, style, FALSE, exStyle, unsigned(qRound(dpi))) == FALSE) {
1129 qErrnoWarning("%s: AdjustWindowRectExForDpi failed", __FUNCTION__);
1130 }
1131 const QMargins result(qAbs(rect.left), qAbs(rect.top),
1132 qAbs(rect.right), qAbs(rect.bottom));
1133 qCDebug(lcQpaWindow).nospace() << __FUNCTION__ << " style="
1134 << Qt::showbase << Qt::hex << style << " exStyle=" << exStyle << Qt::dec << Qt::noshowbase
1135 << " dpi=" << dpi
1136 << ' ' << rect << ' ' << result;
1137 return result;
1138}
1139
1140QMargins QWindowsGeometryHint::frame(const QWindow *w, HWND hwnd, DWORD style, DWORD exStyle)
1141{
1142 if (!w->isTopLevel() || shouldOmitFrameAdjustment(w->flags(), style))
1143 return {};
1144 if (QWindowsScreenManager::isSingleScreen())
1145 return frameOnPrimaryScreen(w, style, exStyle);
1147 auto screen = screenManager.screenForHwnd(hwnd);
1148 if (!screen)
1149 screen = screenManager.screens().value(0);
1150 const auto dpi = screen ? screen->logicalDpi().first : qreal(96);
1151 return frame(w, style, exStyle, dpi);
1152}
1153
1154QMargins QWindowsGeometryHint::frame(const QWindow *w, HWND hwnd)
1155{
1156 return frame(w, hwnd, DWORD(GetWindowLongPtr(hwnd, GWL_STYLE)),
1157 DWORD(GetWindowLongPtr(hwnd, GWL_EXSTYLE)));
1158}
1159
1160// For newly created windows.
1161QMargins QWindowsGeometryHint::frame(const QWindow *w, const QRect &geometry,
1162 DWORD style, DWORD exStyle)
1163{
1164 if (!w->isTopLevel() || shouldOmitFrameAdjustment(w->flags(), style))
1165 return {};
1167 || !QWindowsContext::shouldHaveNonClientDpiScaling(w)) {
1168 return frameOnPrimaryScreen(w, style, exStyle);
1169 }
1170 qreal dpi = 96;
1172 auto screen = screenManager.screenAtDp(geometry.center());
1173 if (!screen)
1174 screen = screenManager.screens().value(0);
1175 if (screen)
1176 dpi = screen->logicalDpi().first;
1177 return QWindowsGeometryHint::frame(w, style, exStyle, dpi);
1178}
1179
1180bool QWindowsGeometryHint::handleCalculateSize(const QWindow *window, const QMargins &customMargins, const MSG &msg, LRESULT *result)
1181{
1182 // Prevent adding any border for frameless window
1183 if (msg.wParam && window->flags() & Qt::FramelessWindowHint) {
1184 *result = 0;
1185 return true;
1186 }
1187 const QWindowsWindow *platformWindow = QWindowsWindow::windowsWindowOf(window);
1188 // In case the platformwindow was not yet created, use the initial windowflags provided by the user.
1189 const bool clientAreaExpanded = platformWindow != nullptr ? platformWindow->isClientAreaExpanded() : window->flags() & Qt::ExpandedClientAreaHint;
1190 // Return 0 to remove the window's border
1191 if (msg.wParam && clientAreaExpanded) {
1192 // Prevent content from being cutoff by border for maximized, but not fullscreened windows.
1193 const bool maximized = IsZoomed(msg.hwnd) && window->visibility() != QWindow::FullScreen;
1194 auto *ncp = reinterpret_cast<NCCALCSIZE_PARAMS *>(msg.lParam);
1195 RECT *clientArea = &ncp->rgrc[0];
1196 const int border = getResizeBorderThickness(96);
1197 if (maximized)
1198 clientArea->top += border;
1199 clientArea->bottom -= border;
1200 clientArea->left += border;
1201 clientArea->right -= border;
1202 *result = 0;
1203 return true;
1204 }
1205 // NCCALCSIZE_PARAMS structure if wParam==TRUE
1206 if (!msg.wParam || customMargins.isNull())
1207 return false;
1208 *result = DefWindowProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
1209 auto *ncp = reinterpret_cast<NCCALCSIZE_PARAMS *>(msg.lParam);
1210 const RECT oldClientArea = ncp->rgrc[0];
1211 ncp->rgrc[0].left += customMargins.left();
1212 ncp->rgrc[0].top += customMargins.top();
1213 ncp->rgrc[0].right -= customMargins.right();
1214 ncp->rgrc[0].bottom -= customMargins.bottom();
1215 result = nullptr;
1216 qCDebug(lcQpaWindow).nospace() << __FUNCTION__ << oldClientArea << '+' << customMargins << "-->"
1217 << ncp->rgrc[0] << ' ' << ncp->rgrc[1] << ' ' << ncp->rgrc[2]
1218 << ' ' << ncp->lppos->cx << ',' << ncp->lppos->cy;
1219 return true;
1220}
1221
1222void QWindowsGeometryHint::frameSizeConstraints(const QWindow *w, const QScreen *screen,
1223 const QMargins &margins,
1224 QSize *minimumSize, QSize *maximumSize)
1225{
1226 *minimumSize = toNativeSizeConstrained(w->minimumSize(), screen);
1227 *maximumSize = toNativeSizeConstrained(w->maximumSize(), screen);
1228
1229 const int maximumWidth = qMax(maximumSize->width(), minimumSize->width());
1230 const int maximumHeight = qMax(maximumSize->height(), minimumSize->height());
1231 const int frameWidth = margins.left() + margins.right();
1232 const int frameHeight = margins.top() + margins.bottom();
1233
1234 if (minimumSize->width() > 0)
1235 minimumSize->rwidth() += frameWidth;
1236 if (minimumSize->height() > 0)
1237 minimumSize->rheight() += frameHeight;
1238 if (maximumWidth < QWINDOWSIZE_MAX)
1239 maximumSize->setWidth(maximumWidth + frameWidth);
1240 if (maximumHeight < QWINDOWSIZE_MAX)
1241 maximumSize->setHeight(maximumHeight + frameHeight);
1242}
1243
1244void QWindowsGeometryHint::applyToMinMaxInfo(const QWindow *w,
1245 const QScreen *screen,
1246 const QMargins &margins,
1247 MINMAXINFO *mmi)
1248{
1249 QSize minimumSize;
1250 QSize maximumSize;
1251 frameSizeConstraints(w, screen, margins, &minimumSize, &maximumSize);
1252 qCDebug(lcQpaWindow).nospace() << '>' << __FUNCTION__ << '<' << " min="
1253 << minimumSize.width() << ',' << minimumSize.height()
1254 << " max=" << maximumSize.width() << ',' << maximumSize.height()
1255 << " margins=" << margins
1256 << " in " << *mmi;
1257
1258 if (minimumSize.width() > 0)
1259 mmi->ptMinTrackSize.x = minimumSize.width();
1260 if (minimumSize.height() > 0)
1261 mmi->ptMinTrackSize.y = minimumSize.height();
1262
1263 if (maximumSize.width() < QWINDOWSIZE_MAX)
1264 mmi->ptMaxTrackSize.x = maximumSize.width();
1265 if (maximumSize.height() < QWINDOWSIZE_MAX)
1266 mmi->ptMaxTrackSize.y = maximumSize.height();
1267 qCDebug(lcQpaWindow).nospace() << '<' << __FUNCTION__ << " out " << *mmi;
1268}
1269
1270void QWindowsGeometryHint::applyToMinMaxInfo(const QWindow *w,
1271 const QMargins &margins,
1272 MINMAXINFO *mmi)
1273{
1274 applyToMinMaxInfo(w, w->screen(), margins, mmi);
1275}
1276
1277bool QWindowsGeometryHint::positionIncludesFrame(const QWindow *w)
1278{
1279 return qt_window_private(const_cast<QWindow *>(w))->positionPolicy
1280 == QWindowPrivate::WindowFrameInclusive;
1281}
1282
1283/*!
1284 \class QWindowsBaseWindow
1285 \brief Base class for QWindowsForeignWindow, QWindowsWindow
1286
1287 The class provides some _sys() getters for querying window
1288 data from a HWND and some _sys() setters.
1289
1290 Derived classes wrapping foreign windows may use them directly
1291 to calculate geometry, margins, etc.
1292
1293 Derived classes representing windows created by Qt may defer
1294 expensive calculations until change notifications are received.
1295
1296 \since 5.6
1297 \internal
1298*/
1299
1300bool QWindowsBaseWindow::isRtlLayout(HWND hwnd)
1301{
1302 return (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_LAYOUTRTL) != 0;
1303}
1304
1305QWindowsBaseWindow *QWindowsBaseWindow::baseWindowOf(const QWindow *w)
1306{
1307 if (w) {
1308 if (QPlatformWindow *pw = w->handle())
1309 return static_cast<QWindowsBaseWindow *>(pw);
1310 }
1311 return nullptr;
1312}
1313
1314HWND QWindowsBaseWindow::handleOf(const QWindow *w)
1315{
1316 const QWindowsBaseWindow *bw = QWindowsBaseWindow::baseWindowOf(w);
1317 return bw ? bw->handle() : HWND(nullptr);
1318}
1319
1321{
1322 const HWND parent = parentHwnd();
1323 return !parent || parent == GetDesktopWindow();
1324}
1325
1327{
1328 return frameGeometry(handle(), isTopLevel());
1329}
1330
1332{
1333 return frameGeometry_sys().marginsRemoved(fullFrameMargins());
1334}
1335
1337{
1338 return QWindowsGeometryHint::frame(window(), handle(), style(), exStyle());
1339}
1340
1343{
1344 ULONG touchFlags = 0;
1345 if (IsTouchWindow(handle(), &touchFlags) == FALSE)
1346 return {};
1347 TouchWindowTouchTypes result;
1348 if ((touchFlags & TWF_FINETOUCH) != 0)
1349 result.setFlag(TouchWindowTouchType::FineTouch);
1350 if ((touchFlags & TWF_WANTPALM) != 0)
1351 result.setFlag(TouchWindowTouchType::WantPalmTouch);
1352 return result;
1353}
1354
1355void QWindowsBaseWindow::hide_sys() // Normal hide, do not activate other windows.
1356{
1357 SetWindowPos(handle(), nullptr , 0, 0, 0, 0,
1358 SWP_HIDEWINDOW | SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
1359}
1360
1362{
1363 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window();
1364 const Qt::WindowType type = window()->type();
1365 if (type == Qt::Popup
1366 || type == Qt::SubWindow // Special case for QTBUG-63121: MDI subwindows with WindowStaysOnTopHint
1367 || !(window()->flags() & Qt::WindowStaysOnBottomHint)) {
1368 SetWindowPos(handle(), HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1369 }
1370}
1371
1373{
1374 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window();
1375 if (!(window()->flags() & Qt::WindowStaysOnTopHint))
1376 SetWindowPos(handle(), HWND_BOTTOM, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1377}
1378
1379void QWindowsBaseWindow::setWindowTitle_sys(const QString &title)
1380{
1381 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window() << title;
1382 SetWindowText(handle(), reinterpret_cast<const wchar_t *>(title.utf16()));
1383}
1384
1385QPoint QWindowsBaseWindow::mapToGlobal(const QPoint &pos) const
1386{
1387 return QWindowsGeometryHint::mapToGlobal(handle(), pos);
1388}
1389
1390QPoint QWindowsBaseWindow::mapFromGlobal(const QPoint &pos) const
1391{
1392 return QWindowsGeometryHint::mapFromGlobal(handle(), pos);
1393}
1394
1396{
1397 Q_UNIMPLEMENTED();
1398}
1399
1401{
1402 Q_UNIMPLEMENTED();
1403 return false;
1404}
1405
1407{
1408 return {};
1409}
1410
1412{
1413 Q_UNIMPLEMENTED();
1414}
1415
1417{
1418 switch (event->type()) {
1419 case QEvent::ChildWindowAdded:
1420 if (!(GetWindowLongPtr(handle(), GWL_STYLE) & WS_CLIPCHILDREN)) {
1421 auto *childWindowEvent = static_cast<QChildWindowEvent*>(event);
1422 qWarning() << childWindowEvent->child() << "added as child to"
1423 << window() << "which does not have WS_CLIPCHILDREN set."
1424 << "This will result in drawing artifacts!";
1425 }
1426 break;
1427 default:
1428 break;
1429 }
1430
1431 return QPlatformWindow::windowEvent(event);
1432}
1433
1434/*!
1435 \class QWindowsDesktopWindow
1436 \brief Window wrapping GetDesktopWindow not allowing any manipulation.
1437 \since 5.6
1438 \internal
1439*/
1440
1441/*!
1442 \class QWindowsForeignWindow
1443 \brief Window wrapping a foreign native window.
1444
1445 QWindowsForeignWindow stores a native HWND and implements getters for
1446 geometry, margins, etc. reparenting and geometry manipulation for use as a
1447 child window in Qt.
1448
1449 \since 5.6
1450 \internal
1451*/
1452
1453QWindowsForeignWindow::QWindowsForeignWindow(QWindow *window, HWND hwnd)
1454 : QWindowsBaseWindow(window)
1455 , m_hwnd(hwnd)
1456 , m_topLevelStyle(0)
1457{
1458 if (QPlatformWindow::parent())
1459 setParent(QPlatformWindow::parent());
1460}
1461
1463{
1464 if (QPlatformWindow::parent())
1465 setParent(nullptr);
1466}
1467
1468void QWindowsForeignWindow::setParent(const QPlatformWindow *newParentWindow)
1469{
1470 const bool wasTopLevel = isTopLevel_sys();
1471 const HWND newParent = newParentWindow ? reinterpret_cast<HWND>(newParentWindow->winId()) : HWND(nullptr);
1472 const bool isTopLevel = !newParent;
1473 const DWORD oldStyle = style();
1474
1475 qCDebug(lcQpaWindow) << __FUNCTION__ << window() << "newParent="
1476 << newParentWindow << newParent << "oldStyle=" << debugWinStyle(oldStyle);
1477
1478 auto updateWindowFlags = [&] {
1479 // Top level window flags need to be set/cleared manually.
1480 DWORD newStyle = oldStyle;
1481 if (isTopLevel) {
1482 newStyle = m_topLevelStyle;
1483 } else {
1484 m_topLevelStyle = oldStyle;
1485 newStyle &= ~(WS_OVERLAPPEDWINDOW | WS_POPUPWINDOW);
1486 newStyle |= WS_CHILD;
1487 }
1488 SetWindowLongPtr(m_hwnd, GWL_STYLE, newStyle);
1489 };
1490
1491 if (wasTopLevel && !isTopLevel) {
1492 // Becoming a child window requires the style
1493 // flags to be updated before reparenting.
1494 updateWindowFlags();
1495 }
1496
1497 SetParent(m_hwnd, newParent);
1498
1499 if (!wasTopLevel && isTopLevel) {
1500 // Becoming a top level window requires the style
1501 // flags to be updated after reparenting.
1502 updateWindowFlags();
1503 }
1504}
1505
1507{
1508 qCDebug(lcQpaWindow) << __FUNCTION__ << window() << visible;
1509 if (visible)
1510 ShowWindow(handle(), SW_SHOWNOACTIVATE);
1511 else
1512 hide_sys();
1513}
1514
1515/*!
1516 \class QWindowCreationContext
1517 \brief Active Context for creating windows.
1518
1519 There is a phase in window creation (WindowCreationData::create())
1520 in which events are sent before the system API CreateWindowEx() returns
1521 the handle. These cannot be handled by the platform window as the association
1522 of the unknown handle value to the window does not exist yet and as not
1523 to trigger recursive handle creation, etc.
1524
1525 In that phase, an instance of QWindowCreationContext is set on
1526 QWindowsContext.
1527
1528 QWindowCreationContext stores the information to answer the initial
1529 WM_GETMINMAXINFO and obtains the corrected size/position.
1530
1531 \sa WindowCreationData, QWindowsContext
1532 \internal
1533*/
1534
1535QWindowCreationContext::QWindowCreationContext(const QWindow *w, const QScreen *s,
1536 const QRect &geometryIn, const QRect &geometry,
1537 const QMargins &cm,
1538 DWORD style, DWORD exStyle) :
1539 window(w),
1540 screen(s),
1541 requestedGeometryIn(geometryIn),
1542 requestedGeometry(geometry),
1543 obtainedPos(geometryIn.topLeft()),
1544 obtainedSize(geometryIn.size()),
1545 margins(QWindowsGeometryHint::frame(w, geometry, style, exStyle))
1546{
1547 // Geometry of toplevels does not consider window frames.
1548 // TODO: No concept of WA_wasMoved yet that would indicate a
1549 // CW_USEDEFAULT unless set. For now, assume that 0,0 means 'default'
1550 // for toplevels.
1551
1552 if (!(w->flags() & Qt::FramelessWindowHint))
1553 customMargins = cm;
1554
1555 if (geometry.isValid()
1556 || !qt_window_private(const_cast<QWindow *>(w))->resizeAutomatic) {
1557 frameX = geometry.x();
1558 frameY = geometry.y();
1559 const QMargins effectiveMargins = margins + customMargins;
1560 frameWidth = effectiveMargins.left() + geometry.width() + effectiveMargins.right();
1561 frameHeight = effectiveMargins.top() + geometry.height() + effectiveMargins.bottom();
1562 if (QWindowsMenuBar::menuBarOf(w) != nullptr) {
1563 menuHeight = GetSystemMetrics(SM_CYMENU);
1564 frameHeight += menuHeight;
1565 }
1566 const bool isDefaultPosition = !frameX && !frameY && w->isTopLevel();
1567 if (!QWindowsGeometryHint::positionIncludesFrame(w) && !isDefaultPosition) {
1568 frameX -= effectiveMargins.left();
1569 frameY -= effectiveMargins.top();
1570 }
1571 }
1572
1573 qCDebug(lcQpaWindow).nospace()
1574 << __FUNCTION__ << ' ' << w << ' ' << geometry
1575 << " pos incl. frame=" << QWindowsGeometryHint::positionIncludesFrame(w)
1576 << " frame=" << frameWidth << 'x' << frameHeight << '+'
1577 << frameX << '+' << frameY
1578 << " margins=" << margins << " custom margins=" << customMargins;
1579}
1580
1581void QWindowCreationContext::applyToMinMaxInfo(MINMAXINFO *mmi) const
1582{
1583 QWindowsGeometryHint::applyToMinMaxInfo(window, screen, margins + customMargins, mmi);
1584}
1585
1586/*!
1587 \class QWindowsWindow
1588 \brief Raster or OpenGL Window.
1589
1590 \list
1591 \li Raster type: handleWmPaint() is implemented to
1592 to bitblt the image. The DC can be accessed
1593 via getDC/releaseDC, which has special handling
1594 when within a paint event (in that case, the DC obtained
1595 from BeginPaint() is returned).
1596
1597 \li Open GL: The first time QWindowsGLContext accesses
1598 the handle, it sets up the pixelformat on the DC
1599 which in turn sets it on the window (see flag
1600 PixelFormatInitialized).
1601 handleWmPaint() is empty (although required).
1602 \endlist
1603
1604 \internal
1605*/
1606
1607const char *QWindowsWindow::embeddedNativeParentHandleProperty = "_q_embedded_native_parent_handle";
1608const char *QWindowsWindow::hasBorderInFullScreenProperty = "_q_has_border_in_fullscreen";
1609bool QWindowsWindow::m_borderInFullScreenDefault = false;
1610bool QWindowsWindow::m_inSetgeometry = false;
1611
1612QWindowsWindow::QWindowsWindow(QWindow *aWindow, const QWindowsWindowData &data) :
1613 QWindowsBaseWindow(aWindow),
1614 m_data(data),
1615 m_cursor(new CursorHandle)
1616#if QT_CONFIG(vulkan)
1617 , m_vkSurface(VK_NULL_HANDLE)
1618#endif
1619{
1620 QWindowsContext::instance()->addWindow(m_data.hwnd, this);
1621
1622 if (aWindow->flags().testFlags(Qt::ExpandedClientAreaHint)) {
1623 SetParent(m_data.hwndTitlebar, m_data.hwnd);
1624 ShowWindow(m_data.hwndTitlebar, SW_SHOW);
1625 }
1626
1627 if (aWindow->surfaceType() == QWindow::Direct3DSurface)
1629#if QT_CONFIG(opengl)
1630 if (aWindow->surfaceType() == QWindow::OpenGLSurface)
1631 setFlag(OpenGLSurface);
1632#endif
1633#if QT_CONFIG(vulkan)
1634 if (aWindow->surfaceType() == QSurface::VulkanSurface)
1635 setFlag(VulkanSurface);
1636#endif
1637 updateDropSite(window()->isTopLevel());
1638
1639 // Register touch unless if the flags are already set by a hook
1640 // such as HCBT_CREATEWND
1641 if (!touchWindowTouchTypes_sys().has_value())
1643
1644#if QT_CONFIG(directmanipulation)
1645 // Direct Manipulation delivers touchpad gestures per window, and only to
1646 // windows which it has been activated for.
1647 if (auto *dm = QWindowsContext::instance()->directManipulation())
1648 dm->registerWindow(aWindow, m_data.hwnd);
1649#endif
1650
1651 const qreal opacity = qt_window_private(aWindow)->opacity;
1652 if (!qFuzzyCompare(opacity, qreal(1.0)))
1653 setOpacity(opacity);
1654
1655 setMask(QHighDpi::toNativeLocalRegion(window()->mask(), window()));
1656
1657 if (aWindow->isTopLevel())
1658 setWindowIcon(aWindow->icon());
1659 if (m_borderInFullScreenDefault || aWindow->property(hasBorderInFullScreenProperty).toBool())
1662}
1663
1665{
1666 if (m_vsyncServiceCallbackId != 0)
1667 QDxgiVSyncService::instance()->unregisterCallback(m_vsyncServiceCallbackId);
1669 QWindowsThemeCache::clearThemeCache(m_data.hwnd);
1671 UnregisterTouchWindow(m_data.hwnd);
1672#if QT_CONFIG(directmanipulation)
1673 if (auto *dm = QWindowsContext::instance()->directManipulation())
1674 dm->unregisterWindow(m_data.hwnd);
1675#endif
1676 destroyWindow();
1677 destroyIcon();
1678}
1679
1681{
1682 // Clear the creation context as the window can be found in QWindowsContext's map.
1683 QWindowCreationContextPtr creationContext =
1684 QWindowsContext::instance()->setWindowCreationContext(QWindowCreationContextPtr());
1685
1686 QWindow *w = window();
1687 setWindowState(w->windowStates());
1688
1689 // Trigger geometry change (unless it has a special state in which case setWindowState()
1690 // will send the message) and screen change signals of QWindow.
1691 const Qt::WindowState state = w->windowState();
1692 const QRect obtainedGeometry(creationContext->obtainedPos, creationContext->obtainedSize);
1693 QPlatformScreen *obtainedScreen = screenForGeometry(obtainedGeometry);
1694 if (obtainedScreen && screen() != obtainedScreen)
1695 QWindowSystemInterface::handleWindowScreenChanged<QWindowSystemInterface::SynchronousDelivery>(w, obtainedScreen->screen());
1696 if (state != Qt::WindowMaximized && state != Qt::WindowFullScreen
1697 && creationContext->requestedGeometryIn != obtainedGeometry) {
1698 QWindowSystemInterface::handleGeometryChange<QWindowSystemInterface::SynchronousDelivery>(w, obtainedGeometry);
1699 }
1700 QWindowsWindow::setSavedDpi(GetDpiForWindow(handle()));
1701}
1702
1704{
1705 return window()->requestedFormat();
1706}
1707
1708void QWindowsWindow::fireExpose(const QRegion &region, bool force)
1709{
1710 if (region.isEmpty() && !force)
1712 else
1714 QWindowSystemInterface::handleExposeEvent(window(), region);
1715}
1716
1717void QWindowsWindow::fireFullExpose(bool force)
1718{
1719 fireExpose(QRect(QPoint(0, 0), m_data.geometry.size()), force);
1720}
1721
1722void QWindowsWindow::destroyWindow()
1723{
1724 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window() << m_data.hwnd;
1725 if (m_data.hwnd) { // Stop event dispatching before Window is destroyed.
1727 // Clear any transient child relationships as Windows will otherwise destroy them (QTBUG-35499, QTBUG-36666)
1728 const auto tlw = QGuiApplication::topLevelWindows();
1729 for (QWindow *w : tlw) {
1730 if (w->transientParent() == window()) {
1731 if (QWindowsWindow *tw = QWindowsWindow::windowsWindowOf(w))
1732 tw->updateTransientParent();
1733 }
1734 }
1736 if (context->windowUnderMouse() == window())
1740 setDropSiteEnabled(false);
1741#if QT_CONFIG(vulkan)
1742 if (m_vkSurface) {
1743 QVulkanInstance *inst = window()->vulkanInstance();
1744 if (inst)
1745 static_cast<QWindowsVulkanInstance *>(inst->handle())->destroySurface(m_vkSurface);
1746 m_vkSurface = VK_NULL_HANDLE;
1747 }
1748#endif
1749#ifndef QT_NO_OPENGL
1750 if (m_surface) {
1752 staticOpenGLContext->destroyWindowSurface(m_surface);
1753 m_surface = nullptr;
1754 }
1755#endif
1756 DestroyWindow(m_data.hwndTitlebar);
1757 DestroyWindow(m_data.hwnd);
1758 context->removeWindow(m_data.hwnd);
1759 m_data.hwndTitlebar = nullptr;
1760 m_data.hwnd = nullptr;
1761 }
1762}
1763
1764void QWindowsWindow::updateDropSite(bool topLevel)
1765{
1766 bool enabled = false;
1767 bool parentIsEmbedded = false;
1768
1769 if (!topLevel) {
1770 // if the parent window is a foreign window wrapped via QWindow::fromWinId, we need to enable the drop site
1771 // on the first child window
1772 const QWindow *parent = window()->parent();
1773 if (parent && parent->handle() && parent->handle()->isForeignWindow())
1774 parentIsEmbedded = true;
1775 }
1776
1777 if (topLevel || parentIsEmbedded) {
1778 switch (window()->type()) {
1779 case Qt::Window:
1780 case Qt::Dialog:
1781 case Qt::Sheet:
1782 case Qt::Drawer:
1783 case Qt::Popup:
1784 case Qt::Tool:
1785 enabled = true;
1786 break;
1787 default:
1788 break;
1789 }
1790 }
1791 setDropSiteEnabled(enabled);
1792}
1793
1794void QWindowsWindow::setDropSiteEnabled(bool dropEnabled)
1795{
1796 if (isDropSiteEnabled() == dropEnabled)
1797 return;
1798 qCDebug(lcQpaMime) << __FUNCTION__ << window() << dropEnabled;
1799#if QT_CONFIG(clipboard) && QT_CONFIG(draganddrop)
1800 if (dropEnabled) {
1801 Q_ASSERT(m_data.hwnd);
1802 m_dropTarget = new QWindowsOleDropTarget(window());
1803 RegisterDragDrop(m_data.hwnd, m_dropTarget);
1804 CoLockObjectExternal(m_dropTarget, true, true);
1805 } else {
1806 CoLockObjectExternal(m_dropTarget, false, true);
1807 m_dropTarget->Release();
1808 RevokeDragDrop(m_data.hwnd);
1809 m_dropTarget = nullptr;
1810 }
1811#endif // QT_CONFIG(clipboard) && QT_CONFIG(draganddrop)
1812}
1813
1814bool QWindowsWindow::m_screenForGLInitialized = false;
1815
1817{
1818 m_screenForGLInitialized = false;
1819}
1820
1822{
1823 m_screenForGLInitialized = false;
1824}
1825
1826QScreen *QWindowsWindow::forcedScreenForGLWindow(const QWindow *w)
1827{
1828 static QString forceToScreen;
1829 if (!m_screenForGLInitialized) {
1830 forceToScreen = GpuDescription::detect().gpuSuitableScreen;
1831 m_screenForGLInitialized = true;
1832 }
1833 return forceToScreen.isEmpty() ? nullptr : screenForDeviceName(w, forceToScreen);
1834}
1835
1836// Returns topmost QWindowsWindow ancestor even if there are embedded windows in the chain.
1837// Returns this window if it is the topmost ancestor.
1838QWindow *QWindowsWindow::topLevelOf(QWindow *w)
1839{
1840 while (QWindow *parent = w->parent())
1841 w = parent;
1842
1843 if (const QPlatformWindow *handle = w->handle()) {
1844 const auto *ww = static_cast<const QWindowsWindow *>(handle);
1845 if (ww->isEmbedded()) {
1846 HWND parentHWND = GetAncestor(ww->handle(), GA_PARENT);
1847 const HWND desktopHwnd = GetDesktopWindow();
1849 while (parentHWND && parentHWND != desktopHwnd) {
1850 if (QWindowsWindow *ancestor = ctx->findPlatformWindow(parentHWND))
1851 return topLevelOf(ancestor->window());
1852 parentHWND = GetAncestor(parentHWND, GA_PARENT);
1853 }
1854 }
1855 }
1856 return w;
1857}
1858
1860 QWindowsWindowData::create(const QWindow *w,
1861 const QWindowsWindowData &parameters,
1862 const QString &title)
1863{
1864 WindowCreationData creationData;
1865 creationData.fromWindow(w, parameters.flags);
1866 QWindowsWindowData result = creationData.create(w, parameters, title);
1867 // Force WM_NCCALCSIZE (with wParam=1) via SWP_FRAMECHANGED for custom margin.
1868 creationData.initialize(w, result.hwnd, !parameters.customMargins.isNull(), 1);
1869 return result;
1870}
1871
1872void QWindowsWindow::setVisible(bool visible)
1873{
1874 const QWindow *win = window();
1875 qCDebug(lcQpaWindow) << __FUNCTION__ << this << win << m_data.hwnd << visible;
1876 if (m_data.hwnd) {
1877 if (visible) {
1878 show_sys();
1879
1880 // When the window is layered, we won't get WM_PAINT, and "we" are in control
1881 // over the rendering of the window
1882 // There is nobody waiting for this, so we don't need to flush afterwards.
1883 if (isLayered())
1884 fireFullExpose();
1885 // QTBUG-44928, QTBUG-7386: This is to resolve the problem where popups are
1886 // opened from the system tray and not being implicitly activated
1887
1888 if (win->type() == Qt::Popup && !win->parent() && !QGuiApplication::focusWindow())
1889 SetForegroundWindow(m_data.hwnd);
1890 } else {
1893 if (window()->flags() & Qt::Popup) // from QWidgetPrivate::hide_sys(), activate other
1894 ShowWindow(m_data.hwnd, SW_HIDE);
1895 else
1896 hide_sys();
1897#ifndef QT_NO_CURSOR
1898 // QTBUG-140455: After hiding a modal dialog, directly re-apply
1899 // the parent window's cursor via SetCursor(). This is needed
1900 // because hide_sys() uses SWP_NOACTIVATE which does not trigger
1901 // WM_SETCURSOR, and the normal changeCursor() path is blocked
1902 // by multiple optimizations (unchanged cursor shape/handle,
1903 // stale windowUnderMouse).
1904 if (win->isModal()) {
1905 if (QWindow *parent = win->transientParent()) {
1906 if (auto *pw = QWindowsWindow::windowsWindowOf(parent))
1907 pw->applyCursor();
1908 }
1909 }
1910#endif
1911 fireExpose(QRegion());
1912 }
1913 }
1914}
1915
1917{
1918 return m_data.hwnd && IsWindowVisible(m_data.hwnd);
1919}
1920
1922{
1923 // Check for native windows or children of the active native window.
1924 if (const HWND activeHwnd = GetForegroundWindow())
1925 if (m_data.hwnd == activeHwnd || IsChild(activeHwnd, m_data.hwnd))
1926 return true;
1927 return false;
1928}
1929
1930bool QWindowsWindow::isAncestorOf(const QPlatformWindow *child) const
1931{
1932 const auto *childWindow = static_cast<const QWindowsWindow *>(child);
1933 return IsChild(m_data.hwnd, childWindow->handle());
1934}
1935
1937{
1938 return m_data.embedded;
1939}
1940
1941QPoint QWindowsWindow::mapToGlobal(const QPoint &pos) const
1942{
1943 return m_data.hwnd ? QWindowsGeometryHint::mapToGlobal(m_data.hwnd, pos) : pos;
1944}
1945
1946QPoint QWindowsWindow::mapFromGlobal(const QPoint &pos) const
1947{
1948 return m_data.hwnd ? QWindowsGeometryHint::mapFromGlobal(m_data.hwnd, pos) : pos;
1949}
1950
1951// Update the transient parent for a toplevel window. The concept does not
1952// really exist on Windows, the relationship is set by passing a parent along with !WS_CHILD
1953// to window creation or by setting the parent using GWL_HWNDPARENT (as opposed to
1954// SetParent, which would make it a real child).
1955
1956void QWindowsWindow::updateTransientParent() const
1957{
1958 if (window()->type() == Qt::Popup)
1959 return; // QTBUG-34503, // a popup stays on top, no parent, see also WindowCreationData::fromWindow().
1960 // Update transient parent.
1961 const HWND oldTransientParent = GetWindow(m_data.hwnd, GW_OWNER);
1962 HWND newTransientParent = nullptr;
1963 if (const QWindow *tp = window()->transientParent()) {
1964 if (const QWindowsWindow *tw = QWindowsWindow::windowsWindowOf(tp)) {
1965 if (!tw->testFlag(WithinDestroy)) { // Prevent destruction by parent window (QTBUG-35499, QTBUG-36666)
1966 newTransientParent = tw->handle();
1967 }
1968 } else if (const QWindowsBaseWindow *tbw = QWindowsBaseWindow::baseWindowOf(tp)) {
1969 newTransientParent = tbw->handle();
1970 }
1971 }
1972
1973 // QTSOLBUG-71: When using the MFC/winmigrate solution, it is possible that a child
1974 // window is found, which can cause issues with modality. Loop up to top level.
1975 while (newTransientParent && (GetWindowLongPtr(newTransientParent, GWL_STYLE) & WS_CHILD) != 0)
1976 newTransientParent = GetParent(newTransientParent);
1977
1978 if (newTransientParent != oldTransientParent)
1979 SetWindowLongPtr(m_data.hwnd, GWL_HWNDPARENT, LONG_PTR(newTransientParent));
1980}
1981
1982static inline bool testShowWithoutActivating(const QWindow *window)
1983{
1984 // QWidget-attribute Qt::WA_ShowWithoutActivating .
1985 const QVariant showWithoutActivating = window->property("_q_showWithoutActivating");
1986 return showWithoutActivating.isValid() && showWithoutActivating.toBool();
1987}
1988
1989static void setMinimizedGeometry(HWND hwnd, const QRect &r)
1990{
1991 WINDOWPLACEMENT windowPlacement;
1992 windowPlacement.length = sizeof(WINDOWPLACEMENT);
1993 if (GetWindowPlacement(hwnd, &windowPlacement)) {
1994 windowPlacement.showCmd = SW_SHOWMINIMIZED;
1995 windowPlacement.rcNormalPosition = RECTfromQRect(r);
1996 SetWindowPlacement(hwnd, &windowPlacement);
1997 }
1998}
1999
2000static void setRestoreMaximizedFlag(HWND hwnd, bool set = true)
2001{
2002 // Let Windows know that we need to restore as maximized
2003 WINDOWPLACEMENT windowPlacement;
2004 windowPlacement.length = sizeof(WINDOWPLACEMENT);
2005 if (GetWindowPlacement(hwnd, &windowPlacement)) {
2006 if (set)
2007 windowPlacement.flags |= WPF_RESTORETOMAXIMIZED;
2008 else
2009 windowPlacement.flags &= ~WPF_RESTORETOMAXIMIZED;
2010 SetWindowPlacement(hwnd, &windowPlacement);
2011 }
2012}
2013
2014// partially from QWidgetPrivate::show_sys()
2015void QWindowsWindow::show_sys() const
2016{
2017 int sm = SW_SHOWNORMAL;
2018 bool fakedMaximize = false;
2019 bool restoreMaximize = false;
2020 const QWindow *w = window();
2021 const Qt::WindowFlags flags = w->flags();
2022 const Qt::WindowType type = w->type();
2023 if (w->isTopLevel()) {
2024 const Qt::WindowStates state = w->windowStates();
2025 if (state & Qt::WindowMinimized) {
2026 sm = SW_SHOWMINIMIZED;
2027 if (!isVisible())
2028 sm = SW_SHOWMINNOACTIVE;
2029 if (state & Qt::WindowMaximized)
2030 restoreMaximize = true;
2031 } else {
2032 updateTransientParent();
2033 if (state & Qt::WindowMaximized) {
2034 sm = SW_SHOWMAXIMIZED;
2035 // Windows will not behave correctly when we try to maximize a window which does not
2036 // have minimize nor maximize buttons in the window frame. Windows would then ignore
2037 // non-available geometry, and rather maximize the widget to the full screen, minus the
2038 // window frame (caption). So, we do a trick here, by adding a maximize button before
2039 // maximizing the widget, and then remove the maximize button afterwards.
2040 if (flags & Qt::WindowTitleHint &&
2041 !(flags & (Qt::WindowMinMaxButtonsHint | Qt::FramelessWindowHint))) {
2042 fakedMaximize = TRUE;
2043 setStyle(style() | WS_MAXIMIZEBOX);
2044 }
2045 } // Qt::WindowMaximized
2046 } // !Qt::WindowMinimized
2047 }
2048 if (type == Qt::Popup ||
2049 type == Qt::ToolTip ||
2050 type == Qt::Tool ||
2051 (flags & Qt::WindowDoesNotAcceptFocus) ||
2052 testShowWithoutActivating(w))
2053 sm = SW_SHOWNOACTIVATE;
2054
2055 if (w->windowStates() & Qt::WindowMaximized)
2056 setFlag(WithinMaximize); // QTBUG-8361
2057
2058 ShowWindow(m_data.hwnd, sm);
2059
2061
2062 if (fakedMaximize) {
2063 setStyle(style() & ~WS_MAXIMIZEBOX);
2064 SetWindowPos(m_data.hwnd, nullptr, 0, 0, 0, 0,
2065 SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER
2066 | SWP_FRAMECHANGED);
2067 }
2068 if (restoreMaximize)
2069 setRestoreMaximizedFlag(m_data.hwnd);
2070}
2071
2072void QWindowsWindow::setParent(const QPlatformWindow *newParent)
2073{
2074 qCDebug(lcQpaWindow) << __FUNCTION__ << window() << newParent;
2075
2076 if (m_data.hwnd)
2077 setParent_sys(newParent);
2078}
2079
2080void QWindowsWindow::setParent_sys(const QPlatformWindow *parent)
2081{
2082 // Use GetAncestor instead of GetParent, as GetParent can return owner window for toplevels
2083 HWND oldParentHWND = parentHwnd();
2084 HWND newParentHWND = nullptr;
2085 if (parent) {
2086 const auto *parentW = static_cast<const QWindowsWindow *>(parent);
2087 newParentHWND = parentW->handle();
2088
2089 }
2090
2091 // NULL handle means desktop window, which also has its proper handle -> disambiguate
2092 HWND desktopHwnd = GetDesktopWindow();
2093 if (oldParentHWND == desktopHwnd)
2094 oldParentHWND = nullptr;
2095 if (newParentHWND == desktopHwnd)
2096 newParentHWND = nullptr;
2097
2098 if (newParentHWND != oldParentHWND) {
2099 const bool wasTopLevel = oldParentHWND == nullptr;
2100 const bool isTopLevel = newParentHWND == nullptr;
2101
2103 SetParent(m_data.hwnd, newParentHWND);
2105
2106 // WS_CHILD/WS_POPUP must be manually set/cleared in addition
2107 // to dialog frames, etc (see SetParent() ) if the top level state changes.
2108 // Force toplevel state as QWindow::isTopLevel cannot be relied upon here.
2109 if (wasTopLevel != isTopLevel) {
2110 setDropSiteEnabled(false);
2111 m_data = setWindowFlags_sys(window()->flags(), unsigned(isTopLevel ? WindowCreationData::ForceTopLevel : WindowCreationData::ForceChild));
2112 // Update frame margins for the new top-level state.
2113 // Child windows have no frame/titlebar, so margins must be zero.
2114 // Top-level windows need frame margins recalculated.
2115 if (isTopLevel)
2117 else
2118 m_data.fullFrameMargins = {};
2119 setDarkBorder(QWindowsTheme::instance()->colorScheme() == Qt::ColorScheme::Dark);
2120 updateDropSite(isTopLevel);
2121 }
2122 }
2123}
2124
2126{
2127 fireExpose(QRegion());
2128}
2129
2131{
2132 const QWindow *w = window();
2133 if (windowIsAccelerated(w) && w->format().hasAlpha())
2134 applyBlurBehindWindow(handle());
2135}
2136
2138{
2139 return QHighDpiScaling::roundScaleFactor(qreal(dpi) / QWindowsScreen::baseDpi) /
2140 QHighDpiScaling::roundScaleFactor(qreal(savedDpi()) / QWindowsScreen::baseDpi);
2141}
2142
2143void QWindowsWindow::handleDpiScaledSize(WPARAM wParam, LPARAM lParam, LRESULT *result)
2144{
2145 // We want to keep QWindow's device independent size constant across the
2146 // DPI change. To accomplish this, scale QPlatformWindow's native size
2147 // by the change of DPI (e.g. 120 -> 144 = 1.2), also taking any scale
2148 // factor rounding into account. The win32 window size includes the margins;
2149 // add the margins for the new DPI to the window size.
2150 const UINT dpi = UINT(wParam);
2151 const qreal scale = dpiRelativeScale(dpi);
2152 const QMargins margins = fullFrameMargins();
2153 if (!(m_data.flags & Qt::FramelessWindowHint)) {
2154 // We need to update the custom margins to match the current DPI, because
2155 // we don't want our users manually hook into this message just to set a
2156 // new margin, but here we can't call setCustomMargins() directly, that
2157 // function will change the window geometry which conflicts with what we
2158 // are currently doing.
2159 m_data.customMargins *= scale;
2160 }
2161
2162 const QSize windowSize = (geometry().size() * scale).grownBy((margins * scale) + customMargins());
2163 SIZE *size = reinterpret_cast<SIZE *>(lParam);
2164 size->cx = windowSize.width();
2165 size->cy = windowSize.height();
2166 *result = true; // Inform Windows that we've set a size
2167}
2168
2169void QWindowsWindow::handleDpiChanged(HWND hwnd, WPARAM wParam, LPARAM lParam)
2170{
2171 const UINT dpi = HIWORD(wParam);
2172 const qreal scale = dpiRelativeScale(dpi);
2173 setSavedDpi(dpi);
2174
2175 QWindowsThemeCache::clearThemeCache(hwnd);
2176
2177 // QTBUG-148525: The icons are created for a specific DPI, so they have to
2178 // be recreated for the DPI of the monitor the window has been moved to.
2179 if (isTopLevel() && !window()->icon().isNull())
2180 setWindowIcon(window()->icon());
2181
2182 // Send screen change first, so that the new screen is set during any following resize
2183 const auto prcNewWindow = reinterpret_cast<const RECT *>(lParam);
2184 checkForScreenChanged(QWindowsWindow::FromDpiChange, !m_inSetgeometry ? prcNewWindow : nullptr);
2185
2186 if (!IsZoomed(hwnd))
2187 m_data.restoreGeometry.setSize(m_data.restoreGeometry.size() * scale);
2188
2189 // We get WM_DPICHANGED in one of two situations:
2190 //
2191 // 1. The DPI change is a "spontaneous" DPI change as a result of e.g.
2192 // the user dragging the window to a new screen. In this case Windows
2193 // first sends WM_GETDPISCALEDSIZE, where we set the new window size,
2194 // followed by this event where we apply the suggested window geometry
2195 // to the native window. This will make sure the window tracks the mouse
2196 // cursor during screen change, and also that the window size is scaled
2197 // according to the DPI change.
2198 //
2199 // 2. The DPI change is a result of a setGeometry() call. In this case
2200 // Qt has already scaled the window size for the new DPI. Further, Windows
2201 // does not call WM_GETDPISCALEDSIZE, and also applies its own scaling
2202 // to the already scaled window size. Since there is no need to set the
2203 // window geometry again, and the provided geometry is incorrect, we omit
2204 // making the SetWindowPos() call.
2205 if (!m_inSetgeometry) {
2206 // Forces the system to recalculate the window size, which would further
2207 // help in using correct min/max limit as set through application. It
2208 // also internally handle setting the correct frame margins.
2209 QWindowsContext::forceNcCalcSize(hwnd);
2210 SetWindowPos(hwnd, nullptr, prcNewWindow->left, prcNewWindow->top,
2211 prcNewWindow->right - prcNewWindow->left,
2212 prcNewWindow->bottom - prcNewWindow->top, SWP_NOZORDER | SWP_NOACTIVATE);
2213 // If the window does not have a frame, WM_MOVE and WM_SIZE won't be
2214 // called which prevents the content from being scaled appropriately
2215 // after a DPI change.
2216 if (shouldOmitFrameAdjustment(m_data.flags, m_data.hwnd))
2217 handleGeometryChange();
2218 // Layered windows (e.g. with Qt::WA_TranslucentBackground set) do not
2219 // receive WM_PAINT and rely on explicit expose events to trigger
2220 // repaints via the backing store. After a DPI change, fire a full
2221 // expose to ensure the backing store is updated at the new resolution.
2222 if (isLayered())
2223 fireFullExpose();
2224 }
2225
2226 // Re-apply mask now that we have a new DPI, which have resulted in
2227 // a new scale factor.
2228 setMask(QHighDpi::toNativeLocalRegion(window()->mask(), window()));
2229}
2230
2232{
2233 const UINT dpi = GetDpiForWindow(hwnd);
2234 const qreal scale = dpiRelativeScale(dpi);
2235 setSavedDpi(dpi);
2236
2237 QWindowsThemeCache::clearThemeCache(hwnd);
2238
2239 checkForScreenChanged(QWindowsWindow::FromDpiChange);
2240
2241 // Child windows do not get WM_GETDPISCALEDSIZE messages to inform
2242 // Windows about the new size, so we need to manually scale them.
2243 QRect currentGeometry = geometry();
2244 QRect scaledGeometry = QRect(currentGeometry.topLeft() * scale, currentGeometry.size() * scale);
2245 setGeometry(scaledGeometry);
2246}
2247
2249{
2250 WINDOWPLACEMENT wp;
2251 wp.length = sizeof(WINDOWPLACEMENT);
2252 if (GetWindowPlacement(hwnd, &wp)) {
2253 const QRect result = qrectFromRECT(wp.rcNormalPosition);
2254 return result.translated(windowPlacementOffset(hwnd, result.topLeft()));
2255 }
2256 return QRect();
2257}
2258
2260{
2261 // Check for fake 'fullscreen' mode.
2262 const bool fakeFullScreen =
2263 m_savedFrameGeometry.isValid() && (window()->windowStates() & Qt::WindowFullScreen);
2264 const QRect frame = fakeFullScreen ? m_savedFrameGeometry : normalFrameGeometry(m_data.hwnd);
2265 const QMargins margins = fakeFullScreen
2266 ? QWindowsGeometryHint::frame(window(), handle(), m_savedStyle, 0)
2267 : fullFrameMargins();
2268 return frame.isValid() ? frame.marginsRemoved(margins) : frame;
2269}
2270
2272{
2273 if (m_data.flags.testFlags(Qt::ExpandedClientAreaHint)) {
2274 const int titleBarHeight = getTitleBarHeight_sys(96);
2275
2276 return QMargins(0, titleBarHeight, 0, 0);
2277 }
2278 return QMargins();
2279}
2280
2281static QString msgUnableToSetGeometry(const QWindowsWindow *platformWindow,
2282 const QRect &requestedRect,
2283 const QRect &obtainedRect,
2284 const QMargins &fullMargins,
2285 const QMargins &customMargins)
2286{
2287 QString result;
2288 QDebug debug(&result);
2289 debug.nospace();
2290 debug.noquote();
2291 const auto window = platformWindow->window();
2292 debug << "Unable to set geometry ";
2293 formatBriefRectangle(debug, requestedRect);
2294 debug << " (frame: ";
2295 formatBriefRectangle(debug, requestedRect + fullMargins);
2296 debug << ") on " << window->metaObject()->className() << "/\""
2297 << window->objectName() << "\" on \"" << window->screen()->name()
2298 << "\". Resulting geometry: ";
2299 formatBriefRectangle(debug, obtainedRect);
2300 debug << " (frame: ";
2301 formatBriefRectangle(debug, obtainedRect + fullMargins);
2302 debug << ") margins: ";
2303 formatBriefMargins(debug, fullMargins);
2304 if (!customMargins.isNull()) {
2305 debug << " custom margin: ";
2306 formatBriefMargins(debug, customMargins);
2307 }
2308 const auto minimumSize = window->minimumSize();
2309 const bool hasMinimumSize = !minimumSize.isEmpty();
2310 if (hasMinimumSize)
2311 debug << " minimum size: " << minimumSize.width() << 'x' << minimumSize.height();
2312 const auto maximumSize = window->maximumSize();
2313 const bool hasMaximumSize = maximumSize.width() != QWINDOWSIZE_MAX || maximumSize.height() != QWINDOWSIZE_MAX;
2314 if (hasMaximumSize)
2315 debug << " maximum size: " << maximumSize.width() << 'x' << maximumSize.height();
2316 if (hasMinimumSize || hasMaximumSize) {
2317 MINMAXINFO minmaxInfo;
2318 memset(&minmaxInfo, 0, sizeof(minmaxInfo));
2319 platformWindow->getSizeHints(&minmaxInfo);
2320 debug << ' ' << minmaxInfo;
2321 }
2322 debug << ')';
2323 return result;
2324}
2325
2326void QWindowsWindow::setGeometry(const QRect &rectIn)
2327{
2328 QScopedValueRollback b(m_inSetgeometry, true);
2329
2330 QRect rect = rectIn;
2331 // This means it is a call from QWindow::setFramePosition() and
2332 // the coordinates include the frame (size is still the contents rectangle).
2333 if (QWindowsGeometryHint::positionIncludesFrame(window())) {
2334 const QMargins margins = frameMargins();
2335 rect.moveTopLeft(rect.topLeft() + QPoint(margins.left(), margins.top()));
2336 }
2337 if (m_windowState & Qt::WindowMinimized)
2338 m_data.geometry = rect; // Otherwise set by handleGeometryChange() triggered by event.
2339 if (m_data.hwnd) {
2340 // A ResizeEvent with resulting geometry will be sent. If we cannot
2341 // achieve that size (for example, window title minimal constraint),
2342 // notify and warn.
2344 setGeometry_sys(rect);
2346 if (m_data.geometry != rect && (isVisible() || QLibraryInfo::isDebugBuild())) {
2347 const auto warning =
2348 msgUnableToSetGeometry(this, rectIn, m_data.geometry,
2349 fullFrameMargins(), customMargins());
2350 qWarning("%s: %s", __FUNCTION__, qPrintable(warning));
2351 }
2352 } else {
2353 QPlatformWindow::setGeometry(rect);
2354 }
2355}
2356
2358{
2359 // Minimize/Set parent can send nonsensical move events.
2360 if (!IsIconic(m_data.hwnd) && !testFlag(WithinSetParent))
2361 handleGeometryChange();
2362}
2363
2364void QWindowsWindow::handleResized(int wParam, LPARAM lParam)
2365{
2366 /* Prevents borderless windows from covering the taskbar when maximized. */
2367 if ((m_data.flags.testFlag(Qt::FramelessWindowHint)
2368 || (m_data.flags.testFlag(Qt::CustomizeWindowHint) && !m_data.flags.testFlag(Qt::WindowTitleHint)))
2369 && IsZoomed(m_data.hwnd)) {
2370 const int resizedWidth = LOWORD(lParam);
2371 const int resizedHeight = HIWORD(lParam);
2372
2373 const HMONITOR monitor = MonitorFromWindow(m_data.hwnd, MONITOR_DEFAULTTOPRIMARY);
2374 MONITORINFO monitorInfo = {};
2375 monitorInfo.cbSize = sizeof(MONITORINFO);
2376 GetMonitorInfoW(monitor, &monitorInfo);
2377
2378 int correctLeft = monitorInfo.rcMonitor.left;
2379 int correctTop = monitorInfo.rcMonitor.top;
2380 int correctWidth = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
2381 int correctHeight = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
2382
2383 if (!m_data.flags.testFlag(Qt::FramelessWindowHint)) {
2384 const int borderWidth = invisibleMargins(m_data.hwnd).left();
2385 correctLeft -= borderWidth;
2386 correctTop -= borderWidth;
2387 correctWidth += borderWidth * 2;
2388 correctHeight += borderWidth * 2;
2389 }
2390
2391 if (resizedWidth != correctWidth || resizedHeight != correctHeight) {
2392 qCDebug(lcQpaWindow) << __FUNCTION__ << "correcting: " << resizedWidth << "x"
2393 << resizedHeight << " -> " << correctWidth << "x" << correctHeight;
2394 SetWindowPos(m_data.hwnd, nullptr, correctLeft, correctTop, correctWidth, correctHeight,
2395 SWP_NOZORDER | SWP_NOACTIVATE);
2396 }
2397 }
2398
2399 switch (wParam) {
2400 case SIZE_MAXHIDE: // Some other window affected.
2401 case SIZE_MAXSHOW:
2402 return;
2403 case SIZE_MINIMIZED: // QTBUG-53577, prevent state change events during programmatic state change
2404 if (!testFlag(WithinSetStyle) && !testFlag(WithinSetGeometry))
2405 handleWindowStateChange(m_windowState | Qt::WindowMinimized);
2406 return;
2407 case SIZE_MAXIMIZED:
2408 handleGeometryChange();
2409 updateRestoreGeometry(); // we might be in ResizeMoveActive mode but changed the screen
2410 if (!testFlag(WithinSetStyle) && !testFlag(WithinSetGeometry))
2411 handleWindowStateChange(Qt::WindowMaximized | (isFullScreen_sys() ? Qt::WindowFullScreen
2412 : Qt::WindowNoState));
2413 break;
2414 case SIZE_RESTORED:
2415 handleGeometryChange();
2417 if (isFullScreen_sys())
2418 handleWindowStateChange(
2419 Qt::WindowFullScreen
2420 | (testFlag(MaximizeToFullScreen) ? Qt::WindowMaximized : Qt::WindowNoState));
2421 else if (m_windowState != Qt::WindowNoState && !testFlag(MaximizeToFullScreen))
2422 handleWindowStateChange(Qt::WindowNoState);
2423 }
2424 break;
2425 }
2426}
2427
2428static inline bool equalDpi(const QDpi &d1, const QDpi &d2)
2429{
2430 return qFuzzyCompare(d1.first, d2.first) && qFuzzyCompare(d1.second, d2.second);
2431}
2432
2433void QWindowsWindow::checkForScreenChanged(ScreenChangeMode mode, const RECT *suggestedRect)
2434{
2435 if ((parent() && !parent()->isForeignWindow()) || QWindowsScreenManager::isSingleScreen())
2436 return;
2437
2438 QPlatformScreen *currentScreen = screen();
2439 auto topLevel = isTopLevel_sys() ? m_data.hwnd : GetAncestor(m_data.hwnd, GA_ROOT);
2440 const QWindowsScreen *newScreen = suggestedRect ?
2441 QWindowsContext::instance()->screenManager().screenForRect(suggestedRect) :
2442 QWindowsContext::instance()->screenManager().screenForHwnd(topLevel);
2443
2444 if (newScreen == nullptr || newScreen == currentScreen)
2445 return;
2446 // For screens with different DPI: postpone until WM_DPICHANGE
2447 // Check on currentScreen as it can be 0 when resuming a session (QTBUG-80436).
2448 const bool changingDpi = !equalDpi(QDpi(savedDpi(), savedDpi()), newScreen->logicalDpi());
2449 if (mode == FromGeometryChange && currentScreen != nullptr && changingDpi)
2450 return;
2451
2452 qCDebug(lcQpaWindow).noquote().nospace() << __FUNCTION__
2453 << ' ' << window() << " \"" << (currentScreen ? currentScreen->name() : QString())
2454 << "\"->\"" << newScreen->name() << '"';
2456 QWindowSystemInterface::handleWindowScreenChanged<QWindowSystemInterface::SynchronousDelivery>(window(), newScreen->screen());
2457}
2458
2459void QWindowsWindow::handleGeometryChange()
2460{
2461 const QRect previousGeometry = m_data.geometry;
2463 m_data.geometry = geometry_sys();
2464 // Avoid superfluous geometry change events, possibly triggered by window
2465 // customization frameworks.
2466 if (m_data.geometry == previousGeometry)
2467 return;
2468 QWindowSystemInterface::handleGeometryChange(window(), m_data.geometry);
2469 // QTBUG-32121: OpenGL/normal windows (with exception of ANGLE
2470 // which we no longer support in Qt 6) do not receive expose
2471 // events when shrinking, synthesize.
2472 if (isExposed()
2473 && m_data.geometry.size() != previousGeometry.size() // Exclude plain move
2474 // One dimension grew -> Windows will send expose, no need to synthesize.
2475 && !(m_data.geometry.width() > previousGeometry.width() || m_data.geometry.height() > previousGeometry.height())) {
2476 fireFullExpose(true);
2477 }
2478
2479 const bool wasSync = testFlag(SynchronousGeometryChangeEvent);
2480 checkForScreenChanged();
2481
2482 if (testFlag(SynchronousGeometryChangeEvent))
2483 QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
2484
2487
2488 if (!wasSync)
2490 qCDebug(lcQpaEvents) << __FUNCTION__ << this << window() << m_data.geometry;
2491
2492 if (m_data.flags & Qt::ExpandedClientAreaHint) {
2493 const int titleBarHeight = getTitleBarHeight_sys(savedDpi());
2494 MoveWindow(m_data.hwndTitlebar, 0, 0, m_data.geometry.width(), titleBarHeight, true);
2495 }
2496}
2497
2498void QWindowsBaseWindow::setGeometry_sys(const QRect &rect) const
2499{
2500 const QMargins margins = fullFrameMargins();
2501 const QRect frameGeometry = rect + margins;
2502
2503 qCDebug(lcQpaWindow) << '>' << __FUNCTION__ << window()
2504 << "\n from " << geometry_sys() << " frame: "
2505 << margins << " to " <<rect
2506 << " new frame: " << frameGeometry;
2507
2508 bool result = false;
2509 const HWND hwnd = handle();
2510 WINDOWPLACEMENT windowPlacement;
2511 windowPlacement.length = sizeof(WINDOWPLACEMENT);
2512 GetWindowPlacement(hwnd, &windowPlacement);
2513 // If the window is hidden and in maximized state or minimized, instead of moving the
2514 // window, set the normal position of the window.
2515 if ((windowPlacement.showCmd == SW_MAXIMIZE && !IsWindowVisible(hwnd))
2516 || windowPlacement.showCmd == SW_SHOWMINIMIZED) {
2517 windowPlacement.rcNormalPosition =
2518 RECTfromQRect(frameGeometry.translated(-windowPlacementOffset(hwnd, frameGeometry.topLeft())));
2519 windowPlacement.showCmd = windowPlacement.showCmd == SW_SHOWMINIMIZED ? SW_SHOWMINIMIZED : SW_HIDE;
2520 result = SetWindowPlacement(hwnd, &windowPlacement);
2521 } else {
2522 int x = frameGeometry.x();
2523 if (!window()->isTopLevel()) {
2524 const HWND parentHandle = GetParent(hwnd);
2525 if (isRtlLayout(parentHandle)) {
2526 RECT rect;
2527 GetClientRect(parentHandle, &rect);
2528 x = rect.right - frameGeometry.width() - x;
2529 }
2530 }
2531 result = MoveWindow(hwnd, x, frameGeometry.y(),
2532 frameGeometry.width(), frameGeometry.height(), true);
2533 }
2534 qCDebug(lcQpaWindow) << '<' << __FUNCTION__ << window()
2535 << "\n resulting " << result << geometry_sys();
2536}
2537
2538/*!
2539 Allocates a HDC for the window or returns the temporary one
2540 obtained from WinAPI BeginPaint within a WM_PAINT event.
2541
2542 \sa releaseDC()
2543*/
2544
2546{
2547 if (!m_hdc) {
2548 m_hdc = GetDC(handle());
2549 if (QGuiApplication::layoutDirection() == Qt::RightToLeft)
2550 SetLayout(m_hdc, 0); // Clear RTL layout
2551 }
2552 return m_hdc;
2553}
2554
2555/*!
2556 Releases the HDC for the window or does nothing in
2557 case it was obtained from WinAPI BeginPaint within a WM_PAINT event.
2558
2559 \sa getDC()
2560*/
2561
2563{
2564 if (m_hdc) {
2565 ReleaseDC(handle(), m_hdc);
2566 m_hdc = nullptr;
2567 }
2568}
2569
2570static inline bool isSoftwareGl()
2571{
2572#if QT_CONFIG(dynamicgl)
2573 return QOpenGLStaticContext::opengl32.moduleIsNotOpengl32()
2574 && QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL;
2575#else
2576 return false;
2577#endif // dynamicgl
2578}
2579
2580bool QWindowsWindow::handleWmPaint(HWND hwnd, UINT message,
2581 WPARAM, LPARAM, LRESULT *result)
2582{
2583 if (message == WM_ERASEBKGND) { // Backing store - ignored.
2584 *result = 1;
2585 return true;
2586 }
2587 // QTBUG-75455: Suppress WM_PAINT sent to invisible windows when setting WS_EX_LAYERED
2588 if (!window()->isVisible() && (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0)
2589 return false;
2590 // Ignore invalid update bounding rectangles
2591 if (!GetUpdateRect(m_data.hwnd, 0, FALSE))
2592 return false;
2593 PAINTSTRUCT ps;
2594
2595 // GL software rendering (QTBUG-58178) with some AMD cards
2596 // (QTBUG-60527) need InvalidateRect() to suppress artifacts while resizing.
2598 InvalidateRect(hwnd, nullptr, false);
2599
2600 BeginPaint(hwnd, &ps);
2601
2602 // If the a window is obscured by another window (such as a child window)
2603 // we still need to send isExposed=true, for compatibility.
2604 // Our tests depend on it.
2605 fireExpose(QRegion(qrectFromRECT(ps.rcPaint)), true);
2606 if (!QWindowsContext::instance()->asyncExpose())
2607 QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
2608
2609 EndPaint(hwnd, &ps);
2610 return true;
2611}
2612
2613void QWindowsWindow::setWindowTitle(const QString &title)
2614{
2615 m_windowTitle = QWindowsWindow::formatWindowTitle(title);
2616 setWindowTitle_sys(m_windowTitle);
2617}
2618
2620{
2621 return m_windowTitle;
2622}
2623
2624void QWindowsWindow::setWindowFlags(Qt::WindowFlags flags)
2625{
2626 qCDebug(lcQpaWindow) << '>' << __FUNCTION__ << this << window() << "\n from: "
2627 << m_data.flags << "\n to: " << flags;
2628 const QRect oldGeometry = geometry();
2629 if (m_data.flags != flags) {
2630 m_data.flags = flags;
2631 if (m_data.hwnd) {
2632 m_data = setWindowFlags_sys(flags);
2633 updateDropSite(window()->isTopLevel());
2634 }
2635 }
2636 // When switching to a frameless window, geometry
2637 // may change without a WM_MOVE. Report change manually.
2638 // Do not send synchronously as not to clobber the widget
2639 // geometry in a sequence of setting flags and geometry.
2640 const QRect newGeometry = geometry_sys();
2641 if (oldGeometry != newGeometry)
2642 handleGeometryChange();
2643
2644 qCDebug(lcQpaWindow) << '<' << __FUNCTION__ << "\n returns: "
2645 << m_data.flags << " geometry " << oldGeometry << "->" << newGeometry;
2646}
2647
2648QWindowsWindowData QWindowsWindow::setWindowFlags_sys(Qt::WindowFlags wt,
2649 unsigned flags) const
2650{
2651 WindowCreationData creationData;
2652 creationData.fromWindow(window(), wt, flags);
2653 creationData.applyWindowFlags(m_data.hwnd);
2654 creationData.initialize(window(), m_data.hwnd, true, m_opacity);
2655
2656 if (creationData.flags.testFlag(Qt::ExpandedClientAreaHint)) {
2657 SetParent(m_data.hwndTitlebar, m_data.hwnd);
2658 ShowWindow(m_data.hwndTitlebar, SW_SHOW);
2659 } else {
2660 if (IsWindowVisible(m_data.hwndTitlebar)) {
2661 SetParent(m_data.hwndTitlebar, HWND_MESSAGE);
2662 ShowWindow(m_data.hwndTitlebar, SW_HIDE);
2663 }
2664 }
2665
2666 QWindowsWindowData result = m_data;
2667 result.flags = creationData.flags;
2668 result.embedded = creationData.embedded;
2669 result.hasFrame = (creationData.style & (WS_DLGFRAME | WS_THICKFRAME))
2670 && !(creationData.flags & Qt::FramelessWindowHint);
2671 return result;
2672}
2673
2674void QWindowsWindow::handleWindowStateChange(Qt::WindowStates state)
2675{
2676 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window()
2677 << "\n from " << m_windowState << " to " << state;
2678 m_windowState = state;
2679 QWindowSystemInterface::handleWindowStateChanged(window(), state);
2680 if (state & Qt::WindowMinimized) {
2682 QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents); // Tell QQuickWindow to stop rendering now.
2683 } else {
2685 if (state & Qt::WindowMaximized) {
2686 WINDOWPLACEMENT windowPlacement{};
2687 windowPlacement.length = sizeof(WINDOWPLACEMENT);
2688 GetWindowPlacement(m_data.hwnd, &windowPlacement);
2689 const RECT geometry = RECTfromQRect(m_data.restoreGeometry);
2690 windowPlacement.rcNormalPosition = geometry;
2691 correctWindowPlacement(windowPlacement);
2692
2693 // Even if the window is hidden, windowPlacement's showCmd is not SW_HIDE, so change it
2694 // manually to avoid unhiding a hidden window with the subsequent call to
2695 // SetWindowPlacement().
2696 if (!isVisible())
2697 windowPlacement.showCmd = SW_HIDE;
2698 SetWindowPlacement(m_data.hwnd, &windowPlacement);
2699 }
2700 // QTBUG-17548: We send expose events when receiving WM_Paint, but for
2701 // layered windows and transient children, we won't receive any WM_Paint.
2702 QWindow *w = window();
2703 bool exposeEventsSent = false;
2704 if (isLayered()) {
2705 fireFullExpose();
2706 exposeEventsSent = true;
2707 }
2708 const QWindowList allWindows = QGuiApplication::allWindows();
2709 for (QWindow *child : allWindows) {
2710 if (child != w && child->isVisible() && child->transientParent() == w) {
2711 QWindowsWindow *platformWindow = QWindowsWindow::windowsWindowOf(child);
2712 if (platformWindow && platformWindow->isLayered()) {
2713 platformWindow->fireFullExpose();
2714 exposeEventsSent = true;
2715 }
2716 }
2717 }
2718 if (exposeEventsSent && !QWindowsContext::instance()->asyncExpose())
2719 QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
2720 }
2721}
2722
2723// Apply corrections to window placement in Windows 10
2724// Related to task bar on top or left.
2725
2727{
2728 return window()->maximumHeight() != QWINDOWSIZE_MAX;
2729}
2730
2732{
2733 return window()->maximumWidth() != QWINDOWSIZE_MAX;
2734}
2735
2737{
2739}
2740
2741void QWindowsWindow::correctWindowPlacement(WINDOWPLACEMENT &windowPlacement)
2742{
2743 static const auto windows11 = QOperatingSystemVersion::Windows11_21H2;
2744 static const bool isWindows10 = QOperatingSystemVersion::current() < windows11;
2745 if (!isWindows10)
2746 return;
2747
2748 // Correct normal position by placement offset on Windows 10
2749 // (where task bar can be on any side of the screen)
2750 const QPoint offset = windowPlacementOffset(m_data.hwnd, m_data.restoreGeometry.topLeft());
2751 windowPlacement.rcNormalPosition = RECTfromQRect(m_data.restoreGeometry.translated(-offset));
2752 qCDebug(lcQpaWindow) << "Corrected normal position by" << -offset;
2753
2754 // A bug in windows 10 grows
2755 // - ptMaxPosition.x by the task bar's width, if it's on the left
2756 // - ptMaxPosition.y by the task bar's height, if it's on the top
2757 // each time GetWindowPlacement() is called.
2758 // The offset of the screen's left edge (as per frameMargins_sys().left()) is ignored.
2759 // => Check for windows 10 and correct.
2760 if (hasMaximumSize()) {
2761 const QMargins margins = frameMargins_sys();
2762 const QPoint topLeft = window()->screen()->geometry().topLeft();
2763 windowPlacement.ptMaxPosition = POINT{ topLeft.x() - margins.left(), topLeft.y() };
2764 qCDebug(lcQpaWindow) << "Window has maximum size. Corrected topLeft by"
2765 << -margins.left();
2766
2767 // If there is a placement offset correct width/height unless restricted,
2768 // in order to fit window onto the screen.
2769 if (offset.x() > 0 && !hasMaximumWidth()) {
2770 const int adjust = offset.x() / window()->devicePixelRatio();
2771 window()->setWidth(window()->width() - adjust);
2772 qCDebug(lcQpaWindow) << "Width shortened by" << adjust << "logical pixels.";
2773 }
2774 if (offset.y() > 0 && !hasMaximumHeight()) {
2775 const int adjust = offset.y() / window()->devicePixelRatio();
2776 window()->setHeight(window()->height() - adjust);
2777 qCDebug(lcQpaWindow) << "Height shortened by" << adjust << "logical pixels.";
2778 }
2779 }
2780}
2781
2783{
2784 m_data.restoreGeometry = normalFrameGeometry(m_data.hwnd);
2785}
2786
2787void QWindowsWindow::setWindowState(Qt::WindowStates state)
2788{
2789 if (m_data.hwnd) {
2790 setWindowState_sys(state);
2791 m_windowState = state;
2792 }
2793}
2794
2795bool QWindowsWindow::isFullScreen_sys() const
2796{
2797 const QWindow *w = window();
2798 if (!w->isTopLevel())
2799 return false;
2800 QRect geometry = geometry_sys();
2802 geometry += QMargins(1, 1, 1, 1);
2803 QPlatformScreen *screen = screenForGeometry(geometry);
2804 return screen && geometry == screen->geometry();
2805}
2806
2807/*!
2808 \brief Change the window state.
2809
2810 \note Window frames change when maximized;
2811 the top margin shrinks somewhat but that cannot be obtained using
2812 AdjustWindowRectEx().
2813
2814 \note Some calls to SetWindowLong require a subsequent call
2815 to ShowWindow.
2816*/
2817
2818void QWindowsWindow::setWindowState_sys(Qt::WindowStates newState)
2819{
2820 const Qt::WindowStates oldState = m_windowState;
2821 if (oldState == newState)
2822 return;
2823 qCDebug(lcQpaWindow) << '>' << __FUNCTION__ << this << window()
2824 << " from " << oldState << " to " << newState;
2825
2826 const bool visible = isVisible();
2827 auto stateChange = oldState ^ newState;
2828
2829 if (stateChange & Qt::WindowFullScreen) {
2830 if (newState & Qt::WindowFullScreen) {
2831 UINT newStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP;
2832 // Save geometry and style to be restored when fullscreen
2833 // is turned off again, since on Windows, it is not a real
2834 // Window state but emulated by changing geometry and style.
2835 if (!m_savedStyle) {
2836 m_savedStyle = style();
2837 if ((oldState & Qt::WindowMinimized) || (oldState & Qt::WindowMaximized)) {
2838 const QRect nf = normalFrameGeometry(m_data.hwnd);
2839 if (nf.isValid())
2840 m_savedFrameGeometry = nf;
2841 } else {
2842 m_savedFrameGeometry = frameGeometry_sys();
2843 }
2844 }
2845 if (newState & Qt::WindowMaximized)
2847 if (m_savedStyle & WS_SYSMENU)
2848 newStyle |= WS_SYSMENU;
2849 if (visible)
2850 newStyle |= WS_VISIBLE;
2852 newStyle |= WS_BORDER;
2853 setStyle(newStyle);
2854 const HMONITOR monitor = MonitorFromWindow(m_data.hwnd, MONITOR_DEFAULTTONEAREST);
2855 MONITORINFO monitorInfo = {};
2856 monitorInfo.cbSize = sizeof(MONITORINFO);
2857 GetMonitorInfoW(monitor, &monitorInfo);
2858 const QRect screenGeometry(monitorInfo.rcMonitor.left, monitorInfo.rcMonitor.top,
2859 monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left,
2860 monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top);
2861 if (newState & Qt::WindowMinimized) {
2862 setMinimizedGeometry(m_data.hwnd, screenGeometry);
2863 if (stateChange & Qt::WindowMaximized)
2864 setRestoreMaximizedFlag(m_data.hwnd, newState & Qt::WindowMaximized);
2865 } else {
2866 const UINT swpf = SWP_FRAMECHANGED | SWP_NOACTIVATE;
2867 const bool wasSync = testFlag(SynchronousGeometryChangeEvent);
2869 SetWindowPos(m_data.hwnd, HWND_TOP, screenGeometry.left(), screenGeometry.top(), screenGeometry.width(), screenGeometry.height(), swpf);
2870 if (!wasSync)
2873 QWindowSystemInterface::handleGeometryChange(window(), screenGeometry);
2874 QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents);
2875 }
2876 } else {
2877 // Restore saved state.
2878 unsigned newStyle = m_savedStyle ? m_savedStyle : style();
2879 if (visible)
2880 newStyle |= WS_VISIBLE;
2881 setStyle(newStyle);
2882
2883 const QScreen *screen = window()->screen();
2884 if (!screen)
2885 screen = QGuiApplication::primaryScreen();
2886 // That area of the virtual desktop might not be covered by a screen anymore.
2887 if (const auto platformScreen = screen->handle()) {
2888 if (!platformScreen->geometry().intersects(m_savedFrameGeometry))
2889 m_savedFrameGeometry.moveTo(platformScreen->geometry().topLeft());
2890 }
2891
2892 if (newState & Qt::WindowMinimized) {
2893 setMinimizedGeometry(m_data.hwnd, m_savedFrameGeometry);
2894 if (stateChange & Qt::WindowMaximized)
2895 setRestoreMaximizedFlag(m_data.hwnd, newState & Qt::WindowMaximized);
2896 } else {
2897 UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOACTIVATE;
2898 if (!m_savedFrameGeometry.isValid())
2899 swpf |= SWP_NOSIZE | SWP_NOMOVE;
2900 const bool wasSync = testFlag(SynchronousGeometryChangeEvent);
2902 // After maximized/fullscreen; the window can be in a maximized state. Clear
2903 // it before applying the normal geometry.
2904 if (windowVisibility_sys(m_data.hwnd) == QWindow::Maximized)
2905 ShowWindow(m_data.hwnd, SW_SHOWNOACTIVATE);
2906 SetWindowPos(m_data.hwnd, nullptr, m_savedFrameGeometry.x(), m_savedFrameGeometry.y(),
2907 m_savedFrameGeometry.width(), m_savedFrameGeometry.height(), swpf);
2908 if (!wasSync)
2910 // preserve maximized state
2911 if (visible) {
2913 ShowWindow(m_data.hwnd,
2914 (newState & Qt::WindowMaximized) ? SW_MAXIMIZE : SW_SHOWNA);
2916 }
2917 }
2918 m_savedStyle = 0;
2919 m_savedFrameGeometry = QRect();
2920 }
2921 } else if ((oldState & Qt::WindowMaximized) != (newState & Qt::WindowMaximized)) {
2922 if (visible && !(newState & Qt::WindowMinimized)) {
2924 if (newState & Qt::WindowFullScreen)
2926 ShowWindow(m_data.hwnd,
2927 (newState & Qt::WindowMaximized) ? SW_MAXIMIZE : SW_SHOWNOACTIVATE);
2930 } else if (visible && (oldState & newState & Qt::WindowMinimized)) {
2931 // change of the maximized state while keeping minimized
2932 setRestoreMaximizedFlag(m_data.hwnd, newState & Qt::WindowMaximized);
2933 }
2934 }
2935
2936 if (stateChange & Qt::WindowMinimized) {
2937 if (visible) {
2938 ShowWindow(m_data.hwnd,
2939 (newState & Qt::WindowMinimized) ? SW_MINIMIZE :
2940 (newState & Qt::WindowMaximized) ? SW_MAXIMIZE : SW_SHOWNORMAL);
2941 if ((newState & Qt::WindowMinimized) && (stateChange & Qt::WindowMaximized))
2942 setRestoreMaximizedFlag(m_data.hwnd, newState & Qt::WindowMaximized);
2943 }
2944 }
2945 qCDebug(lcQpaWindow) << '<' << __FUNCTION__ << this << window() << newState;
2946}
2947
2948void QWindowsWindow::setStyle(unsigned s) const
2949{
2950 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window() << debugWinStyle(s);
2952 SetWindowLongPtr(m_data.hwnd, GWL_STYLE, s);
2954}
2955
2956void QWindowsWindow::setExStyle(unsigned s) const
2957{
2958 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window() << debugWinExStyle(s);
2959 SetWindowLongPtr(m_data.hwnd, GWL_EXSTYLE, s);
2960}
2961
2962bool QWindowsWindow::windowEvent(QEvent *event)
2963{
2964 switch (event->type()) {
2965 case QEvent::ApplicationPaletteChange:
2966 setDarkBorder(QWindowsTheme::instance()->colorScheme() == Qt::ColorScheme::Dark);
2967 break;
2968 case QEvent::WindowBlocked: // Blocked by another modal window.
2969 setEnabled(false);
2972 ReleaseCapture();
2973 break;
2974 case QEvent::WindowUnblocked:
2975 setEnabled(true);
2977 break;
2978 default:
2979 break;
2980 }
2981
2982 return QWindowsBaseWindow::windowEvent(event);
2983}
2984
2986{
2987 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window();
2988}
2989
2990static bool isResize(const WINDOWPOS *windowPos)
2991{
2992 bool result = false;
2993 if ((windowPos->flags & SWP_NOSIZE) == 0) {
2994 RECT rect;
2995 GetWindowRect(windowPos->hwnd, &rect);
2996 result = rect.right - rect.left != windowPos->cx || rect.bottom - rect.top != windowPos->cy;
2997 }
2998 return result;
2999}
3000
3001bool QWindowsWindow::handleGeometryChangingMessage(MSG *message, const QWindow *qWindow, const QMargins &margins)
3002{
3003 auto *windowPos = reinterpret_cast<WINDOWPOS *>(message->lParam);
3004 const QRect suggestedFrameGeometry(windowPos->x, windowPos->y,
3005 windowPos->cx, windowPos->cy);
3006 const QRect suggestedGeometry = suggestedFrameGeometry - margins;
3007
3008 // Tell Windows to discard the entire contents of the client area, as re-using
3009 // parts of the client area would lead to jitter during resize.
3010 // Check the suggestedGeometry against the current one to only discard during
3011 // resize, and not a plain move. We also look for SWP_NOSIZE since that, too,
3012 // implies an identical size, and comparing QRects wouldn't work with null cx/cy
3013 if (isResize(windowPos))
3014 windowPos->flags |= SWP_NOCOPYBITS;
3015
3016 if ((windowPos->flags & SWP_NOZORDER) == 0) {
3017 if (QWindowsWindow *platformWindow = QWindowsWindow::windowsWindowOf(qWindow)) {
3018 QWindow *parentWindow = qWindow->parent();
3019 HWND parentHWND = GetAncestor(windowPos->hwnd, GA_PARENT);
3020 HWND desktopHWND = GetDesktopWindow();
3021 platformWindow->m_data.embedded = !parentWindow && parentHWND && (parentHWND != desktopHWND);
3022 }
3023 if (qWindow->flags().testFlag(Qt::WindowStaysOnBottomHint))
3024 windowPos->hwndInsertAfter = HWND_BOTTOM;
3025 }
3026 if (!qWindow->isTopLevel()) // Implement hasHeightForWidth().
3027 return false;
3028 if (windowPos->flags & SWP_NOSIZE)
3029 return false;
3030 const QRectF correctedGeometryF = QPlatformWindow::closestAcceptableGeometry(qWindow, suggestedGeometry);
3031 if (!correctedGeometryF.isValid())
3032 return false;
3033 const QRect correctedFrameGeometry = correctedGeometryF.toRect() + margins;
3034 if (correctedFrameGeometry == suggestedFrameGeometry)
3035 return false;
3036 windowPos->x = correctedFrameGeometry.left();
3037 windowPos->y = correctedFrameGeometry.top();
3038 windowPos->cx = correctedFrameGeometry.width();
3039 windowPos->cy = correctedFrameGeometry.height();
3040 return true;
3041}
3042
3044{
3045 const QMargins margins = window()->isTopLevel() ? fullFrameMargins() : QMargins();
3046 return QWindowsWindow::handleGeometryChangingMessage(message, window(), margins);
3047}
3048
3049void QWindowsWindow::setFullFrameMargins(const QMargins &newMargins)
3050{
3051 if (shouldOmitFrameAdjustment(m_data.flags, m_data.hwnd))
3052 return;
3053 if (m_data.fullFrameMargins != newMargins) {
3054 qCDebug(lcQpaWindow) << __FUNCTION__ << window() << m_data.fullFrameMargins << "->" << newMargins;
3055 m_data.fullFrameMargins = newMargins;
3056 }
3057}
3058
3060{
3061 // QTBUG-82580: If a native menu is present, force a WM_NCCALCSIZE.
3062 if (GetMenu(m_data.hwnd))
3063 QWindowsContext::forceNcCalcSize(m_data.hwnd);
3064 else
3065 calculateFullFrameMargins();
3066}
3067
3068void QWindowsWindow::calculateFullFrameMargins()
3069{
3070 if (shouldOmitFrameAdjustment(m_data.flags, m_data.hwnd))
3071 return;
3072
3073 // QTBUG-113736: systemMargins depends on AdjustWindowRectExForDpi. This doesn't take into
3074 // account possible external modifications to the titlebar, as with ExtendsContentIntoTitleBar()
3075 // from the Windows App SDK. We can fix this by comparing the WindowRect (which includes the
3076 // frame) to the ClientRect. If a 'typical' frame is detected, i.e. only the titlebar has been
3077 // modified, we can safely adjust the frame by deducting the bottom margin to the total Y
3078 // difference between the two rects, to get the actual size of the titlebar and prevent
3079 // unwanted client area slicing.
3080
3081 RECT windowRect{};
3082 RECT clientRect{};
3083 GetWindowRect(handle(), &windowRect);
3084 GetClientRect(handle(), &clientRect);
3085
3086 // QTBUG-117704 It is also possible that the user has manually removed the frame (for example
3087 // by handling WM_NCCALCSIZE). If that is the case, i.e., the client area and the window area
3088 // have identical sizes, we don't want to override the user-defined margins.
3089
3090 if (qSizeOfRect(windowRect) == qSizeOfRect(clientRect))
3091 return;
3092
3093 // Normally obtained from WM_NCCALCSIZE. This calculation only works
3094 // when no native menu is present.
3095 const auto systemMargins = testFlag(DisableNonClientScaling)
3096 ? QWindowsGeometryHint::frameOnPrimaryScreen(window(), m_data.hwnd)
3097 : frameMargins_sys();
3098 const int extendedClientAreaBorder = window()->flags().testFlag(Qt::ExpandedClientAreaHint) ? qRound(QHighDpiScaling::factor(window())) * 2 : 0;
3099 const QMargins actualMargins = systemMargins + customMargins() - extendedClientAreaBorder;
3100
3101 const int yDiff = (windowRect.bottom - windowRect.top) - (clientRect.bottom - clientRect.top);
3102 const bool typicalFrame = (actualMargins.left() == actualMargins.right())
3103 && (actualMargins.right() == actualMargins.bottom());
3104
3105 const QMargins adjustedMargins = typicalFrame ?
3106 QMargins(actualMargins.left(), (yDiff - actualMargins.bottom()),
3107 actualMargins.right(), actualMargins.bottom())
3108 : actualMargins;
3109
3110 setFullFrameMargins(adjustedMargins);
3111}
3112
3114{
3115 QMargins result = fullFrameMargins();
3116 if (isTopLevel() && m_data.hasFrame)
3117 result -= invisibleMargins(m_data.hwnd);
3118 return result;
3119}
3120
3122{
3123 if (shouldOmitFrameAdjustment(m_data.flags, m_data.hwnd))
3124 return {};
3125 return m_data.fullFrameMargins;
3126}
3127
3128void QWindowsWindow::setOpacity(qreal level)
3129{
3130 qCDebug(lcQpaWindow) << __FUNCTION__ << level;
3131 if (!qFuzzyCompare(m_opacity, level)) {
3132 m_opacity = level;
3133 if (m_data.hwnd)
3134 setWindowOpacity(m_data.hwnd, m_data.flags,
3136 level);
3137 }
3138}
3139
3140static inline HRGN createRectRegion(const QRect &r)
3141{
3142 return CreateRectRgn(r.left(), r.top(), r.x() + r.width(), r.y() + r.height());
3143}
3144
3145static inline void addRectToWinRegion(const QRect &rect, HRGN *winRegion)
3146{
3147 if (const HRGN rectRegion = createRectRegion(rect)) {
3148 HRGN result = CreateRectRgn(0, 0, 0, 0);
3149 if (CombineRgn(result, *winRegion, rectRegion, RGN_OR)) {
3150 DeleteObject(*winRegion);
3151 *winRegion = result;
3152 }
3153 DeleteObject(rectRegion);
3154 }
3155}
3156
3157static HRGN qRegionToWinRegion(const QRegion &region)
3158{
3159 auto it = region.begin();
3160 const auto end = region.end();
3161 if (it == end)
3162 return nullptr;
3163 HRGN hRegion = createRectRegion(*it);
3164 while (++it != end)
3165 addRectToWinRegion(*it, &hRegion);
3166 return hRegion;
3167}
3168
3169void QWindowsWindow::setMask(const QRegion &region)
3170{
3171 if (region.isEmpty()) {
3172 SetWindowRgn(m_data.hwnd, nullptr, true);
3173 return;
3174 }
3175 const HRGN winRegion = qRegionToWinRegion(region);
3176
3177 // Mask is in client area coordinates, so offset it in case we have a frame
3178 if (window()->isTopLevel()) {
3179 const QMargins margins = fullFrameMargins();
3180 OffsetRgn(winRegion, margins.left(), margins.top());
3181 }
3182
3183 // SetWindowRgn takes ownership.
3184 if (!SetWindowRgn(m_data.hwnd, winRegion, true))
3185 DeleteObject(winRegion);
3186}
3187
3189{
3190 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window();
3191
3192 if (!m_data.hwnd)
3193 return;
3194
3195 const auto activationBehavior = QWindowsIntegration::instance()->windowActivationBehavior();
3196 if (QGuiApplication::applicationState() == Qt::ApplicationActive
3197 || activationBehavior != QWindowsApplication::AlwaysActivateWindow) {
3198 SetForegroundWindow(m_data.hwnd);
3199 SetFocus(m_data.hwnd);
3200 return;
3201 }
3202
3203 // Force activate this window. The following code will bring the window to the
3204 // foreground and activate it. If the window is hidden, it will show up. If
3205 // the window is minimized, it will restore to the previous position.
3206
3207 // But first we need some sanity checks.
3208 if (m_data.flags & Qt::WindowStaysOnBottomHint) {
3209 qCWarning(lcQpaWindow) <<
3210 "Windows with Qt::WindowStaysOnBottomHint can't be brought to the foreground.";
3211 return;
3212 }
3213 if (m_data.flags & Qt::WindowStaysOnTopHint) {
3214 qCWarning(lcQpaWindow) <<
3215 "Windows with Qt::WindowStaysOnTopHint will always be on the foreground.";
3216 return;
3217 }
3218 if (window()->type() == Qt::ToolTip) {
3219 qCWarning(lcQpaWindow) << "ToolTip windows should not be activated.";
3220 return;
3221 }
3222
3223 // We need to show the window first, otherwise we won't be able to bring it to front.
3224 if (!IsWindowVisible(m_data.hwnd))
3225 ShowWindow(m_data.hwnd, SW_SHOW);
3226
3227 if (IsIconic(m_data.hwnd)) {
3228 ShowWindow(m_data.hwnd, SW_RESTORE);
3229 // When the window is restored, it will always become the foreground window.
3230 // So return early here, we don't need the following code to bring it to front.
3231 return;
3232 }
3233
3234 // OK, our window is not minimized, so now we will try to bring it to front manually.
3235 const HWND oldForegroundWindow = GetForegroundWindow();
3236 if (!oldForegroundWindow) { // There's no foreground window at all, just activate our window directly.
3237 // Already the foreground window, just need to be activated.
3238 SetActiveWindow(m_data.hwnd);
3239 // SetActiveWindow() doesn't transfer focus, we need to do it ourself.
3240 SetFocus(m_data.hwnd);
3241 return;
3242 }
3243
3244 // First try to send a message to the current foreground window to check whether
3245 // it is currently hanging or not.
3246 if (SendMessageTimeoutW(oldForegroundWindow, WM_NULL, 0, 0,
3247 SMTO_BLOCK | SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG, 1000, nullptr) == 0) {
3248 qCWarning(lcQpaWindow) << "The foreground window hangs, can't activate current window.";
3249 return;
3250 }
3251
3252 const DWORD windowThreadProcessId = GetWindowThreadProcessId(oldForegroundWindow, nullptr);
3253 const DWORD currentThreadId = GetCurrentThreadId();
3254
3255 AttachThreadInput(windowThreadProcessId, currentThreadId, TRUE);
3256 const auto cleanup = qScopeGuard([windowThreadProcessId, currentThreadId](){
3257 AttachThreadInput(windowThreadProcessId, currentThreadId, FALSE);
3258 });
3259
3260 BringWindowToTop(m_data.hwnd);
3261
3262 // Activate the window too. This will force us to the virtual desktop this
3263 // window is on, if it's on another virtual desktop.
3264 SetActiveWindow(m_data.hwnd);
3265 SetFocus(m_data.hwnd);
3266}
3267
3269{
3270 if (!m_data.hwnd) {
3271 qWarning("%s: No handle", __FUNCTION__);
3272 return false;
3273 }
3274 qCDebug(lcQpaWindow) << __FUNCTION__ << this << window() << grab;
3275
3277 if (grab) {
3278 context->setKeyGrabber(window());
3279 } else {
3280 if (context->keyGrabber() == window())
3281 context->setKeyGrabber(nullptr);
3282 }
3283 return true;
3284}
3285
3287{
3288 qCDebug(lcQpaWindow) << __FUNCTION__ << window() << grab;
3289 if (!m_data.hwnd) {
3290 qWarning("%s: No handle", __FUNCTION__);
3291 return false;
3292 }
3293 if (!isVisible() && grab) {
3294 qWarning("%s: Not setting mouse grab for invisible window %s/'%s'",
3295 __FUNCTION__, window()->metaObject()->className(),
3296 qPrintable(window()->objectName()));
3297 return false;
3298 }
3299 // release grab or an explicit grab overriding autocapture: Clear flag.
3301 if (hasMouseCapture() != grab) {
3302 if (grab) {
3303 SetCapture(m_data.hwnd);
3304 } else {
3305 ReleaseCapture();
3306 }
3307 }
3308 return grab;
3309}
3310
3311static inline DWORD edgesToWinOrientation(Qt::Edges edges)
3312{
3313 if (edges == Qt::LeftEdge)
3314 return 0xf001; // SC_SIZELEFT;
3315 else if (edges == (Qt::RightEdge))
3316 return 0xf002; // SC_SIZERIGHT
3317 else if (edges == (Qt::TopEdge))
3318 return 0xf003; // SC_SIZETOP
3319 else if (edges == (Qt::TopEdge | Qt::LeftEdge))
3320 return 0xf004; // SC_SIZETOPLEFT
3321 else if (edges == (Qt::TopEdge | Qt::RightEdge))
3322 return 0xf005; // SC_SIZETOPRIGHT
3323 else if (edges == (Qt::BottomEdge))
3324 return 0xf006; // SC_SIZEBOTTOM
3325 else if (edges == (Qt::BottomEdge | Qt::LeftEdge))
3326 return 0xf007; // SC_SIZEBOTTOMLEFT
3327 else if (edges == (Qt::BottomEdge | Qt::RightEdge))
3328 return 0xf008; // SC_SIZEBOTTOMRIGHT
3329
3330 return 0xf000; // SC_SIZE
3331}
3332
3333bool QWindowsWindow::startSystemResize(Qt::Edges edges)
3334{
3335 if (Q_UNLIKELY(window()->flags().testFlag(Qt::MSWindowsFixedSizeDialogHint)))
3336 return false;
3337
3338 ReleaseCapture();
3339 PostMessage(m_data.hwnd, WM_SYSCOMMAND, edgesToWinOrientation(edges), 0);
3341 return true;
3342}
3343
3345{
3346 ReleaseCapture();
3347 PostMessage(m_data.hwnd, WM_SYSCOMMAND, 0xF012 /*SC_DRAGMOVE*/, 0);
3348 return true;
3349}
3350
3352{
3353 if (enabled) {
3355 } else {
3357 }
3358}
3359
3360void QWindowsWindow::getSizeHints(MINMAXINFO *mmi) const
3361{
3362 QWindowsGeometryHint::applyToMinMaxInfo(window(), fullFrameMargins(), mmi);
3363
3364 // A frameless (WS_POPUP) window maximizes to the full screen geometry
3365 // instead of the work area (QTBUG-129791). Constrain the maximize rect
3366 // here, unless the window is meant to fill the screen.
3367 if ((m_data.flags & Qt::FramelessWindowHint) && window()->isTopLevel()
3368 && !testFlag(MaximizeToFullScreen)) {
3369 const HMONITOR monitor = MonitorFromWindow(m_data.hwnd, MONITOR_DEFAULTTONEAREST);
3370 MONITORINFO monitorInfo = {};
3371 monitorInfo.cbSize = sizeof(MONITORINFO);
3372 GetMonitorInfoW(monitor, &monitorInfo);
3373 const RECT &work = monitorInfo.rcWork;
3374 const RECT &screen = monitorInfo.rcMonitor;
3375 // ptMaxPosition and ptMaxSize are relative to the monitor the window
3376 // maximizes on, which handles multi-monitor setups.
3377 mmi->ptMaxPosition.x = work.left - screen.left;
3378 mmi->ptMaxPosition.y = work.top - screen.top;
3379 mmi->ptMaxSize.x = work.right - work.left;
3380 mmi->ptMaxSize.y = work.bottom - work.top;
3381 }
3382 qCDebug(lcQpaWindow) << __FUNCTION__ << window() << *mmi;
3383}
3384
3385bool QWindowsWindow::handleNonClientHitTest(const QPoint &globalPos, LRESULT *result) const
3386{
3387 // QTBUG-32663, suppress resize cursor for fixed size windows.
3388 const QWindow *w = window();
3389 const QPoint localPos = w->mapFromGlobal(QHighDpi::fromNativePixels(globalPos, w));
3390 const QRect geom = geometry();
3391 static auto oldMouseButtonState = Qt::NoButton;
3392
3393 if (m_data.flags.testFlags(Qt::ExpandedClientAreaHint)) {
3394 bool isDefaultTitleBar = !w->flags().testFlag(Qt::CustomizeWindowHint);
3395 bool isCustomized = w->flags().testFlags(Qt::CustomizeWindowHint) && w->flags().testAnyFlags(Qt::WindowTitleHint|
3396 Qt::WindowMinimizeButtonHint|
3397 Qt::WindowMaximizeButtonHint|
3398 Qt::WindowCloseButtonHint);
3399 const int border = (IsZoomed(m_data.hwnd) || isFullScreen_sys()) ? 0 : getResizeBorderThickness(savedDpi());
3400 const int titleBarHeight = getTitleBarHeight_sys(savedDpi());
3401 const int titleButtonWidth = titleBarHeight * 1.5;
3402 const bool mouseButtonsSwapped = GetSystemMetrics(SM_SWAPBUTTON);
3403 auto mouseButtons = Qt::NoButton;
3404 if (mouseButtonsSwapped)
3405 mouseButtons = GetAsyncKeyState(VK_LBUTTON) != 0 ? Qt::RightButton : (GetAsyncKeyState(VK_RBUTTON) ? Qt::LeftButton : Qt::NoButton);
3406 else
3407 mouseButtons = GetAsyncKeyState(VK_LBUTTON) != 0 ? Qt::LeftButton : (GetAsyncKeyState(VK_RBUTTON) ? Qt::RightButton : Qt::NoButton);
3408
3409 *result = HTCLIENT;
3410 if (isCustomized || isDefaultTitleBar) {
3411 int buttons = 1;
3412
3413 if (globalPos.y() < geom.top() + titleBarHeight) {
3414 if (m_data.flags.testFlags(Qt::WindowCloseButtonHint) || isDefaultTitleBar) {
3415 if ((globalPos.x() > geom.right() - titleButtonWidth * buttons) && (globalPos.x() <= geom.right())) {
3416 if (mouseButtons == Qt::LeftButton)
3417 *result = HTCLOSE;
3418 }
3419 buttons++;
3420 } if (m_data.flags.testFlags(Qt::WindowMaximizeButtonHint) || isDefaultTitleBar) {
3421 if ((globalPos.x() > geom.right() - titleButtonWidth * buttons) && (globalPos.x() <= geom.right() - titleButtonWidth * (buttons-1))){
3422 if (mouseButtons == Qt::LeftButton) {
3423 if (IsZoomed(m_data.hwnd))
3424 *result = HTSIZE;
3425 else
3426 *result = HTMAXBUTTON;
3427 }
3428 }
3429 buttons++;
3430 } if (m_data.flags.testFlags(Qt::WindowMinimizeButtonHint) || isDefaultTitleBar) {
3431 if ((globalPos.x() > geom.right() - titleButtonWidth * buttons) && (globalPos.x() <= geom.right() - titleButtonWidth * (buttons-1))){
3432 if (mouseButtons == Qt::LeftButton)
3433 *result = HTMINBUTTON;
3434 }
3435 buttons++;
3436 } if ((isCustomized || isDefaultTitleBar) &&
3437 *result == HTCLIENT){
3438 QWindow* wnd = window();
3439 if (mouseButtons != oldMouseButtonState) {
3440 auto mouseEventType = mouseButtons == Qt::NoButton ? QEvent::MouseButtonRelease : QEvent::MouseButtonPress;
3441 auto mouseEventButtons = mouseEventType == QEvent::MouseButtonPress ? mouseButtons : oldMouseButtonState;
3442 bool accepted = QWindowSystemInterface::handleMouseEvent<QWindowSystemInterface::SynchronousDelivery>(wnd, QHighDpi::toNativeLocalPosition(localPos, w), globalPos, mouseEventButtons, mouseEventButtons, mouseEventType);
3443 if (!accepted && mouseButtons == Qt::RightButton)
3444 *result = HTSYSMENU;
3445 else if (!accepted && globalPos.y() < geom.top() + titleBarHeight)
3446 *result = HTCAPTION;
3447 }
3448 }
3449 }
3450 } else if (w->flags().testFlag(Qt::CustomizeWindowHint)) {
3451
3452 QWindow* wnd = window();
3453 if (mouseButtons != oldMouseButtonState) {
3454 auto mouseEventType = mouseButtons == Qt::NoButton ? QEvent::MouseButtonRelease : QEvent::MouseButtonPress;
3455 auto mouseEventButtons = mouseEventType == QEvent::MouseButtonPress ? mouseButtons : oldMouseButtonState;
3456 bool accepted = QWindowSystemInterface::handleMouseEvent<QWindowSystemInterface::SynchronousDelivery>(wnd, QHighDpi::toNativeLocalPosition(localPos, w), globalPos, mouseEventButtons, mouseEventButtons, mouseEventType);
3457 if (!accepted && mouseButtons == Qt::RightButton)
3458 *result = HTSYSMENU;
3459 else if (!accepted && globalPos.y() < geom.top() + titleBarHeight)
3460 *result = HTCAPTION;
3461 }
3462 }
3463 oldMouseButtonState = mouseButtons;
3464
3465 if (border != 0) {
3466 const bool left = (globalPos.x() >= geom.left()) && (globalPos.x() < geom.left() + border);
3467 const bool right = (globalPos.x() > geom.right() - border) && (globalPos.x() <= geom.right());
3468 const bool top = (globalPos.y() >= geom.top()) && (globalPos.y() < geom.top() + border);
3469 const bool bottom = (globalPos.y() > geom.bottom() - border) && (globalPos.y() <= geom.bottom());
3470
3471 if (left || right || top || bottom) {
3472 if (left)
3473 *result = top ? HTTOPLEFT : (bottom ? HTBOTTOMLEFT : HTLEFT);
3474 else if (right)
3475 *result = top ? HTTOPRIGHT : (bottom ? HTBOTTOMRIGHT : HTRIGHT);
3476 else
3477 *result = top ? HTTOP : HTBOTTOM;
3478 }
3479 }
3480
3481 switch (*result) {
3482 case HTCLOSE:
3483 const_cast<QWindow *>(w)->close();
3484 break;
3485 case HTMAXBUTTON:
3486 const_cast<QWindow *>(w)->showMaximized();
3487 break;
3488 case HTMINBUTTON:
3489 const_cast<QWindow *>(w)->showMinimized();
3490 break;
3491 case HTSIZE:
3492 const_cast<QWindow *>(w)->showNormal();
3493 break;
3494 case HTSYSMENU: {
3495 HWND hwnd = reinterpret_cast<HWND>(w->winId());
3496 HMENU sysMenu = GetSystemMenu(hwnd, false);
3497 TrackPopupMenu(sysMenu, 0, globalPos.x(), globalPos.y(), 0, hwnd, nullptr);
3498 }
3499 default:
3500 break;
3501 }
3502 return true;
3503 }
3504
3505 // QTBUG-32663, suppress resize cursor for fixed size windows.
3506 if (m_data.flags & Qt::ExpandedClientAreaHint) {
3507 const int border = (IsZoomed(m_data.hwnd) || isFullScreen_sys()) ? 0 : getResizeBorderThickness(savedDpi());
3508 if (border == 0) {
3509 *result = HTCLIENT;
3510 return true;
3511 }
3512 const QRect rect = geom;
3513 const bool left = (globalPos.x() >= rect.left()) && (globalPos.x() < rect.left() + border);
3514 const bool right = (globalPos.x() > rect.right() - border) && (globalPos.x() <= rect.right());
3515 const bool top = (globalPos.y() >= rect.top()) && (globalPos.y() < rect.top() + border);
3516 const bool bottom = (globalPos.y() > rect.bottom() - border) && (globalPos.y() <= rect.bottom());
3517
3518
3519 if (left || right || top || bottom) {
3520 if (left)
3521 *result = top ? HTTOPLEFT : (bottom ? HTBOTTOMLEFT : HTLEFT);
3522 else if (right)
3523 *result = top ? HTTOPRIGHT : (bottom ? HTBOTTOMRIGHT : HTRIGHT);
3524 else
3525 *result = top ? HTTOP : HTBOTTOM;
3526 } else {
3527 *result = HTCLIENT;
3528 }
3529 return true;
3530 }
3531
3532 // QTBUG-32663, suppress resize cursor for fixed size windows.
3533 if (!w->isTopLevel() // Task 105852, minimized windows need to respond to user input.
3534 || (m_windowState != Qt::WindowNoState)
3535 || !isActive()
3536 || (m_data.flags & Qt::FramelessWindowHint)) {
3537 return false;
3538 }
3539 const QSize minimumSize = w->minimumSize();
3540 if (minimumSize.isEmpty())
3541 return false;
3542 const QSize maximumSize = w->maximumSize();
3543 const bool fixedWidth = minimumSize.width() == maximumSize.width();
3544 const bool fixedHeight = minimumSize.height() == maximumSize.height();
3545 if (!fixedWidth && !fixedHeight)
3546 return false;
3547 const QSize size = w->size();
3548 if (fixedHeight) {
3549 if (localPos.y() >= size.height()) {
3550 *result = HTBORDER; // Unspecified border, no resize cursor.
3551 return true;
3552 }
3553 if (localPos.y() < 0) {
3554 const int topResizeBarPos = invisibleMargins(m_data.hwnd).left() - frameMargins().top();
3555 if (localPos.y() < topResizeBarPos) {
3556 *result = HTCAPTION; // Extend caption over top resize bar, let's user move the window.
3557 return true;
3558 }
3559 }
3560 }
3561 if (fixedWidth && (localPos.x() < 0 || localPos.x() >= size.width())) {
3562 *result = HTBORDER; // Unspecified border, no resize cursor.
3563 return true;
3564 }
3565 return false;
3566}
3567
3568bool QWindowsWindow::handleNonClientActivate(LRESULT *result) const
3569{
3570 // If this window is frameless we choose to consume the event,
3571 // since the default logic causes the window title to appear.
3572 // QTBUG-127116
3573 if (m_data.flags & Qt::FramelessWindowHint) {
3574 *result = true;
3575 return true;
3576 }
3577 return false;
3578}
3579
3581{
3582 HWND hwnd = m_data.hwndTitlebar;
3583 QWindow *wnd = window();
3584
3585 RECT windowRect;
3586 GetWindowRect(hwnd, &windowRect);
3587
3588 const int titleBarHeight = getTitleBarHeight_sys(savedDpi());
3589 const int titleButtonWidth = titleBarHeight * 1.5;
3590 const qreal factor = QHighDpiScaling::factor(wnd);
3591 const int windowWidth = windowRect.right - windowRect.left;
3592
3593 POINT localPos;
3594 GetCursorPos(&localPos);
3595 MapWindowPoints(HWND_DESKTOP, m_data.hwnd, &localPos, 1);
3596
3597 const bool isDarkmode = QWindowsIntegration::instance()->darkModeHandling().testFlags(QWindowsApplication::DarkModeWindowFrames) &&
3598 qApp->styleHints()->colorScheme() == Qt::ColorScheme::Dark;
3599 const bool isWindows11orAbove = QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows11;
3600
3601 const QBrush closeButtonBrush(QColor(0xC4, 0x2C, 0x1E, 255));
3602 const QBrush minMaxButtonBrush = QBrush(isDarkmode ? QColor(0xFF, 0xFF, 0xFF, 0x40) : QColor(0x00, 0x00, 0x00, 0x20));
3603 const QBrush titleBarBackgroundColor = QBrush(isDarkmode ? QColor(0x1F, 0x1F, 0x1F, 0xFF) : QColor(0xF3, 0xF3, 0xF3, 0xFF));
3604 const QPen textPen = QPen(isDarkmode ? QColor(0xFF, 0xFF, 0xFD, 0xFF) : QColor(0x00, 0x00, 0x00, 0xFF));
3605
3606 QImage image(windowWidth, titleBarHeight, QImage::Format_ARGB32);
3607 QPainter p(&image);
3608 p.setCompositionMode(QPainter::CompositionMode_Clear);
3609 p.fillRect(0, 0, windowWidth, titleBarHeight, Qt::transparent);
3610
3611 p.setCompositionMode(QPainter::CompositionMode_SourceOver);
3612
3613 p.setBrush(titleBarBackgroundColor);
3614 p.setPen(Qt::NoPen);
3615 if (!wnd->flags().testFlags(Qt::NoTitleBarBackgroundHint)) {
3616 QRect titleRect;
3617 titleRect.setWidth(windowWidth);
3618 titleRect.setHeight(titleBarHeight);
3619 p.drawRect(titleRect);
3620 }
3621
3622 if (wnd->flags().testFlags(Qt::WindowTitleHint | Qt::CustomizeWindowHint) || !wnd->flags().testFlag(Qt::CustomizeWindowHint)) {
3623 QRect titleRect;
3624 titleRect.setY(1);
3625 titleRect.setX(12);
3626 titleRect.setWidth(windowWidth);
3627 titleRect.setHeight(titleBarHeight);
3628
3629 titleRect.adjust(factor * 4, 0, 0, 0);
3630 QRect iconRect(titleRect.x(), titleRect.y() + factor * 8, factor * 16, factor * 16);
3631 if (wnd->icon().isNull()) {
3632 static QIcon defaultIcon;
3633 if (defaultIcon.isNull()) {
3634 const QImage defaultIconImage = QImage::fromHICON(LoadIcon(0, IDI_APPLICATION));
3635 defaultIcon = QIcon(QPixmap::fromImage(defaultIconImage));
3636 }
3637 defaultIcon.paint(&p, iconRect);
3638 } else {
3639 wnd->icon().paint(&p, iconRect);
3640 }
3641 titleRect.adjust(factor * 24, 0, 0, 0);
3642
3643 p.setPen(textPen);
3644 QFont titleFont = QWindowsIntegration::instance()->fontDatabase()->defaultFont();
3645 titleFont.setPointSize(factor * 9);
3646 titleFont.setWeight(QFont::Thin);
3647 titleFont.setHintingPreference(QFont::PreferFullHinting);
3648 p.setFont(titleFont);
3649 const QString title = wnd->title().isEmpty() ? qApp->applicationName() : wnd->title();
3650 p.drawText(titleRect, title, QTextOption(Qt::AlignVCenter));
3651 }
3652
3653 int buttons = 1;
3654 const QString assetFontName = isWindows11orAbove ? QStringLiteral("Segoe Fluent Icons") : QStringLiteral("Segoe MDL2 Assets");
3655 QFont assetFont = QFont(assetFontName, factor * 7);
3656 assetFont.setWeight(QFont::Thin);
3657 assetFont.setHintingPreference(QFont::PreferFullHinting);
3658 p.setFont(assetFont);
3659 p.setBrush(closeButtonBrush);
3660 p.setPen(Qt::NoPen);
3661 if (wnd->flags().testFlags(Qt::WindowCloseButtonHint | Qt::CustomizeWindowHint) || !wnd->flags().testFlag(Qt::CustomizeWindowHint)) {
3662 QRectF rect;
3663 rect.setY(1);
3664 rect.setX(windowWidth - titleButtonWidth * buttons);
3665 rect.setWidth(titleButtonWidth);
3666 rect.setHeight(titleBarHeight);
3667 if (localPos.x > (windowWidth - buttons * titleButtonWidth) &&
3668 localPos.x < (windowWidth - (buttons - 1) * titleButtonWidth) &&
3669 localPos.y > rect.y() && localPos.y < rect.y() + rect.height()) {
3670 p.drawRect(rect);
3671 const QPen closeButtonHoveredPen = QPen(QColor(0xFF, 0xFF, 0xFD, 0xFF));
3672 p.setPen(closeButtonHoveredPen);
3673 } else {
3674 p.setPen(textPen);
3675 }
3676 p.drawText(rect, QStringLiteral("\uE8BB"), QTextOption(Qt::AlignVCenter | Qt::AlignHCenter));
3677 buttons++;
3678 }
3679
3680 p.setBrush(minMaxButtonBrush);
3681 p.setPen(Qt::NoPen);
3682 if (wnd->flags().testFlags(Qt::WindowMaximizeButtonHint | Qt::CustomizeWindowHint) || !wnd->flags().testFlag(Qt::CustomizeWindowHint)) {
3683 QRectF rect;
3684 rect.setY(1);
3685 rect.setX(windowWidth - titleButtonWidth * buttons);
3686 rect.setWidth(titleButtonWidth);
3687 rect.setHeight(titleBarHeight);
3688 if (localPos.x > (windowWidth - buttons * titleButtonWidth) &&
3689 localPos.x < (windowWidth - (buttons - 1) * titleButtonWidth) &&
3690 localPos.y > rect.y() && localPos.y < rect.y() + rect.height()) {
3691 p.drawRect(rect);
3692 }
3693 p.setPen(textPen);
3694 // Show the restore glyph while maximized, the maximize glyph otherwise.
3695 const QString maximizeGlyph = IsZoomed(m_data.hwnd) ? QStringLiteral("\uE923") // ChromeRestore
3696 : QStringLiteral("\uE922"); // ChromeMaximize
3697 p.drawText(rect, maximizeGlyph, QTextOption(Qt::AlignVCenter | Qt::AlignHCenter));
3698 buttons++;
3699 }
3700
3701 p.setBrush(minMaxButtonBrush);
3702 p.setPen(Qt::NoPen);
3703 if (wnd->flags().testFlags(Qt::WindowMinimizeButtonHint | Qt::CustomizeWindowHint) || !wnd->flags().testFlag(Qt::CustomizeWindowHint)) {
3704 QRectF rect;
3705 rect.setY(1);
3706 rect.setX(windowWidth - titleButtonWidth * buttons);
3707 rect.setWidth(titleButtonWidth);
3708 rect.setHeight(titleBarHeight);
3709 if (localPos.x > (windowWidth - buttons * titleButtonWidth) &&
3710 localPos.x < (windowWidth - (buttons - 1) * titleButtonWidth) &&
3711 localPos.y > rect.y() && localPos.y < rect.y() + rect.height()) {
3712 p.drawRect(rect);
3713 }
3714 p.setPen(textPen);
3715 p.drawText(rect,QStringLiteral("\uE921"), QTextOption(Qt::AlignVCenter | Qt::AlignHCenter));
3716 buttons++;
3717 }
3718
3719 p.end();
3720
3721 HBITMAP bmp = image.toHBITMAP();
3722
3723 HDC hdc = GetDC(hwnd);
3724
3725 HDC memdc = CreateCompatibleDC(hdc);
3726 HGDIOBJ original = SelectObject(memdc, bmp);
3727
3728
3729 BLENDFUNCTION blend = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA};
3730 POINT ptLocation = { 0, 0 };
3731 SIZE szWnd = { windowWidth, titleBarHeight };
3732 POINT ptSrc = { 0, 0 };
3733 UpdateLayeredWindow(hwnd, hdc, &ptLocation, &szWnd, memdc, &ptSrc, 0, &blend, ULW_ALPHA);
3734 SelectObject(hdc, original);
3735
3736 DeleteObject(bmp);
3737 DeleteObject(memdc);
3738 ReleaseDC(hwnd,hdc);
3739}
3740
3741#ifndef QT_NO_CURSOR
3742// Return the default cursor (Arrow) from QWindowsCursor's cache.
3743static inline CursorHandlePtr defaultCursor(const QWindow *w)
3744{
3745 if (QScreen *screen = w->screen())
3746 if (const QPlatformScreen *platformScreen = screen->handle())
3747 if (QPlatformCursor *cursor = platformScreen->cursor())
3748 return static_cast<QWindowsCursor *>(cursor)->standardWindowCursor(Qt::ArrowCursor);
3749 return CursorHandlePtr(new CursorHandle(QWindowsCursor::createCursorFromShape(Qt::ArrowCursor)));
3750}
3751
3752// Check whether to apply a new cursor. Either the window in question is
3753// currently under mouse, or it is the parent of the window under mouse and
3754// there is no other window with an explicitly set cursor in-between.
3755static inline bool applyNewCursor(const QWindow *w)
3756{
3757 const QWindow *underMouse = QWindowsContext::instance()->windowUnderMouse();
3758 if (underMouse == w)
3759 return true;
3760 for (const QWindow *p = underMouse; p ; p = p->parent()) {
3761 if (p == w)
3762 return true;
3763 const QWindowsWindow *platformWindow = QWindowsWindow::windowsWindowOf(p);
3764 if (platformWindow && !platformWindow->cursor()->isNull())
3765 return false;
3766 }
3767 return false;
3768}
3769#endif // !QT_NO_CURSOR
3770
3771/*!
3772 \brief Applies to cursor property set on the window to the global cursor.
3773
3774 \sa QWindowsCursor
3775*/
3776
3778{
3780 if (isTopLevel())
3782 return;
3783 }
3784#ifndef QT_NO_CURSOR
3785 if (m_cursor->isNull()) { // Recurse up to parent with non-null cursor. Set default for toplevel.
3786 if (const QWindow *p = window()->parent()) {
3787 if (QWindowsWindow *platformWindow = QWindowsWindow::windowsWindowOf(p))
3788 platformWindow->applyCursor();
3789 } else {
3790 SetCursor(defaultCursor(window())->handle());
3791 }
3792 } else {
3793 SetCursor(m_cursor->handle());
3794 }
3795#endif
3796}
3797
3798void QWindowsWindow::setCursor(const CursorHandlePtr &c)
3799{
3800#ifndef QT_NO_CURSOR
3801 bool changed = c->handle() != m_cursor->handle();
3802 // QTBUG-98856: Cursors can get out of sync after restoring override
3803 // cursors on native windows. Force an update.
3806 changed = true;
3807 }
3808 if (changed) {
3809 const bool apply = applyNewCursor(window());
3810 qCDebug(lcQpaWindow) << window() << __FUNCTION__
3811 << c->handle() << " doApply=" << apply;
3812 m_cursor = c;
3813 if (apply)
3815 }
3816#endif
3817}
3818
3820{
3821 if (isAlertState() == enabled)
3822 return;
3823 if (enabled) {
3826 } else {
3829 }
3830}
3831
3832void QWindowsWindow::alertWindow(int durationMs)
3833{
3834 UINT timeOutMs = GetCaretBlinkTime();
3835 if (!timeOutMs || timeOutMs == INFINITE)
3836 timeOutMs = 250;
3837
3838 FLASHWINFO info;
3839 info.cbSize = sizeof(info);
3840 info.hwnd = m_data.hwnd;
3841 info.dwFlags = FLASHW_TRAY;
3842 info.dwTimeout = timeOutMs;
3843 info.uCount = durationMs == 0 ? 10 : UINT(durationMs) / timeOutMs;
3844 FlashWindowEx(&info);
3845}
3846
3848{
3849 FLASHWINFO info;
3850 info.cbSize = sizeof(info);
3851 info.hwnd = m_data.hwnd;
3852 info.dwFlags = FLASHW_STOP;
3853 info.dwTimeout = 0;
3854 info.uCount = 0;
3855 FlashWindowEx(&info);
3856}
3857
3859{
3860 return (style() & WS_DISABLED) == 0;
3861}
3862
3863void QWindowsWindow::setEnabled(bool enabled)
3864{
3865 const unsigned oldStyle = style();
3866 unsigned newStyle = oldStyle;
3867 if (enabled) {
3868 newStyle &= ~WS_DISABLED;
3869 } else {
3870 newStyle |= WS_DISABLED;
3871 }
3872 if (newStyle != oldStyle)
3873 setStyle(newStyle);
3874}
3875
3877{
3878 // The primary monitor is the one that has its origin at (0, 0).
3879 const POINT origin{0, 0};
3880 if (const HMONITOR monitor = MonitorFromPoint(origin, MONITOR_DEFAULTTOPRIMARY)) {
3881 UINT dpiX;
3882 UINT dpiY;
3883 if (SUCCEEDED(GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY)))
3884 return dpiX;
3885 }
3886 return GetDpiForSystem();
3887}
3888
3889static HICON createHIcon(const QIcon &icon, UINT dpi, int xSizeMetric, int ySizeMetric)
3890{
3891 if (!icon.isNull()) {
3892 // QTBUG-90363, QTBUG-148524: Deliver the icon in exactly the physical
3893 // size that is expected at the given DPI, so that it does not have to be
3894 // rescaled for display. GetSystemMetrics() must not be used, as it
3895 // reports metrics for the system (primary monitor) DPI only. Pass the
3896 // corresponding device pixel ratio rather than 1, so that QIcon can
3897 // pick a representation authored for fractional scale factors.
3898 const qreal dpr = qreal(dpi) / QWindowsScreen::baseDpi;
3899 const QSize physicalSize(GetSystemMetricsForDpi(xSizeMetric, dpi),
3900 GetSystemMetricsForDpi(ySizeMetric, dpi));
3901 const QPixmap pm = icon.pixmap(icon.actualSize(physicalSize / dpr), dpr);
3902 if (!pm.isNull())
3903 return qt_pixmapToWinHICON(pm);
3904 }
3905 return nullptr;
3906}
3907
3908void QWindowsWindow::setWindowIcon(const QIcon &icon)
3909{
3910 if (m_data.hwnd) {
3911 destroyIcon();
3912
3913 // The small icon is drawn in the window's title bar, so it is sized for the
3914 // monitor the window is shown on. Note: Do not use savedDpi() here, it is
3915 // initialized in initialize(), whereas setWindowIcon() is already called
3916 // from the constructor.
3917 const UINT windowDpi = GetDpiForWindow(m_data.hwnd);
3918 const UINT titleBarDpi = windowDpi ? windowDpi : UINT(QWindowsScreen::baseDpi);
3919 m_iconSmall = createHIcon(icon, titleBarDpi, SM_CXSMICON, SM_CYSMICON);
3920
3921 // The big icon is used by the task bar and the Alt+Tab dialog. The task bar
3922 // is shown on every monitor, so there is no size that is correct on all of
3923 // them. Size it for the primary monitor, which keeps it sharp where the task
3924 // bar usually is, and, more importantly, keeps it stable when the window is
3925 // moved to a monitor with a different scale factor.
3926 m_iconBig = createHIcon(icon, primaryScreenDpi(), SM_CXICON, SM_CYICON);
3927
3928 if (m_iconBig) {
3929 SendMessage(m_data.hwnd, WM_SETICON, 0 /* ICON_SMALL */, LPARAM(m_iconSmall));
3930 SendMessage(m_data.hwnd, WM_SETICON, 1 /* ICON_BIG */, LPARAM(m_iconBig));
3931 } else {
3932 SendMessage(m_data.hwnd, WM_SETICON, 0 /* ICON_SMALL */, LPARAM(m_iconSmall));
3933 SendMessage(m_data.hwnd, WM_SETICON, 1 /* ICON_BIG */, LPARAM(m_iconSmall));
3934 }
3935 }
3936}
3937
3939{
3940 return window()->isTopLevel() && !m_data.embedded;
3941}
3942
3943enum : WORD {
3946};
3947
3948bool QWindowsWindow::setDarkBorderToWindow(HWND hwnd, bool d)
3949{
3950 const BOOL darkBorder = d ? TRUE : FALSE;
3951 const bool ok =
3952 SUCCEEDED(DwmSetWindowAttribute(hwnd, DwmwaUseImmersiveDarkMode, &darkBorder, sizeof(darkBorder)))
3953 || SUCCEEDED(DwmSetWindowAttribute(hwnd, DwmwaUseImmersiveDarkModeBefore20h1, &darkBorder, sizeof(darkBorder)));
3954 if (!ok)
3955 qCWarning(lcQpaWindow, "%s: Unable to set %s window border.", __FUNCTION__, d ? "dark" : "light");
3956 return ok;
3957}
3958
3960{
3961 // frames only apply to toplevel windows
3962 if (!isTopLevel_sys())
3963 return;
3964
3965 // respect explicit opt-out and incompatible palettes or styles
3966 d = d && shouldApplyDarkFrame(window());
3967
3968 setDarkBorderToWindow(m_data.hwnd, d);
3969}
3970
3972{
3973 return m_menuBar.data();
3974}
3975
3977{
3978 m_menuBar = mb;
3979}
3980
3982{
3983 if (m_data.flags & Qt::FramelessWindowHint)
3984 return {};
3985 return m_data.customMargins;
3986}
3987
3988/*!
3989 \brief Sets custom margins to be added to the default margins determined by
3990 the windows style in the handling of the WM_NCCALCSIZE message.
3991
3992 This is currently used to give the Aero-style QWizard a smaller top margin.
3993 The property can be set using QPlatformNativeInterface::setWindowProperty() or,
3994 before platform window creation, by setting a dynamic property
3995 on the QWindow (see QWindowsIntegration::createPlatformWindow()).
3996*/
3997
3998void QWindowsWindow::setCustomMargins(const QMargins &newCustomMargins)
3999{
4000 if (m_data.flags & Qt::FramelessWindowHint) {
4001 qCWarning(lcQpaWindow) << "You should not set custom margins for a frameless window.";
4002 return;
4003 }
4004 if (newCustomMargins != m_data.customMargins) {
4005 const QMargins oldCustomMargins = m_data.customMargins;
4006 m_data.customMargins = newCustomMargins;
4007 // Re-trigger WM_NCALCSIZE with wParam=1 by passing SWP_FRAMECHANGED
4008 const QRect currentFrameGeometry = frameGeometry_sys();
4009 const QPoint topLeft = currentFrameGeometry.topLeft();
4010 QRect newFrame = currentFrameGeometry.marginsRemoved(oldCustomMargins) + m_data.customMargins;
4011 newFrame.moveTo(topLeft);
4012 qCDebug(lcQpaWindow) << __FUNCTION__ << oldCustomMargins << "->" << newCustomMargins
4013 << currentFrameGeometry << "->" << newFrame;
4014 SetWindowPos(m_data.hwnd, nullptr, newFrame.x(), newFrame.y(), newFrame.width(), newFrame.height(), SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE);
4015 }
4016}
4017
4018void *QWindowsWindow::surface(void *nativeConfig, int *err)
4019{
4020#if QT_CONFIG(vulkan)
4021 Q_UNUSED(nativeConfig);
4022 Q_UNUSED(err);
4023 if (window()->surfaceType() == QSurface::VulkanSurface) {
4024 if (!m_vkSurface) {
4025 QVulkanInstance *inst = window()->vulkanInstance();
4026 if (inst)
4027 m_vkSurface = static_cast<QWindowsVulkanInstance *>(inst->handle())->createSurface(handle());
4028 else
4029 qWarning("Attempted to create Vulkan surface without an instance; was QWindow::setVulkanInstance() called?");
4030 }
4031 // Different semantics for VkSurfaces: the return value is the address,
4032 // not the value, given that this is a 64-bit handle even on x86.
4033 return &m_vkSurface;
4034 }
4035#elif defined(QT_NO_OPENGL)
4036 Q_UNUSED(err);
4037 Q_UNUSED(nativeConfig);
4038 return nullptr;
4039#endif
4040#ifndef QT_NO_OPENGL
4041 if (!m_surface) {
4043 m_surface = staticOpenGLContext->createWindowSurface(m_data.hwnd, nativeConfig, err);
4044 }
4045
4046 return m_surface;
4047#else
4048 return nullptr;
4049#endif
4050}
4051
4053{
4054#if QT_CONFIG(vulkan)
4055 if (m_vkSurface) {
4056 QVulkanInstance *inst = window()->vulkanInstance();
4057 if (inst)
4058 static_cast<QWindowsVulkanInstance *>(inst->handle())->destroySurface(m_vkSurface);
4059 m_vkSurface = VK_NULL_HANDLE;
4060 }
4061#endif
4062#ifndef QT_NO_OPENGL
4063 if (m_surface) {
4065 staticOpenGLContext->destroyWindowSurface(m_surface);
4066 m_surface = nullptr;
4067 }
4068#endif // QT_NO_OPENGL
4069}
4070
4072{
4074 return;
4075
4076 // Initially register or re-register to change the flags
4077 const auto touchTypes = QWindowsIntegration::instance()->touchWindowTouchType();
4079 const auto currentTouchTypes = touchWindowTouchTypes_sys();
4080 if (currentTouchTypes.has_value() && currentTouchTypes.value() == touchTypes)
4081 return;
4082 }
4083
4084 ULONG touchFlags = 0;
4085 if (touchTypes.testFlag(TouchWindowTouchType::FineTouch))
4086 touchFlags |= TWF_FINETOUCH;
4087 if (touchTypes.testFlag(TouchWindowTouchType::WantPalmTouch))
4088 touchFlags |= TWF_WANTPALM;
4089 if (RegisterTouchWindow(m_data.hwnd, touchFlags))
4091 else
4092 qErrnoWarning("RegisterTouchWindow() failed for window '%s'.", qPrintable(window()->objectName()));
4093}
4094
4095void QWindowsWindow::setHasBorderInFullScreenStatic(QWindow *window, bool border)
4096{
4097 if (QPlatformWindow *handle = window->handle())
4098 static_cast<QWindowsWindow *>(handle)->setHasBorderInFullScreen(border);
4099 else
4100 window->setProperty(hasBorderInFullScreenProperty, QVariant(border));
4101}
4102
4104{
4105 m_borderInFullScreenDefault = border;
4106}
4107
4112
4114{
4115 if (hasBorderInFullScreen() == border)
4116 return;
4117 if (border)
4119 else
4121 // Directly apply the flag in case we are fullscreen.
4122 if (m_windowState == Qt::WindowFullScreen) {
4123 LONG_PTR style = GetWindowLongPtr(handle(), GWL_STYLE);
4124 if (border)
4125 style |= WS_BORDER;
4126 else
4127 style &= ~WS_BORDER;
4128 SetWindowLongPtr(handle(), GWL_STYLE, style);
4129 }
4130}
4131
4132QString QWindowsWindow::formatWindowTitle(const QString &title)
4133{
4134 return QPlatformWindow::formatWindowTitle(title, QStringLiteral(" - "));
4135}
4136
4138{
4139 enum UpdateState {
4140 Ready = 0,
4141 Requested = 1,
4142 Posted = 2
4143 };
4144 QWindow *w = window();
4145 QDxgiVSyncService *vs = QDxgiVSyncService::instance();
4146 if (vs->supportsWindow(w)) {
4147 // The base class's timer-based fallback may still be running from an
4148 // earlier requestUpdate() serviced before DXGI vsync became available.
4149 // Stop it now that DXGI vsync callbacks take over delivery, otherwise
4150 // both mechanisms end up delivering update requests concurrently.
4151 QPlatformWindow::d_ptr->updateTimer.stop();
4152 if (m_vsyncServiceCallbackId == 0) {
4153 m_vsyncServiceCallbackId = vs->registerCallback([this, w](const QDxgiVSyncService::CallbackWindowList &windowList, qint64) {
4154 if (windowList.contains(w)) {
4155 // Make sure we only post one event at a time. If the state
4156 // isn't Requested, it means there either isn't a pending
4157 // request or we are waiting for the event loop to process
4158 // the Posted event on the GUI thread.
4159 if (m_vsyncUpdatePending.testAndSetAcquire(UpdateState::Requested, UpdateState::Posted)) {
4160 QWindowsWindow *oldSelf = this;
4161 qsizetype oldCallbackId = m_vsyncServiceCallbackId;
4162 QMetaObject::invokeMethod(w, [w, oldSelf, oldCallbackId] {
4163 // 'oldSelf' is only used for comparison, don't access it directly!
4164 auto *self = static_cast<QWindowsWindow *>(w->handle());
4165 // NOTE: In the off chance that the window got destroyed and recreated with the
4166 // same address, we also check that the callback id is the same.
4167 if (self && self == oldSelf && self->m_vsyncServiceCallbackId == oldCallbackId) {
4168 // The platform window is still alive
4169 self->m_vsyncUpdatePending.storeRelease(UpdateState::Ready);
4170 self->deliverUpdateRequest();
4171 }
4172 }, Qt::QueuedConnection); // the callback may run on this thread
4173 }
4174 }
4175 });
4176 }
4177 m_vsyncUpdatePending.testAndSetRelease(UpdateState::Ready, UpdateState::Requested);
4178 } else {
4179 QPlatformWindow::requestUpdate();
4180 }
4181}
4182
4183QT_END_NAMESPACE
\inmodule QtCore\reentrant
Definition qpoint.h:30
Base class for QWindowsForeignWindow, QWindowsWindow.
QMargins frameMargins_sys() const
bool isTopLevel_sys() const
void setHasBorderInFullScreen(bool border) override
QMargins customMargins() const override
bool windowEvent(QEvent *event) override
Reimplement this method to be able to do any platform specific event handling.
bool hasBorderInFullScreen() const override
bool hasMaximumWidth() const
unsigned style() const
std::optional< TouchWindowTouchTypes > touchWindowTouchTypes_sys() const
bool hasMaximumHeight() const
QRect frameGeometry_sys() const
QRect geometry_sys() const
void setCustomMargins(const QMargins &margins) override
void setGeometry_sys(const QRect &rect) const
bool hasMaximumSize() const
void setWindowTitle_sys(const QString &title)
Singleton container for all relevant information.
QWindowsScreenManager & screenManager()
unsigned systemInfo() const
static QWindowsContext * instance()
Platform cursor implementation.
static bool hasOverrideCursor()
static void enforceOverrideCursor()
Window wrapping a foreign native window.
void setVisible(bool visible) override
Reimplemented in subclasses to show the surface if visible is true, and hide it if visible is false.
static QWindowsStaticOpenGLContext * staticOpenGLContext()
static QWindowsIntegration * instance()
Windows native menu bar.
static QWindowsMenuBar * menuBarOf(const QWindow *notYetCreatedWindow)
Manages a list of QWindowsScreen.
const QWindowsScreen * screenAtDp(const QPoint &p) const
Windows screen.
static int baseDpi
virtual void * createWindowSurface(void *, void *, int *)
virtual void destroyWindowSurface(void *)
static QWindowsWindowClassRegistry * instance()
Raster or OpenGL Window.
void alertWindow(int durationMs=0)
void setWindowFlags(Qt::WindowFlags flags) override
Requests setting the window flags of this surface to flags.
void setCustomMargins(const QMargins &m) override
Sets custom margins to be added to the default margins determined by the windows style in the handlin...
void setMenuBar(QWindowsMenuBar *mb)
void invalidateSurface() override
Invalidates the window's surface by releasing its surface buffers.
HDC getDC()
Allocates a HDC for the window or returns the temporary one obtained from WinAPI BeginPaint within a ...
QMargins fullFrameMargins() const override
void checkForScreenChanged(ScreenChangeMode mode=FromGeometryChange, const RECT *suggestedRect=nullptr)
void initialize() override
Called as part of QWindow::create(), after constructing the window.
void handleDpiChangedAfterParent(HWND hwnd)
void requestUpdate() override
Requests an QEvent::UpdateRequest event.
bool testFlag(unsigned f) const
void setFlag(unsigned f) const
void clearFlag(unsigned f) const
void setFrameStrutEventsEnabled(bool enabled) override
Reimplement this method to set whether frame strut events should be sent to enabled.
static void settingsChanged()
void getSizeHints(MINMAXINFO *mmi) const
static void setHasBorderInFullScreenDefault(bool border)
~QWindowsWindow() override
bool handleWmPaint(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, LRESULT *result)
bool setMouseGrabEnabled(bool grab) override
void propagateSizeHints() override
Reimplement to propagate the size hints of the QWindow.
void applyCursor()
Applies to cursor property set on the window to the global cursor.
bool handleGeometryChanging(MSG *message) const
bool isActive() const override
Returns true if the window should appear active from a style perspective.
void setStyle(unsigned s) const
QString windowTitle() const override
Reimplement to return the actual window title used in the underlying windowing system unless the titl...
static void displayChanged()
bool setKeyboardGrabEnabled(bool grab) override
bool windowEvent(QEvent *event) override
Reimplement this method to be able to do any platform specific event handling.
void setGeometry(const QRect &rect) override
This function is called by Qt whenever a window is moved or resized using the QWindow API.
void setEnabled(bool enabled)
void setVisible(bool visible) override
Reimplemented in subclasses to show the surface if visible is true, and hide it if visible is false.
QSurfaceFormat format() const override
Returns the actual surface format of the window.
static const char * embeddedNativeParentHandleProperty
QWindowsMenuBar * menuBar() const
bool isLayered() const
void handleDpiChanged(HWND hwnd, WPARAM wParam, LPARAM lParam)
QMargins frameMargins() const override
void setWindowIcon(const QIcon &icon) override
Reimplement to set the window icon to icon.
bool isClientAreaExpanded() const
void handleResized(int wParam, LPARAM lParam)
void setOpacity(qreal level) override
Reimplement to be able to let Qt set the opacity level of a window.
bool isEmbedded() const override
Returns true if the window is a child of a non-Qt window.
QMargins customMargins() const override
bool handleNonClientActivate(LRESULT *result) const
bool isEnabled() const
QRect normalGeometry() const override
Returns the geometry of a window in 'normal' state (neither maximized, fullscreen nor minimized) for ...
void setExStyle(unsigned s) const
qreal dpiRelativeScale(const UINT dpi) const
QMargins safeAreaMargins() const override
The safe area margins of a window represent the area that is safe to place content within,...
void setSavedDpi(int dpi)
void requestActivateWindow() override
Reimplement to let Qt be able to request activation/focus for a window.
void handleDpiScaledSize(WPARAM wParam, LPARAM lParam, LRESULT *result)
@ WithinSetParent
Automatic mouse capture on button press.
static const char * hasBorderInFullScreenProperty
bool startSystemMove() override
Reimplement this method to start a system move operation if the system supports it and return true to...
bool isTopLevel() const override
void releaseDC()
Releases the HDC for the window or does nothing in case it was obtained from WinAPI BeginPaint within...
void setWindowState(Qt::WindowStates state) override
Requests setting the window state of this surface to type.
void setCursor(const CursorHandlePtr &c)
bool hasBorderInFullScreen() const override
bool hasMouseCapture() const
void * surface(void *nativeConfig, int *err)
void setHasBorderInFullScreen(bool border) override
bool isVisible() const
void handleCompositionSettingsChanged()
void setWindowTitle(const QString &title) override
Reimplement to set the window title to title.
void setDarkBorder(bool d)
bool startSystemResize(Qt::Edges edges) override
Reimplement this method to start a system resize operation if the system supports it and return true ...
void setFullFrameMargins(const QMargins &newMargins)
void setMask(const QRegion &region) override
Reimplement to be able to let Qt set the mask of a window.
void setAlertState(bool enabled) override
Reimplement this method to set whether the window demands attention (for example, by flashing the tas...
bool isAlertState() const override
Reimplement this method return whether the window is in an alert state.
Combined button and popup list for selecting options.
@ defaultWindowHeight
Definition qioswindow.mm:35
@ defaultWindowWidth
Definition qioswindow.mm:34
static HICON createHIcon(const QIcon &icon, UINT dpi, int xSizeMetric, int ySizeMetric)
static QSize toNativeSizeConstrained(QSize dip, const QScreen *s)
static void fixTopLevelWindowFlags(Qt::WindowFlags &flags)
static QString msgUnableToSetGeometry(const QWindowsWindow *platformWindow, const QRect &requestedRect, const QRect &obtainedRect, const QMargins &fullMargins, const QMargins &customMargins)
static bool shouldOmitFrameAdjustment(const Qt::WindowFlags flags, DWORD style)
static QRect normalFrameGeometry(HWND hwnd)
static void formatBriefRectangle(QDebug &d, const QRect &r)
static bool testShowWithoutActivating(const QWindow *window)
static bool shouldShowMaximizeButton(const QWindow *w, Qt::WindowFlags flags)
static void setMinimizedGeometry(HWND hwnd, const QRect &r)
static bool applyNewCursor(const QWindow *w)
static bool isSoftwareGl()
static void addRectToWinRegion(const QRect &rect, HRGN *winRegion)
static QByteArray debugWinSwpPos(UINT flags)
static HRGN createRectRegion(const QRect &r)
static QByteArray debugWinStyle(DWORD style)
static QScreen * screenForDeviceName(const QWindow *w, const QString &name)
static QPoint windowPlacementOffset(HWND hwnd, const QPoint &point)
static bool applyBlurBehindWindow(HWND hwnd)
static void setRestoreMaximizedFlag(HWND hwnd, bool set=true)
static RECT RECTfromQRect(const QRect &rect)
static QMargins invisibleMargins(const HWND hwnd)
static QRect frameGeometry(HWND hwnd, bool topLevel)
static void setWindowOpacity(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, bool accelerated, qreal level)
static QMargins invisibleMargins(QPoint screenPoint)
Calculates the dimensions of the invisible borders within the window frames which only exist on Windo...
static int getResizeBorderThickness(const UINT dpi)
static bool windowIsAccelerated(const QWindow *w)
static bool equalDpi(const QDpi &d1, const QDpi &d2)
static bool isResize(const WINDOWPOS *windowPos)
static void formatBriefMargins(QDebug &d, const QMargins &m)
static int getTitleBarHeight_sys(const UINT dpi)
static QByteArray debugWindowPlacementFlags(const UINT flags)
static QSize qSizeOfRect(const RECT &rect)
static DWORD edgesToWinOrientation(Qt::Edges edges)
static bool shouldApplyDarkFrame(const QWindow *w)
static QByteArray debugWinExStyle(DWORD exStyle)
static CursorHandlePtr defaultCursor(const QWindow *w)
static QByteArray debugShowWindowCmd(const UINT cmd)
static UINT primaryScreenDpi()
#define GWL_HWNDPARENT
static HRGN qRegionToWinRegion(const QRegion &region)
static QPoint calcPosition(const QWindow *w, const QWindowCreationContextPtr &context, const QMargins &invMargins)
@ DwmwaUseImmersiveDarkMode
@ DwmwaUseImmersiveDarkModeBefore20h1
static QRect qrectFromRECT(const RECT &rect)
static QWindow::Visibility windowVisibility_sys(HWND hwnd)
static GpuDescription detect()
Active Context for creating windows.
void applyToMinMaxInfo(MINMAXINFO *mmi) const
Stores geometry constraints and provides utility functions.
Window creation code.
void applyWindowFlags(HWND hwnd) const
void initialize(const QWindow *w, HWND h, bool frameChange, qreal opacityLevel) const
QWindowsWindowData WindowData
WindowData create(const QWindow *w, const WindowData &data, QString title) const
void fromWindow(const QWindow *w, const Qt::WindowFlags flags, unsigned creationFlags=0)
Qt::WindowFlags flags