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
qwindowscontext.cpp
Go to the documentation of this file.
1// Copyright (C) 2013 Samuel Gaist <samuel.gaist@edeltech.ch>
2// Copyright (C) 2016 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
12#if QT_CONFIG(directmanipulation)
13# include "qwindowsdirectmanipulation.h"
14#endif
16#include "qwindowsmenu.h"
19#if QT_CONFIG(tabletevent)
20# include "qwindowstabletsupport.h"
21#endif
22#include "qwindowstheme.h"
23#include <private/qguiapplication_p.h>
24#if QT_CONFIG(accessibility)
25# include "uiautomation/qwindowsuiaaccessibility.h"
26#endif
27#if QT_CONFIG(sessionmanager)
28# include <private/qsessionmanager_p.h>
29# include "qwindowssessionmanager.h"
30#endif
31#include "qwindowsscreen.h"
32#include "qwindowstheme.h"
34
35#include <QtGui/qwindow.h>
36#include <qpa/qwindowsysteminterface.h>
37#include <qpa/qwindowsysteminterface_p.h>
38#include <qpa/qplatformnativeinterface.h>
39#include <QtGui/qguiapplication.h>
40#include <QtGui/qopenglcontext.h>
41#include <QtGui/qpointingdevice.h>
42
43#include <QtCore/qhash.h>
44#include <QtCore/qstringlist.h>
45#include <QtCore/qdebug.h>
46#include <QtCore/qsysinfo.h>
47#include <QtCore/qscopedpointer.h>
48#include <QtCore/qscopeguard.h>
49#include <QtCore/private/qwinregistry_p.h>
50#if QT_CONFIG(cpp_winrt)
51# include <QtCore/private/qfactorycacheregistration_p.h>
52#endif
53#include <QtCore/private/qsystemerror_p.h>
54#include <QtCore/private/quniquehandle_types_windows_p.h>
55
56#include <QtGui/private/qwindowsguieventdispatcher_p.h>
57#include <QtGui/private/qwindowsthemecache_p.h>
58
59#include <stdlib.h>
60#include <stdio.h>
61#include <windowsx.h>
62#include <dbt.h>
63#include <wtsapi32.h>
64#include <shellscalingapi.h>
65
66QT_BEGIN_NAMESPACE
67
68using namespace Qt::StringLiterals;
69
70Q_LOGGING_CATEGORY(lcQpaWindow, "qt.qpa.window")
71Q_LOGGING_CATEGORY(lcQpaEvents, "qt.qpa.events")
72Q_LOGGING_CATEGORY(lcQpaGl, "qt.qpa.gl")
73Q_LOGGING_CATEGORY(lcQpaMime, "qt.qpa.mime")
74Q_LOGGING_CATEGORY(lcQpaInputMethods, "qt.qpa.input.methods")
75Q_LOGGING_CATEGORY(lcQpaDialogs, "qt.qpa.dialogs")
76Q_LOGGING_CATEGORY(lcQpaMenus, "qt.qpa.menus")
77Q_LOGGING_CATEGORY(lcQpaTablet, "qt.qpa.input.tablet")
78Q_LOGGING_CATEGORY(lcQpaGestures, "qt.qpa.input.gestures")
79Q_LOGGING_CATEGORY(lcQpaAccessibility, "qt.qpa.accessibility")
80Q_LOGGING_CATEGORY(lcQpaUiAutomation, "qt.qpa.uiautomation")
81Q_LOGGING_CATEGORY(lcQpaTrayIcon, "qt.qpa.trayicon")
82Q_LOGGING_CATEGORY(lcQpaScreen, "qt.qpa.screen")
83Q_LOGGING_CATEGORY(lcQpaTheme, "qt.qpa.theme")
84
85int QWindowsContext::verbose = 0;
86
87#if !defined(LANG_SYRIAC)
88# define LANG_SYRIAC 0x5a
89#endif
90
91static inline bool useRTL_Extensions()
92{
93 // Since the IsValidLanguageGroup/IsValidLocale functions always return true on
94 // Vista, check the Keyboard Layouts for enabling RTL.
95 if (const int nLayouts = GetKeyboardLayoutList(0, nullptr)) {
96 QScopedArrayPointer<HKL> lpList(new HKL[nLayouts]);
97 GetKeyboardLayoutList(nLayouts, lpList.data());
98 for (int i = 0; i < nLayouts; ++i) {
99 switch (PRIMARYLANGID((quintptr)lpList[i])) {
100 case LANG_ARABIC:
101 case LANG_HEBREW:
102 case LANG_FARSI:
103 case LANG_SYRIAC:
104 return true;
105 default:
106 break;
107 }
108 }
109 }
110 return false;
111}
112
113#if QT_CONFIG(sessionmanager)
114static inline QWindowsSessionManager *platformSessionManager()
115{
116 auto *guiPrivate = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(qApp));
117 auto *managerPrivate = static_cast<QSessionManagerPrivate*>(QObjectPrivate::get(guiPrivate->session_manager));
118 return static_cast<QWindowsSessionManager *>(managerPrivate->platformSessionManager);
119}
120
121static inline bool sessionManagerInteractionBlocked()
122{
123 return platformSessionManager()->isInteractionBlocked();
124}
125#else // QT_CONFIG(sessionmanager)
126static inline bool sessionManagerInteractionBlocked() { return false; }
127#endif
128
129QWindowsContext *QWindowsContext::m_instance = nullptr;
130
131/*!
132 \class QWindowsContext
133 \brief Singleton container for all relevant information.
134
135 Holds state information formerly stored in \c qapplication_win.cpp.
136
137 \internal
138*/
139
166
168
171{
172 if (m_pointerHandler.touchDevice())
174 m_displayContext.reset(GetDC(nullptr));
175 m_defaultDPI = GetDeviceCaps(m_displayContext.get(), LOGPIXELSY);
178 m_keyMapper.setUseRTLExtensions(true);
179 }
180 if (FAILED(m_oleInitializeResult)) {
181 qWarning() << "QWindowsContext: OleInitialize() failed: "
182 << QSystemError::windowsComString(m_oleInitializeResult);
183 } else {
184#if QT_CONFIG(directmanipulation)
185 // Needs COM, which OleInitialize() has just set up.
186 m_directManipulation.reset(QWindowsDirectManipulation::create());
187#endif
188 }
189}
190
193{
194 m_instance = this;
195}
196
198{
199#if QT_CONFIG(tabletevent)
200 d->m_tabletSupport.reset(); // Destroy internal window before unregistering classes.
201#endif
202#if QT_CONFIG(directmanipulation)
203 d->m_directManipulation.reset(); // Release COM objects before OleUninitialize().
204#endif
205
206 if (d->m_powerNotification)
207 UnregisterPowerSettingNotification(d->m_powerNotification);
208
209 if (d->m_powerDummyWindow)
210 DestroyWindow(d->m_powerDummyWindow);
211
213 theme->destroyThemeChangeWindow();
214
215 d->m_screenManager.destroyWindow();
216
217 if (d->m_oleInitializeResult == S_OK || d->m_oleInitializeResult == S_FALSE) {
218#ifdef QT_USE_FACTORY_CACHE_REGISTRATION
219 detail::QWinRTFactoryCacheRegistration::clearAllCaches();
220#endif
221 OleUninitialize();
222 }
223
224 d->m_screenManager.clearScreens(); // Order: Potentially calls back to the windows.
225 m_instance = nullptr;
226}
227
232
233bool QWindowsContext::initTouch(unsigned integrationOptions)
234{
235 if (d->m_systemInfo & QWindowsContext::SI_SupportsTouch)
236 return true;
237 auto touchDevice = d->m_pointerHandler.touchDevice();
238 if (touchDevice.isNull()) {
239 const bool mouseEmulation =
240 (integrationOptions & QWindowsIntegration::DontPassOsMouseEventsSynthesizedFromTouch) == 0;
241 touchDevice = QWindowsPointerHandler::createTouchDevice(mouseEmulation);
242 }
243 if (touchDevice.isNull())
244 return false;
245 d->m_pointerHandler.setTouchDevice(touchDevice);
246 QWindowSystemInterface::registerInputDevice(touchDevice.data());
247
248 d->m_systemInfo |= QWindowsContext::SI_SupportsTouch;
249
250 // A touch device was plugged while the app is running. Register all windows for touch.
252
253 return true;
254}
255
257{
258 if (QGuiApplicationPrivate::is_app_running
259 && (d->m_systemInfo & QWindowsContext::SI_SupportsTouch) != 0) {
260 for (QWindowsWindow *w : std::as_const(d->m_windows))
261 w->registerTouchWindow();
262 }
263}
264
266{
267#if QT_CONFIG(tabletevent)
268 d->m_tabletSupport.reset(QWindowsTabletSupport::create());
269 return true;
270#else
271 return false;
272#endif
273}
274
276{
277#if QT_CONFIG(tabletevent)
278 d->m_tabletSupport.reset();
279 return true;
280#else
281 return false;
282#endif
283}
284
285LRESULT QT_WIN_CALLBACK qWindowsPowerWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
286{
287 if (message != WM_POWERBROADCAST || wParam != PBT_POWERSETTINGCHANGE)
288 return DefWindowProc(hwnd, message, wParam, lParam);
289
290 static bool initialized = false; // ignore the initial change
291 if (!initialized) {
292 initialized = true;
293 return DefWindowProc(hwnd, message, wParam, lParam);
294 }
295
296 auto setting = reinterpret_cast<const POWERBROADCAST_SETTING *>(lParam);
297 if (setting) {
298 auto data = reinterpret_cast<const DWORD *>(&setting->Data);
299 if (*data == 1) {
300 // Repaint the windows when returning from sleeping display mode.
301 const auto tlw = QGuiApplication::topLevelWindows();
302 for (auto w : tlw) {
303 if (w->isVisible() && w->windowState() != Qt::WindowMinimized) {
304 if (auto tw = QWindowsWindow::windowsWindowOf(w)) {
305 if (HWND hwnd = tw->handle()) {
306 InvalidateRect(hwnd, nullptr, false);
307 }
308 }
309 }
310 }
311 }
312 }
313 return DefWindowProc(hwnd, message, wParam, lParam);
314}
315
317{
318 if (d->m_powerNotification)
319 return false;
320
321 d->m_powerDummyWindow = createDummyWindow(QStringLiteral("PowerDummyWindow"), L"QtPowerDummyWindow", qWindowsPowerWindowProc);
322 if (!d->m_powerDummyWindow)
323 return false;
324
325 d->m_powerNotification = RegisterPowerSettingNotification(d->m_powerDummyWindow, &GUID_MONITOR_POWER_ON, DEVICE_NOTIFY_WINDOW_HANDLE);
326 if (!d->m_powerNotification) {
327 DestroyWindow(d->m_powerDummyWindow);
328 d->m_powerDummyWindow = nullptr;
329 return false;
330 }
331 return true;
332}
333
335{
336#if QT_CONFIG(tabletevent)
337 QWindowsTabletSupport::setAbsoluteRange(a);
338#else
339 Q_UNUSED(a);
340#endif
341}
342
344{
345 d->m_keyMapper.setDetectAltGrModifier(a);
346}
347
348[[nodiscard]] static inline QtWindows::DpiAwareness
349 dpiAwarenessContextToQtDpiAwareness(DPI_AWARENESS_CONTEXT context)
350{
351 // IsValidDpiAwarenessContext() will handle the NULL pointer case.
352 if (!IsValidDpiAwarenessContext(context))
353 return QtWindows::DpiAwareness::Invalid;
354 if (AreDpiAwarenessContextsEqual(context, DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED))
355 return QtWindows::DpiAwareness::Unaware_GdiScaled;
356 if (AreDpiAwarenessContextsEqual(context, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2))
358 if (AreDpiAwarenessContextsEqual(context, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE))
359 return QtWindows::DpiAwareness::PerMonitor;
360 if (AreDpiAwarenessContextsEqual(context, DPI_AWARENESS_CONTEXT_SYSTEM_AWARE))
361 return QtWindows::DpiAwareness::System;
362 if (AreDpiAwarenessContextsEqual(context, DPI_AWARENESS_CONTEXT_UNAWARE))
363 return QtWindows::DpiAwareness::Unaware;
364 return QtWindows::DpiAwareness::Invalid;
365}
366
367QtWindows::DpiAwareness QWindowsContext::windowDpiAwareness(HWND hwnd)
368{
369 if (!hwnd)
370 return QtWindows::DpiAwareness::Invalid;
371 const auto context = GetWindowDpiAwarenessContext(hwnd);
372 return dpiAwarenessContextToQtDpiAwareness(context);
373}
374
376{
377 // Although we have GetDpiAwarenessContextForProcess(), however,
378 // it's only available on Win10 1903+, which is a little higher
379 // than Qt's minimum supported version (1809), so we can't use it.
380 // Luckily, MS docs said GetThreadDpiAwarenessContext() will also
381 // return the default DPI_AWARENESS_CONTEXT for the process if
382 // SetThreadDpiAwarenessContext() was never called. So we can use
383 // it as an equivalent.
384 const auto context = GetThreadDpiAwarenessContext();
385 return dpiAwarenessContextToQtDpiAwareness(context);
386}
387
388[[nodiscard]] static inline DPI_AWARENESS_CONTEXT
390{
391 switch (dpiAwareness) {
392 case QtWindows::DpiAwareness::Invalid:
393 return nullptr;
394 case QtWindows::DpiAwareness::Unaware:
396 case QtWindows::DpiAwareness::System:
398 case QtWindows::DpiAwareness::PerMonitor:
400 case QtWindows::DpiAwareness::PerMonitorVersion2:
402 case QtWindows::DpiAwareness::Unaware_GdiScaled:
404 }
405 return nullptr;
406}
407
408#ifndef QT_NO_DEBUG_STREAM
409QDebug operator<<(QDebug d, QtWindows::DpiAwareness dpiAwareness)
410{
411 const QDebugStateSaver saver(d);
412 QString message = u"QtWindows::DpiAwareness::"_s;
413 switch (dpiAwareness) {
414 case QtWindows::DpiAwareness::Invalid:
415 message += u"Invalid"_s;
416 break;
417 case QtWindows::DpiAwareness::Unaware:
418 message += u"Unaware"_s;
419 break;
420 case QtWindows::DpiAwareness::System:
421 message += u"System"_s;
422 break;
423 case QtWindows::DpiAwareness::PerMonitor:
424 message += u"PerMonitor"_s;
425 break;
427 message += u"PerMonitorVersion2"_s;
428 break;
430 message += u"Unaware_GdiScaled"_s;
431 break;
432 }
433 d.nospace().noquote() << message;
434 return d;
435}
436#endif
437
439{
440 qCDebug(lcQpaWindow) << __FUNCTION__ << dpiAwareness;
441 [[maybe_unused]] const auto updatePMv2Status = qScopeGuard([](){
444 });
445 if (processDpiAwareness() == dpiAwareness)
446 return true;
447 const auto context = qtDpiAwarenessToDpiAwarenessContext(dpiAwareness);
448 if (!IsValidDpiAwarenessContext(context)) {
449 qCWarning(lcQpaWindow) << dpiAwareness << "is not supported by current system.";
450 return false;
451 }
452 if (!SetProcessDpiAwarenessContext(context)) {
453 qCWarning(lcQpaWindow).noquote().nospace()
454 << "SetProcessDpiAwarenessContext() failed: "
455 << QSystemError::windowsString()
456 << "\nQt's default DPI awareness context is "
457 << "DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2. If you know what you "
458 << "are doing, you can overwrite this default using qt.conf "
459 << "(https://doc.qt.io/qt-6/highdpi.html#configuring-windows).";
460 return false;
461 }
462 return true;
463}
464
466{
467 return m_instance;
468}
469
471{
472 return d->m_systemInfo;
473}
474
476{
477 return d->m_keyMapper.useRTLExtensions();
478}
479
480QPlatformKeyMapper *QWindowsContext::keyMapper() const
481{
482 return &d->m_keyMapper;
483}
484
486{
487 return d->m_windows;
488}
489
490QSharedPointer<QWindowCreationContext> QWindowsContext::setWindowCreationContext(const QSharedPointer<QWindowCreationContext> &ctx)
491{
492 const QSharedPointer<QWindowCreationContext> old = d->m_creationContext;
493 d->m_creationContext = ctx;
494 return old;
495}
496
498{
499 return d->m_creationContext;
500}
501
503{
504 return d->m_defaultDPI;
505}
506
508{
509 return d->m_displayContext.get();
510}
511
513{
514 return d->m_keyMapper.keyGrabber();
515}
516
517void QWindowsContext::setKeyGrabber(QWindow *w)
518{
519 d->m_keyMapper.setKeyGrabber(w);
520}
521
523{
524 return GetDeviceCaps(d->m_displayContext.get(), BITSPIXEL);
525}
526
528{
529 d->m_windows.insert(hwnd, w);
530}
531
533{
534 const HandleBaseWindowHash::iterator it = d->m_windows.find(hwnd);
535 if (it != d->m_windows.end()) {
536 if (d->m_keyMapper.keyGrabber() == it.value()->window())
537 d->m_keyMapper.setKeyGrabber(nullptr);
538 d->m_windows.erase(it);
539 }
540}
541
543{
544 for (auto it = d->m_windows.cbegin(), end = d->m_windows.cend(); it != end; ++it) {
545 if ((*it)->menuBar() == mb)
546 return *it;
547 }
548 return nullptr;
549}
550
552{
553 return d->m_windows.value(hwnd);
554}
555
557{
558 QWindowsWindow *window = d->m_windows.value(hwnd);
559
560 // Requested hwnd may also be a child of a platform window in case of embedded native windows.
561 // Find the closest parent that has a platform window.
562 if (!window) {
563 for (HWND w = hwnd; w; w = GetParent(w)) {
564 window = d->m_windows.value(w);
565 if (window)
566 break;
567 }
568 }
569
570 return window;
571}
572
573QWindow *QWindowsContext::findWindow(HWND hwnd) const
574{
575 if (const QWindowsWindow *bw = findPlatformWindow(hwnd))
576 return bw->window();
577 return nullptr;
578}
579
581{
582 return d->m_pointerHandler.windowUnderMouse();
583}
584
586{
587 d->m_pointerHandler.clearWindowUnderMouse();
588}
589
590/*!
591 \brief Find a child window at a screen point.
592
593 Deep search for a QWindow at global point, skipping non-owned
594 windows (accessibility?). Implemented using ChildWindowFromPointEx()
595 instead of (historically used) WindowFromPoint() to get a well-defined
596 behaviour for hidden/transparent windows.
597
598 \a cwex_flags are flags of ChildWindowFromPointEx().
599 \a parent is the parent window, pass GetDesktopWindow() for top levels.
600*/
601
602static inline bool findPlatformWindowHelper(const POINT &screenPoint, unsigned cwexFlags,
603 const QWindowsContext *context,
604 HWND *hwnd, QWindowsWindow **result)
605{
606 POINT point = screenPoint;
607 screenToClient(*hwnd, &point);
608 // Returns parent if inside & none matched.
609 const HWND child = ChildWindowFromPointEx(*hwnd, point, cwexFlags);
610 if (!child || child == *hwnd)
611 return false;
612 if (QWindowsWindow *window = context->findPlatformWindow(child)) {
613 *result = window;
614 *hwnd = child;
615 return true;
616 }
617 // QTBUG-40555: despite CWP_SKIPINVISIBLE, it is possible to hit on invisible
618 // full screen windows of other applications that have WS_EX_TRANSPARENT set
619 // (for example created by screen sharing applications). In that case, try to
620 // find a Qt window by searching again with CWP_SKIPTRANSPARENT.
621 // Note that Qt 5 uses WS_EX_TRANSPARENT for Qt::WindowTransparentForInput
622 // as well.
623 if (!(cwexFlags & CWP_SKIPTRANSPARENT)
624 && (GetWindowLongPtr(child, GWL_EXSTYLE) & WS_EX_TRANSPARENT)) {
625 const HWND nonTransparentChild = ChildWindowFromPointEx(*hwnd, point, cwexFlags | CWP_SKIPTRANSPARENT);
626 if (!nonTransparentChild || nonTransparentChild == *hwnd)
627 return false;
628 if (QWindowsWindow *nonTransparentWindow = context->findPlatformWindow(nonTransparentChild)) {
629 *result = nonTransparentWindow;
630 *hwnd = nonTransparentChild;
631 return true;
632 }
633 }
634 *hwnd = child;
635 return true;
636}
637
639 const QPoint &screenPointIn,
640 unsigned cwex_flags) const
641{
642 QWindowsWindow *result = nullptr;
643 const POINT screenPoint = { screenPointIn.x(), screenPointIn.y() };
644 while (findPlatformWindowHelper(screenPoint, cwex_flags, this, &parent, &result)) {}
645 // QTBUG-40815: ChildWindowFromPointEx() can hit on special windows from
646 // screen recorder applications like ScreenToGif. Fall back to WindowFromPoint().
647 if (result == nullptr) {
648 if (const HWND window = WindowFromPoint(screenPoint))
649 result = findPlatformWindow(window);
650 }
651 return result;
652}
653
655{
656 bool result = false;
657 const DWORD sessionId = WTSGetActiveConsoleSessionId();
658 if (sessionId != 0xFFFFFFFF) {
659 LPTSTR buffer = nullptr;
660 DWORD size = 0;
661#if !defined(Q_CC_MINGW)
662 if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId,
663 WTSSessionInfoEx, &buffer, &size) == TRUE
664 && size > 0) {
665 const WTSINFOEXW *info = reinterpret_cast<WTSINFOEXW *>(buffer);
666 result = info->Level == 1 && info->Data.WTSInfoExLevel1.SessionFlags == WTS_SESSIONSTATE_LOCK;
667 WTSFreeMemory(buffer);
668 }
669#else // MinGW as of 7.3 does not have WTSINFOEXW in wtsapi32.h
670 // Retrieve the flags which are at offset 16 due to padding for 32/64bit alike.
671 if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId,
672 WTS_INFO_CLASS(25), &buffer, &size) == TRUE
673 && size >= 20) {
674 const DWORD *p = reinterpret_cast<DWORD *>(buffer);
675 const DWORD level = *p;
676 const DWORD sessionFlags = *(p + 4);
677 result = level == 1 && sessionFlags == 1;
678 WTSFreeMemory(buffer);
679 }
680#endif // Q_CC_MINGW
681 }
682 return result;
683}
684
686{
687 return d->m_mimeConverter;
688}
689
691{
692 return d->m_screenManager;
693}
694
696{
697#if QT_CONFIG(directmanipulation)
698 return d->m_directManipulation.data();
699#else
700 return nullptr;
701#endif
702}
703
705{
706#if QT_CONFIG(tabletevent)
707 return d->m_tabletSupport.data();
708#else
709 return 0;
710#endif
711}
712
713/*!
714 \brief Convenience to create a non-visible, message-only dummy
715 window for example used as clipboard watcher or for GL.
716*/
717
718HWND QWindowsContext::createDummyWindow(const QString &classNameIn,
719 const wchar_t *windowName,
720 WNDPROC wndProc, DWORD style)
721{
722 if (!wndProc)
723 wndProc = DefWindowProc;
724 QString className = d->m_windowClassRegistry.registerWindowClass(classNameIn, wndProc);
725 return CreateWindowEx(0, reinterpret_cast<LPCWSTR>(className.utf16()),
726 windowName, style,
727 CW_USEDEFAULT, CW_USEDEFAULT,
728 CW_USEDEFAULT, CW_USEDEFAULT,
729 HWND_MESSAGE, nullptr, static_cast<HINSTANCE>(GetModuleHandle(nullptr)), nullptr);
730}
731
732void QWindowsContext::forceNcCalcSize(HWND hwnd)
733{
734 // Force WM_NCCALCSIZE to adjust margin
735 SetWindowPos(hwnd, nullptr, 0, 0, 0, 0,
736 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
737}
738
739bool QWindowsContext::systemParametersInfo(unsigned action, unsigned param, void *out,
740 unsigned dpi)
741{
742 const BOOL result = dpi != 0
743 ? SystemParametersInfoForDpi(action, param, out, 0, dpi)
744 : SystemParametersInfo(action, param, out, 0);
745 return result == TRUE;
746}
747
748bool QWindowsContext::systemParametersInfoForScreen(unsigned action, unsigned param, void *out,
749 const QPlatformScreen *screen)
750{
751 return systemParametersInfo(action, param, out, screen ? unsigned(screen->logicalDpi().first) : 0u);
752}
753
754bool QWindowsContext::systemParametersInfoForWindow(unsigned action, unsigned param, void *out,
755 const QPlatformWindow *win)
756{
757 return systemParametersInfoForScreen(action, param, out, win ? win->screen() : nullptr);
758}
759
760bool QWindowsContext::nonClientMetrics(NONCLIENTMETRICS *ncm, unsigned dpi)
761{
762 memset(ncm, 0, sizeof(NONCLIENTMETRICS));
763 ncm->cbSize = sizeof(NONCLIENTMETRICS);
764 return systemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm->cbSize, ncm, dpi);
765}
766
767bool QWindowsContext::nonClientMetricsForScreen(NONCLIENTMETRICS *ncm,
768 const QPlatformScreen *screen)
769{
770 const int dpi = screen ? qRound(screen->logicalDpi().first) : 0;
771 return nonClientMetrics(ncm, unsigned(dpi));
772}
773
774bool QWindowsContext::nonClientMetricsForWindow(NONCLIENTMETRICS *ncm, const QPlatformWindow *win)
775{
776 return nonClientMetricsForScreen(ncm, win ? win->screen() : nullptr);
777}
778
780{
781 return qobject_cast<QWindowsInputContext *>(QWindowsIntegration::instance()->inputContext());
782}
783
784bool QWindowsContext::shouldHaveNonClientDpiScaling(const QWindow *window)
785{
786 // DPI aware V2 processes always have NonClientDpiScaling enabled.
788 return true;
789
790 return window->isTopLevel()
791 && !window->property(QWindowsWindow::embeddedNativeParentHandleProperty).isValid()
792#if QT_CONFIG(opengl) // /QTBUG-62901, EnableNonClientDpiScaling has problems with GL
793 && (window->surfaceType() != QSurface::OpenGLSurface
794 || QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGL)
795#endif
796 ;
797}
798
799static inline bool isInputMessage(UINT m)
800{
801 switch (m) {
802 case WM_IME_STARTCOMPOSITION:
803 case WM_IME_ENDCOMPOSITION:
804 case WM_IME_COMPOSITION:
805 case WM_INPUT:
806 case WM_TOUCH:
807 case WM_MOUSEHOVER:
808 case WM_MOUSELEAVE:
809 case WM_NCMOUSEHOVER:
810 case WM_NCMOUSELEAVE:
811 case WM_SIZING:
812 case WM_MOVING:
813 case WM_SYSCOMMAND:
814 case WM_COMMAND:
815 case WM_DWMNCRENDERINGCHANGED:
816 case WM_PAINT:
817 return true;
818 default:
819 break;
820 }
821 return (m >= WM_MOUSEFIRST && m <= WM_MOUSELAST)
822 || (m >= WM_NCMOUSEMOVE && m <= WM_NCXBUTTONDBLCLK)
823 || (m >= WM_KEYFIRST && m <= WM_KEYLAST);
824}
825
826// Note: This only works within WM_NCCREATE
827static bool enableNonClientDpiScaling(HWND hwnd)
828{
829 bool result = false;
830 if (QWindowsContext::windowDpiAwareness(hwnd) == QtWindows::DpiAwareness::PerMonitor) {
831 result = EnableNonClientDpiScaling(hwnd) != FALSE;
832 if (!result) {
833 const DWORD errorCode = GetLastError();
834 qErrnoWarning(int(errorCode), "EnableNonClientDpiScaling() failed for HWND %p (%lu)",
835 hwnd, errorCode);
836 }
837 }
838 return result;
839}
840
841/*!
842 \brief Main windows procedure registered for windows.
843
844 \sa QWindowsGuiEventDispatcher
845*/
846
847bool QWindowsContext::windowsProc(HWND hwnd, UINT message,
848 QtWindows::WindowsEventType et,
849 WPARAM wParam, LPARAM lParam,
850 LRESULT *result,
851 QWindowsWindow **platformWindowPtr)
852{
853 *result = 0;
854
855 MSG msg;
856 msg.hwnd = hwnd; // re-create MSG structure
857 msg.message = message;
858 msg.wParam = wParam;
859 msg.lParam = lParam;
860 msg.time = GetMessageTime();
861 msg.pt.x = msg.pt.y = 0;
862 if (et != QtWindows::CursorEvent && (et & (QtWindows::MouseEventFlag | QtWindows::NonClientEventFlag))) {
863 msg.pt.x = GET_X_LPARAM(lParam);
864 msg.pt.y = GET_Y_LPARAM(lParam);
865 // For non-client-area messages, these are screen coordinates (as expected
866 // in the MSG structure), otherwise they are client coordinates.
867 if (!(et & QtWindows::NonClientEventFlag)) {
868 clientToScreen(msg.hwnd, &msg.pt);
869 }
870 } else {
871 GetCursorPos(&msg.pt);
872 }
873
874 QWindowsWindow *platformWindow = findPlatformWindow(hwnd);
875 *platformWindowPtr = platformWindow;
876
877 // Run the native event filters. QTBUG-67095: Exclude input messages which are sent
878 // by QEventDispatcherWin32::processEvents()
879 if (!isInputMessage(msg.message) && filterNativeEvent(&msg, result))
880 return true;
881
882 if (platformWindow && filterNativeEvent(platformWindow->window(), &msg, result))
883 return true;
884
885 if (et & QtWindows::InputMethodEventFlag) {
886 QWindowsInputContext *windowsInputContext = ::windowsInputContext();
887 // Disable IME assuming this is a special implementation hooking into keyboard input.
888 // "Real" IME implementations should use a native event filter intercepting IME events.
889 if (!windowsInputContext) {
891 return false;
892 }
893 switch (et) {
895 return windowsInputContext->startComposition(hwnd);
896 case QtWindows::InputMethodCompositionEvent:
897 return windowsInputContext->composition(hwnd, lParam);
899 return windowsInputContext->endComposition(hwnd);
900 case QtWindows::InputMethodRequest:
901 return windowsInputContext->handleIME_Request(wParam, lParam, result);
902 default:
903 break;
904 }
905 } // InputMethodEventFlag
906
907 switch (et) {
908 case QtWindows::GestureEvent:
909 // Legacy touch screen gestures; touchpads are handled via Direct
910 // Manipulation, and touch screens via QWindowsPointerHandler.
911 break;
913#if QT_CONFIG(directmanipulation)
914 if (auto *dm = d->m_directManipulation.data();
915 dm && !sessionManagerInteractionBlocked()) {
916 dm->handlePointerHitTest(hwnd, wParam);
917 }
918#endif
919 return false;
922 // TODO: Release/regrab mouse if a popup has mouse grab.
923 return false;
924 case QtWindows::DestroyEvent:
925 if (platformWindow && !platformWindow->testFlag(QWindowsWindow::WithinDestroy)) {
926 qWarning() << "External WM_DESTROY received for " << platformWindow->window()
927 << ", parent: " << platformWindow->window()->parent()
928 << ", transient parent: " << platformWindow->window()->transientParent();
929 }
930 return false;
931 case QtWindows::ClipboardEvent:
932 return false;
933 case QtWindows::CursorEvent: // Sent to windows that do not have capture (see QTBUG-58590).
936 return true;
937 }
938 break;
939 case QtWindows::UnknownEvent:
940 return false;
942#if QT_CONFIG(accessibility)
943 return QWindowsUiaAccessibility::handleWmGetObject(hwnd, wParam, lParam, result);
944#else
945 return false;
946#endif
947 case QtWindows::SettingChangedEvent: {
949 return d->m_screenManager.handleScreenChanges();
950 }
951 default:
952 break;
953 }
954
955 // Before CreateWindowEx() returns, some events are sent,
956 // for example WM_GETMINMAXINFO asking for size constraints for top levels.
957 // Pass on to current creation context
958 if (!platformWindow && !d->m_creationContext.isNull()) {
959 switch (et) {
960 case QtWindows::QuerySizeHints:
961 d->m_creationContext->applyToMinMaxInfo(reinterpret_cast<MINMAXINFO *>(lParam));
962 return true;
963 case QtWindows::ResizeEvent:
964 d->m_creationContext->obtainedSize = QSize(LOWORD(lParam), HIWORD(lParam));
965 return true;
966 case QtWindows::MoveEvent:
967 d->m_creationContext->obtainedPos = QPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
968 return true;
969 case QtWindows::NonClientCreate:
970 if (shouldHaveNonClientDpiScaling(d->m_creationContext->window) &&
971 // DPI aware V2 processes always have NonClientDpiScaling enabled
972 // and there is no need to make an API call to manually enable.
973 !QWindowsContextPrivate::m_v2DpiAware) {
974 enableNonClientDpiScaling(msg.hwnd);
975 }
976 return false;
977 case QtWindows::CalculateSize:
978 return QWindowsGeometryHint::handleCalculateSize(d->m_creationContext->window, d->m_creationContext->customMargins, msg, result);
979 case QtWindows::GeometryChangingEvent:
980 return QWindowsWindow::handleGeometryChangingMessage(&msg, d->m_creationContext->window,
981 d->m_creationContext->margins + d->m_creationContext->customMargins);
982 default:
983 break;
984 }
985 }
986 if (platformWindow) {
987 // Suppress events sent during DestroyWindow() for native children.
989 return false;
991 qCDebug(lcQpaEvents) << "Event window: " << platformWindow->window();
992 } else {
993 qWarning("%s: No Qt Window found for event 0x%x (%s), hwnd=0x%p.",
994 __FUNCTION__, message,
995 QWindowsGuiEventDispatcher::windowsMessageName(message), hwnd);
996 return false;
997 }
998
999 switch (et) {
1000 case QtWindows::DeviceChangeEvent:
1001 if (d->m_systemInfo & QWindowsContext::SI_SupportsTouch)
1002 break;
1003 // See if there are any touch devices added
1004 if (wParam == DBT_DEVNODES_CHANGED)
1006 break;
1007 case QtWindows::InputLanguageChangeEvent:
1009 wic->handleInputLanguageChanged(wParam, lParam);
1010 Q_FALLTHROUGH();
1011 case QtWindows::KeyDownEvent:
1012 case QtWindows::KeyEvent:
1013 case QtWindows::InputMethodKeyEvent:
1014 case QtWindows::InputMethodKeyDownEvent:
1015 case QtWindows::AppCommandEvent:
1016 return sessionManagerInteractionBlocked() || d->m_keyMapper.translateKeyEvent(platformWindow->window(), hwnd, msg, result);
1017 case QtWindows::MenuAboutToShowEvent:
1019 return true;
1020 if (QWindowsPopupMenu::notifyAboutToShow(reinterpret_cast<HMENU>(wParam)))
1021 return true;
1022 if (platformWindow == nullptr || platformWindow->menuBar() == nullptr)
1023 return false;
1024 return platformWindow->menuBar()->notifyAboutToShow(reinterpret_cast<HMENU>(wParam));
1025 case QtWindows::MenuCommandEvent:
1027 return true;
1028 if (QWindowsPopupMenu::notifyTriggered(LOWORD(wParam)))
1029 return true;
1030 if (platformWindow == nullptr || platformWindow->menuBar() == nullptr)
1031 return false;
1032 return platformWindow->menuBar()->notifyTriggered(LOWORD(wParam));
1033 case QtWindows::MoveEvent:
1034 platformWindow->handleMoved();
1035 return true;
1036 case QtWindows::ResizeEvent: {
1037 QWindow *window = platformWindow->window();
1038 platformWindow->handleResized(static_cast<int>(wParam), lParam);
1039 if (window->flags().testFlags(Qt::ExpandedClientAreaHint))
1040 platformWindow->updateCustomTitlebar();
1041 return true;
1042 }
1043 case QtWindows::QuerySizeHints:
1044 platformWindow->getSizeHints(reinterpret_cast<MINMAXINFO *>(lParam));
1045 return true;// maybe available on some SDKs revisit WM_NCCALCSIZE
1046 case QtWindows::CalculateSize:
1047 return QWindowsGeometryHint::handleCalculateSize(platformWindow->window(), platformWindow->customMargins(), msg, result);
1048 case QtWindows::NonClientHitTest: {
1049 QWindow *window = platformWindow->window();
1050 if (window->flags().testFlags(Qt::ExpandedClientAreaHint))
1051 platformWindow->updateCustomTitlebar();
1052 return platformWindow->handleNonClientHitTest(QPoint(msg.pt.x, msg.pt.y), result);
1053 }
1054 case QtWindows::NonClientActivate:
1055 return platformWindow->handleNonClientActivate(result);
1056 case QtWindows::GeometryChangingEvent:
1057 return platformWindow->handleGeometryChanging(&msg);
1058 case QtWindows::ExposeEvent: {
1059 QWindow *window = platformWindow->window();
1060 if (window->flags().testFlags(Qt::ExpandedClientAreaHint))
1061 platformWindow->updateCustomTitlebar();
1062 return platformWindow->handleWmPaint(hwnd, message, wParam, lParam, result);
1063 }
1064 case QtWindows::NonClientMouseEvent:
1065 if (!platformWindow->frameStrutEventsEnabled())
1066 break;
1067 return sessionManagerInteractionBlocked() || d->m_pointerHandler.translateMouseEvent(platformWindow->window(), hwnd, et, msg, result);
1068 case QtWindows::NonClientPointerEvent:
1069 if (!platformWindow->frameStrutEventsEnabled())
1070 break;
1071 return sessionManagerInteractionBlocked() || d->m_pointerHandler.translatePointerEvent(platformWindow->window(), hwnd, et, msg, result);
1072 case QtWindows::EnterSizeMoveEvent:
1074 if (!IsZoomed(hwnd))
1075 platformWindow->updateRestoreGeometry();
1076 return true;
1077 case QtWindows::ExitSizeMoveEvent:
1079 platformWindow->checkForScreenChanged();
1080 handleExitSizeMove(platformWindow->window());
1081 if (!IsZoomed(hwnd))
1082 platformWindow->updateRestoreGeometry();
1083 return true;
1084 case QtWindows::ScrollEvent:
1085 // TODO???
1086 break;
1087 case QtWindows::MouseWheelEvent:
1088 case QtWindows::MouseEvent:
1089 case QtWindows::LeaveEvent:
1090 {
1091 QWindow *window = platformWindow->window();
1092 while (window && (window->flags() & Qt::WindowTransparentForInput))
1093 window = window->parent();
1094 if (!window)
1095 return false;
1096 return sessionManagerInteractionBlocked() || d->m_pointerHandler.translateMouseEvent(window, hwnd, et, msg, result);
1097 }
1098 break;
1099 case QtWindows::TouchEvent:
1100 // TODO???
1101 break;
1102 case QtWindows::PointerEvent:
1103 return sessionManagerInteractionBlocked() || d->m_pointerHandler.translatePointerEvent(platformWindow->window(), hwnd, et, msg, result);
1104 case QtWindows::FocusInEvent: // see QWindowsWindow::requestActivateWindow().
1105 if (platformWindow->window()->flags() & Qt::WindowDoesNotAcceptFocus)
1106 return false;
1107 [[fallthrough]];
1108 case QtWindows::FocusOutEvent:
1109 handleFocusEvent(et, platformWindow);
1110 return true;
1111 case QtWindows::ShowEventOnParentRestoring: // QTBUG-40696, prevent Windows from re-showing hidden transient children (dialogs).
1112 if (!platformWindow->window()->isVisible()) {
1113 *result = 0;
1114 return true;
1115 }
1116 break;
1117 case QtWindows::HideEvent:
1118 platformWindow->handleHidden();
1119 return false;// Indicate transient children should be hidden by windows (SW_PARENTCLOSING)
1120 case QtWindows::CloseEvent:
1121 QWindowSystemInterface::handleCloseEvent(platformWindow->window());
1122 return true;
1123 case QtWindows::ThemeChanged: {
1124 return true;
1125 }
1126 case QtWindows::CompositionSettingsChanged:
1128 return true;
1129 case QtWindows::ActivateWindowEvent:
1130 if (platformWindow->window()->flags() & Qt::WindowDoesNotAcceptFocus) {
1131 *result = LRESULT(MA_NOACTIVATE);
1132 return true;
1133 }
1134#if QT_CONFIG(tabletevent)
1135 if (!d->m_tabletSupport.isNull())
1136 d->m_tabletSupport->notifyActivate();
1137#endif // QT_CONFIG(tabletevent)
1139 if (const QWindow *modalWindow = QGuiApplication::modalWindow()) {
1140 QWindowsWindow *platformWindow = QWindowsWindow::windowsWindowOf(modalWindow);
1141 Q_ASSERT(platformWindow);
1142 platformWindow->alertWindow();
1143 }
1144 break;
1145 case QtWindows::MouseActivateWindowEvent:
1146 case QtWindows::PointerActivateWindowEvent:
1147 if (platformWindow->window()->flags() & Qt::WindowDoesNotAcceptFocus) {
1148 *result = LRESULT(MA_NOACTIVATE);
1149 return true;
1150 }
1151 break;
1152#ifndef QT_NO_CONTEXTMENU
1153 case QtWindows::ContextMenu:
1154 return handleContextMenuEvent(platformWindow->window(), msg);
1155#endif
1156 case QtWindows::WhatsThisEvent: {
1157#ifndef QT_NO_WHATSTHIS
1158 QWindowSystemInterface::handleEnterWhatsThisEvent();
1159 return true;
1160#endif
1161 } break;
1162 case QtWindows::DpiScaledSizeEvent:
1163 platformWindow->handleDpiScaledSize(wParam, lParam, result);
1164 return true;
1165 case QtWindows::DpiChangedEvent:
1166 platformWindow->handleDpiChanged(hwnd, wParam, lParam);
1167 return true;
1168 case QtWindows::DpiChangedAfterParentEvent:
1169 platformWindow->handleDpiChangedAfterParent(hwnd);
1170 return true;
1171#if QT_CONFIG(sessionmanager)
1172 case QtWindows::QueryEndSessionApplicationEvent: {
1173 QWindowsSessionManager *sessionManager = platformSessionManager();
1174 if (sessionManager->isActive()) { // bogus message from windows
1175 *result = sessionManager->wasCanceled() ? 0 : 1;
1176 return true;
1177 }
1178
1179 sessionManager->setActive(true);
1180 sessionManager->blocksInteraction();
1181 sessionManager->clearCancellation();
1182
1183 auto *qGuiAppPriv = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(qApp));
1184 qGuiAppPriv->commitData();
1185
1186 if (lParam & ENDSESSION_LOGOFF)
1187 fflush(nullptr);
1188
1189 *result = sessionManager->wasCanceled() ? 0 : 1;
1190 return true;
1191 }
1192 case QtWindows::EndSessionApplicationEvent: {
1193 QWindowsSessionManager *sessionManager = platformSessionManager();
1194
1195 sessionManager->setActive(false);
1196 sessionManager->allowsInteraction();
1197 const bool endsession = wParam != 0;
1198
1199 // we receive the message for each toplevel window included internal hidden ones,
1200 // but the aboutToQuit signal should be emitted only once.
1201 auto *qGuiAppPriv = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(qApp));
1202 if (endsession && !qGuiAppPriv->aboutToQuitEmitted) {
1203 qGuiAppPriv->aboutToQuitEmitted = true;
1204 int index = QGuiApplication::staticMetaObject.indexOfSignal("aboutToQuit()");
1205 qApp->qt_metacall(QMetaObject::InvokeMetaMethod, index, nullptr);
1206 // since the process will be killed immediately quit() has no real effect
1207 QGuiApplication::quit();
1208 }
1209 return true;
1210 }
1211#endif // !defined(QT_NO_SESSIONMANAGER)
1212 case QtWindows::TaskbarButtonCreated:
1213 // Apply application badge if this is the first time we have a taskbar
1214 // button, or after Explorer restart.
1216 break;
1217 default:
1218 break;
1219 }
1220 return false;
1221}
1222
1223/* Compress activation events. If the next focus window is already known
1224 * at the time the current one receives focus-out, pass that to
1225 * QWindowSystemInterface instead of sending 0 and ignore its consecutive
1226 * focus-in event.
1227 * This helps applications that do handling in focus-out events. */
1228void QWindowsContext::handleFocusEvent(QtWindows::WindowsEventType et,
1229 QWindowsWindow *platformWindow)
1230{
1231 QWindow *nextActiveWindow = nullptr;
1232 if (et == QtWindows::FocusInEvent) {
1233 QWindow *topWindow = QWindowsWindow::topLevelOf(platformWindow->window());
1234 QWindow *modalWindow = nullptr;
1235 if (QGuiApplicationPrivate::instance()->isWindowBlocked(topWindow, &modalWindow) && topWindow != modalWindow) {
1236 modalWindow->requestActivate();
1237 return;
1238 }
1239 // QTBUG-32867: Invoking WinAPI SetParent() can cause focus-in for the
1240 // window which is not desired for native child widgets.
1242 QWindow *currentFocusWindow = QGuiApplication::focusWindow();
1243 if (currentFocusWindow && currentFocusWindow != platformWindow->window()) {
1244 currentFocusWindow->requestActivate();
1245 return;
1246 }
1247 }
1248 nextActiveWindow = platformWindow->window();
1249 } else {
1250 // Focus out: Is the next window known and different
1251 // from the receiving the focus out.
1252 if (const HWND nextActiveHwnd = GetFocus())
1253 if (QWindowsWindow *nextActivePlatformWindow = findClosestPlatformWindow(nextActiveHwnd))
1254 if (nextActivePlatformWindow != platformWindow)
1255 nextActiveWindow = nextActivePlatformWindow->window();
1256 }
1257 if (nextActiveWindow != d->m_lastActiveWindow) {
1258 d->m_lastActiveWindow = nextActiveWindow;
1259 QWindowSystemInterface::handleFocusWindowChanged(nextActiveWindow, Qt::ActiveWindowFocusReason);
1260 }
1261}
1262
1263#ifndef QT_NO_CONTEXTMENU
1264bool QWindowsContext::handleContextMenuEvent(QWindow *window, const MSG &msg)
1265{
1266 const QInputDevice *device = QInputDevice::primaryKeyboard();
1267 QPoint globalPos;
1268 QPoint pos;
1269 if (msg.lParam != int(0xffffffff)) {
1270 device = QPointingDevice::primaryPointingDevice();
1271 globalPos.setX(msg.pt.x);
1272 globalPos.setY(msg.pt.y);
1273 pos = QWindowsGeometryHint::mapFromGlobal(msg.hwnd, globalPos);
1274
1275 RECT clientRect;
1276 if (GetClientRect(msg.hwnd, &clientRect)) {
1277 if (pos.x() < clientRect.left || pos.x() >= clientRect.right ||
1278 pos.y() < clientRect.top || pos.y() >= clientRect.bottom)
1279 {
1280 // This is the case that user has right clicked in the window's caption,
1281 // We should call DefWindowProc() to display a default shortcut menu
1282 // instead of sending a Qt window system event.
1283 return false;
1284 }
1285 }
1286 }
1287
1288 QWindowSystemInterface::handleContextMenuEvent(window, device, pos, globalPos,
1289 keyMapper()->queryKeyboardModifiers());
1290 return true;
1291}
1292#endif
1293
1294void QWindowsContext::handleExitSizeMove(QWindow *window)
1295{
1296 // Windows can be moved/resized by:
1297 // 1) User moving a window by dragging the title bar: Causes a sequence
1298 // of WM_NCLBUTTONDOWN, WM_NCMOUSEMOVE but no WM_NCLBUTTONUP,
1299 // leaving the left mouse button 'pressed'
1300 // 2) User choosing Resize/Move from System menu and using mouse/cursor keys:
1301 // No mouse events are received
1302 // 3) Programmatically via QSizeGrip calling QPlatformWindow::startSystemResize/Move():
1303 // Mouse is left in pressed state after press on size grip (inside window),
1304 // no further mouse events are received
1305 // For cases 1,3, intercept WM_EXITSIZEMOVE to sync the buttons.
1306 const Qt::MouseButtons currentButtons = QWindowsPointerHandler::queryMouseButtons();
1307 const Qt::MouseButtons appButtons = QGuiApplication::mouseButtons();
1308 if (currentButtons == appButtons)
1309 return;
1310 const Qt::KeyboardModifiers keyboardModifiers = keyMapper()->queryKeyboardModifiers();
1311 const QPoint globalPos = QWindowsCursor::mousePosition();
1312 const QPlatformWindow *platWin = window->handle();
1313 const QPoint localPos = platWin->mapFromGlobal(globalPos);
1314 const QEvent::Type type = platWin->geometry().contains(globalPos)
1315 ? QEvent::MouseButtonRelease : QEvent::NonClientAreaMouseButtonRelease;
1316 for (Qt::MouseButton button : {Qt::LeftButton, Qt::RightButton, Qt::MiddleButton}) {
1317 if (appButtons.testFlag(button) && !currentButtons.testFlag(button)) {
1318 QWindowSystemInterface::handleMouseEvent(window, localPos, globalPos,
1319 currentButtons, button, type, keyboardModifiers);
1320 }
1321 }
1322 d->m_pointerHandler.clearEvents();
1323}
1324
1326{
1327 return d->m_asyncExpose;
1328}
1329
1331{
1332 d->m_asyncExpose = value;
1333}
1334
1335DWORD QWindowsContext::readAdvancedExplorerSettings(const wchar_t *subKey, DWORD defaultValue)
1336{
1337 const auto advancedSettings = QWinRegistryKey(
1338 HKEY_CURRENT_USER, LR"(Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced)");
1339 return advancedSettings.value<DWORD>(subKey).value_or(defaultValue);
1340}
1341
1342static inline bool isEmptyRect(const RECT &rect)
1343{
1344 return rect.right - rect.left == 0 && rect.bottom - rect.top == 0;
1345}
1346
1347static inline QMargins marginsFromRects(const RECT &frame, const RECT &client)
1348{
1349 return QMargins(client.left - frame.left, client.top - frame.top,
1350 frame.right - client.right, frame.bottom - client.bottom);
1351}
1352
1353static RECT rectFromNcCalcSize(UINT message, WPARAM wParam, LPARAM lParam, int n)
1354{
1355 RECT result = {0, 0, 0, 0};
1356 if (message == WM_NCCALCSIZE && wParam)
1357 result = reinterpret_cast<const NCCALCSIZE_PARAMS *>(lParam)->rgrc[n];
1358 return result;
1359}
1360
1361static inline bool isMinimized(HWND hwnd)
1362{
1363 WINDOWPLACEMENT windowPlacement;
1364 windowPlacement.length = sizeof(WINDOWPLACEMENT);
1365 return GetWindowPlacement(hwnd, &windowPlacement) && windowPlacement.showCmd == SW_SHOWMINIMIZED;
1366}
1367
1368static inline bool isTopLevel(HWND hwnd)
1369{
1370 return (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CHILD) == 0;
1371}
1372
1373/*!
1374 \brief Windows functions for actual windows.
1375
1376 There is another one for timers, sockets, etc in
1377 QEventDispatcherWin32.
1378
1379*/
1380
1381LRESULT QT_WIN_CALLBACK qWindowsWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
1382{
1383 LRESULT result;
1384 const QtWindows::WindowsEventType et = windowsEventType(message, wParam, lParam);
1385 QWindowsWindow *platformWindow = nullptr;
1386 const RECT ncCalcSizeFrame = rectFromNcCalcSize(message, wParam, lParam, 0);
1387 const bool handled = QWindowsContext::instance()->windowsProc(hwnd, message, et, wParam, lParam, &result, &platformWindow);
1388 if (QWindowsContext::verbose > 1 && lcQpaEvents().isDebugEnabled()) {
1389 if (const char *eventName = QWindowsGuiEventDispatcher::windowsMessageName(message)) {
1390 qCDebug(lcQpaEvents).nospace() << "EVENT: hwd=" << hwnd << ' ' << eventName
1391 << " msg=0x" << Qt::hex << message << " et=0x" << et << Qt::dec << " wp="
1392 << int(wParam) << " at " << GET_X_LPARAM(lParam) << ','
1393 << GET_Y_LPARAM(lParam) << " handled=" << handled;
1394 }
1395 }
1396 if (!handled)
1397 result = DefWindowProc(hwnd, message, wParam, lParam);
1398
1399 // Capture WM_NCCALCSIZE on top level windows and obtain the window margins by
1400 // subtracting the rectangles before and after processing. This will correctly
1401 // capture client code overriding the message and allow for per-monitor margins
1402 // for High DPI (QTBUG-53255, QTBUG-40578).
1403 if (message == WM_NCCALCSIZE && !isEmptyRect(ncCalcSizeFrame) && isTopLevel(hwnd) && !isMinimized(hwnd)) {
1404 const QMargins margins =
1405 marginsFromRects(ncCalcSizeFrame, rectFromNcCalcSize(message, wParam, lParam, 0));
1406 if (margins.left() >= 0) {
1407 if (platformWindow) {
1408 qCDebug(lcQpaWindow) << __FUNCTION__ << "WM_NCCALCSIZE for" << hwnd << margins;
1409 platformWindow->setFullFrameMargins(margins);
1410 } else {
1411 const QSharedPointer<QWindowCreationContext> ctx = QWindowsContext::instance()->windowCreationContext();
1412 if (!ctx.isNull())
1413 ctx->margins = margins;
1414 }
1415 }
1416 }
1417 return result;
1418}
1419
1420
1421static inline QByteArray nativeEventType() { return QByteArrayLiteral("windows_generic_MSG"); }
1422
1423// Send to QAbstractEventDispatcher
1424bool QWindowsContext::filterNativeEvent(MSG *msg, LRESULT *result)
1425{
1426 QAbstractEventDispatcher *dispatcher = QAbstractEventDispatcher::instance();
1427 qintptr filterResult = 0;
1428 if (dispatcher && dispatcher->filterNativeEvent(nativeEventType(), msg, &filterResult)) {
1429 *result = LRESULT(filterResult);
1430 return true;
1431 }
1432 return false;
1433}
1434
1435// Send to QWindowSystemInterface
1436bool QWindowsContext::filterNativeEvent(QWindow *window, MSG *msg, LRESULT *result)
1437{
1438 qintptr filterResult = 0;
1439 if (QWindowSystemInterface::handleNativeEvent(window, nativeEventType(), msg, &filterResult)) {
1440 *result = LRESULT(filterResult);
1441 return true;
1442 }
1443 return false;
1444}
1445
1446QT_END_NAMESPACE
\inmodule QtCore\reentrant
Definition qpoint.h:30
Singleton container for all relevant information.
QSharedPointer< QWindowCreationContext > windowCreationContext() const
QWindowsScreenManager & screenManager()
QWindowsWindow * findClosestPlatformWindow(HWND) const
QWindow * findWindow(HWND) const
bool asyncExpose() const
void addWindow(HWND, QWindowsWindow *w)
static bool systemParametersInfoForScreen(unsigned action, unsigned param, void *out, const QPlatformScreen *screen=nullptr)
static bool setProcessDpiAwareness(QtWindows::DpiAwareness dpiAwareness)
HDC displayContext() const
QWindowsTabletSupport * tabletSupport() const
static bool systemParametersInfoForWindow(unsigned action, unsigned param, void *out, const QPlatformWindow *win=nullptr)
static void setTabletAbsoluteRange(int a)
QWindowsDirectManipulation * directManipulation() const
QWindowsWindow * findPlatformWindowAt(HWND parent, const QPoint &screenPoint, unsigned cwex_flags) const
bool initTouch(unsigned integrationOptions)
HWND createDummyWindow(const QString &classNameIn, const wchar_t *windowName, WNDPROC wndProc=nullptr, DWORD style=WS_OVERLAPPED)
Convenience to create a non-visible, message-only dummy window for example used as clipboard watcher ...
void setAsyncExpose(bool value)
QSharedPointer< QWindowCreationContext > setWindowCreationContext(const QSharedPointer< QWindowCreationContext > &ctx)
bool windowsProc(HWND hwnd, UINT message, QtWindows::WindowsEventType et, WPARAM wParam, LPARAM lParam, LRESULT *result, QWindowsWindow **platformWindowPtr)
Main windows procedure registered for windows.
unsigned systemInfo() const
static QtWindows::DpiAwareness processDpiAwareness()
QWindowsWindow * findPlatformWindow(HWND) const
QWindow * keyGrabber() const
QWindowsWindow * findPlatformWindow(const QWindowsMenuBar *mb) const
QWindow * windowUnderMouse() const
QPlatformKeyMapper * keyMapper() const
bool useRTLExtensions() const
static bool systemParametersInfo(unsigned action, unsigned param, void *out, unsigned dpi=0)
QWindowsMimeRegistry & mimeConverter() const
static bool isSessionLocked()
int screenDepth() const
bool initPowerNotificationHandler()
HandleBaseWindowHash & windows()
static QWindowsContext * instance()
void setDetectAltGrModifier(bool a)
Platform cursor implementation.
static bool hasOverrideCursor()
static void enforceOverrideCursor()
Windows Input context implementation.
static void setWindowsImeEnabled(QWindowsWindow *platformWindow, bool enabled)
static QWindowsIntegration * instance()
Translates Windows keys to QWindowSystemInterface events.
Windows native menu bar.
Manages the list of QWindowsMimeConverter instances.
Manages a list of QWindowsScreen.
Tablet support for Windows.
static QWindowsTheme * instance()
Raster or OpenGL Window.
void alertWindow(int durationMs=0)
bool testFlag(unsigned f) const
void setFlag(unsigned f) const
void clearFlag(unsigned f) const
static void settingsChanged()
static const char * embeddedNativeParentHandleProperty
QWindowsMenuBar * menuBar() const
bool frameStrutEventsEnabled() const override
Reimplement this method to return whether frame strut events are enabled.
@ WithinSetParent
Automatic mouse capture on button press.
void handleCompositionSettingsChanged()
WindowsEventType
Enumerations for WM_XX events.
@ PointerActivateWindowEvent
@ InputMethodEndCompositionEvent
@ ShowEventOnParentRestoring
@ InputMethodCompositionEvent
@ InputMethodOpenCandidateWindowEvent
@ MouseActivateWindowEvent
@ DpiChangedAfterParentEvent
@ InputMethodStartCompositionEvent
@ CompositionSettingsChanged
@ InputMethodCloseCandidateWindowEvent
@ DirectManipulationHitTestEvent
@ AccessibleObjectFromWindowRequest
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
#define WM_TOUCH
#define DPI_AWARENESS_CONTEXT_UNAWARE
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
#define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE
#define DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED
static bool isTopLevel(HWND hwnd)
#define LANG_SYRIAC
static RECT rectFromNcCalcSize(UINT message, WPARAM wParam, LPARAM lParam, int n)
static bool enableNonClientDpiScaling(HWND hwnd)
static bool isInputMessage(UINT m)
static DPI_AWARENESS_CONTEXT qtDpiAwarenessToDpiAwarenessContext(QtWindows::DpiAwareness dpiAwareness)
static bool isMinimized(HWND hwnd)
static QMargins marginsFromRects(const RECT &frame, const RECT &client)
static bool useRTL_Extensions()
static bool sessionManagerInteractionBlocked()
static QWindowsInputContext * windowsInputContext()
static QtWindows::DpiAwareness dpiAwarenessContextToQtDpiAwareness(DPI_AWARENESS_CONTEXT context)
static QByteArray nativeEventType()
static bool isEmptyRect(const RECT &rect)
static bool findPlatformWindowHelper(const POINT &screenPoint, unsigned cwexFlags, const QWindowsContext *context, HWND *hwnd, QWindowsWindow **result)
Find a child window at a screen point.
const HRESULT m_oleInitializeResult
QWindowsKeyMapper m_keyMapper
QWindowsWindowClassRegistry m_windowClassRegistry
QWindowsPointerHandler m_pointerHandler
QUniqueHDCHandle m_displayContext
QWindowsScreenManager m_screenManager
QWindowsMimeRegistry m_mimeConverter
QWindowsContext::HandleBaseWindowHash m_windows
QSharedPointer< QWindowCreationContext > m_creationContext