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
qguiapplication.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
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
7
8#include "private/qguiapplication_p.h"
9#include "private/qabstractfileiconprovider_p.h"
10#include <qpa/qplatformintegrationfactory_p.h>
11#include "private/qevent_p.h"
12#include "private/qeventpoint_p.h"
13#include "private/qiconloader_p.h"
14#include "qfont.h"
16#include <qpa/qplatformfontdatabase.h>
17#include <qpa/qplatformwindow.h>
18#include <qpa/qplatformnativeinterface.h>
19#include <qpa/qplatformtheme.h>
20#include <qpa/qplatformintegration.h>
21#include <qpa/qplatformkeymapper.h>
22
23#include <QtCore/QAbstractEventDispatcher>
24#include <QtCore/QFileInfo>
25#include <QtCore/QStandardPaths>
26#include <QtCore/QVariant>
27#include <QtCore/private/qcoreapplication_p.h>
28#include <QtCore/private/qabstracteventdispatcher_p.h>
29#include <QtCore/private/qminimalflatset_p.h>
30#include <QtCore/qmutex.h>
31#include <QtCore/private/qthread_p.h>
32#include <QtCore/private/qlocking_p.h>
33#include <QtCore/private/qflatmap_p.h>
34#include <QtCore/qdir.h>
35#include <QtCore/qlibraryinfo.h>
36#include <QtCore/private/qnumeric_p.h>
37#include <QtDebug>
38#if QT_CONFIG(accessibility)
39#include "qaccessible.h"
40#include <QtGui/private/qaccessiblewindow_p.h>
41#endif
42#include <qpalette.h>
43#include <qscreen.h>
45#include <private/qcolortrclut_p.h>
46#include <private/qscreen_p.h>
47
48#include <QtGui/qgenericpluginfactory.h>
49#include <QtGui/qstylehints.h>
50#include <QtGui/private/qstylehints_p.h>
51#include <QtGui/qinputmethod.h>
52#include <QtGui/qpixmapcache.h>
53#include <qpa/qplatforminputcontext.h>
54#include <qpa/qplatforminputcontext_p.h>
55
56#include <qpa/qwindowsysteminterface.h>
57#include <qpa/qwindowsysteminterface_p.h>
58#include "private/qwindow_p.h"
59#include "private/qicon_p.h"
60#include "private/qcursor_p.h"
61#if QT_CONFIG(opengl)
62# include "private/qopenglcontext_p.h"
63#endif
64#include "private/qinputdevicemanager_p.h"
65#include "private/qinputmethod_p.h"
66#include "private/qpointingdevice_p.h"
67
68#include <qpa/qplatformthemefactory_p.h>
69
70#if QT_CONFIG(draganddrop)
71#include <qpa/qplatformdrag.h>
72#include <private/qdnd_p.h>
73#endif
74
75#ifndef QT_NO_CURSOR
76#include <qpa/qplatformcursor.h>
77#endif
78
79#include <QtGui/QPixmap>
80
81#ifndef QT_NO_CLIPBOARD
82#include <QtGui/QClipboard>
83#endif
84
85#if QT_CONFIG(library)
86#include <QtCore/QLibrary>
87#endif
88
89#if defined(Q_OS_APPLE)
90# include "private/qcore_mac_p.h"
91#elif defined(Q_OS_WIN)
92# include <QtCore/qt_windows.h>
93# include <QtCore/QLibraryInfo>
94#endif // Q_OS_WIN
95
96#ifdef Q_OS_WASM
97#include <emscripten.h>
98#endif
99
100#if QT_CONFIG(vulkan)
101#include <private/qvulkandefaultinstance_p.h>
102#endif
103
104#if QT_CONFIG(thread)
105#include <QtCore/QThreadPool>
106#endif
107
108#include <qtgui_tracepoints_p.h>
109
110#include <private/qtools_p.h>
111
112#include <limits>
113
115
116Q_LOGGING_CATEGORY(lcPopup, "qt.gui.popup");
117Q_LOGGING_CATEGORY(lcVirtualKeyboard, "qt.gui.virtualkeyboard");
118
119using namespace Qt::StringLiterals;
120using namespace QtMiscUtils;
121
122// Helper macro for static functions to check on the existence of the application class.
123#define CHECK_QAPP_INSTANCE(...)
124 if (Q_LIKELY(QCoreApplication::instance())) {
125 } else {
126 qWarning("Must construct a QGuiApplication first.");
127 return __VA_ARGS__;
128 }
129
132
133Q_CONSTINIT Qt::MouseButtons QGuiApplicationPrivate::mouse_buttons = Qt::NoButton;
134Q_CONSTINIT Qt::KeyboardModifiers QGuiApplicationPrivate::modifier_buttons = Qt::NoModifier;
135
136Q_CONSTINIT QGuiApplicationPrivate::QLastCursorPosition QGuiApplicationPrivate::lastCursorPosition;
137
138Q_CONSTINIT QWindow *QGuiApplicationPrivate::currentMouseWindow = nullptr;
139
140Q_CONSTINIT QString QGuiApplicationPrivate::styleOverride;
141
142Q_CONSTINIT Qt::ApplicationState QGuiApplicationPrivate::applicationState = Qt::ApplicationInactive;
143
144Q_CONSTINIT Qt::HighDpiScaleFactorRoundingPolicy QGuiApplicationPrivate::highDpiScaleFactorRoundingPolicy =
145 Qt::HighDpiScaleFactorRoundingPolicy::PassThrough;
146
147Q_CONSTINIT QPointer<QWindow> QGuiApplicationPrivate::currentDragWindow;
148
149Q_CONSTINIT QList<QGuiApplicationPrivate::TabletPointData> QGuiApplicationPrivate::tabletDevicePoints; // TODO remove
150
151Q_CONSTINIT QPlatformIntegration *QGuiApplicationPrivate::platform_integration = nullptr;
152Q_CONSTINIT QPlatformTheme *QGuiApplicationPrivate::platform_theme = nullptr;
153
154Q_CONSTINIT QList<QObject *> QGuiApplicationPrivate::generic_plugin_list;
155
160
162
163Q_CONSTINIT QIcon *QGuiApplicationPrivate::app_icon = nullptr;
164
165Q_CONSTINIT QString *QGuiApplicationPrivate::platform_name = nullptr;
166Q_CONSTINIT QString *QGuiApplicationPrivate::displayName = nullptr;
167Q_CONSTINIT QString *QGuiApplicationPrivate::desktopFileName = nullptr;
168
169Q_CONSTINIT QPalette *QGuiApplicationPrivate::app_pal = nullptr; // default application palette
170
171Q_CONSTINIT Qt::MouseButton QGuiApplicationPrivate::mousePressButton = Qt::NoButton;
172
175
176Q_CONSTINIT QWindow *QGuiApplicationPrivate::currentMousePressWindow = nullptr;
177
178Q_CONSTINIT static Qt::LayoutDirection layout_direction = Qt::LayoutDirectionAuto;
179Q_CONSTINIT static Qt::LayoutDirection effective_layout_direction = Qt::LeftToRight;
180Q_CONSTINIT static bool force_reverse = false;
181
182Q_DECL_DEPRECATED_X("Use QGuiApplicationPrivate::instance() instead")
183Q_CONSTINIT QGuiApplicationPrivate *QGuiApplicationPrivate::self = nullptr;
184
185Q_CONSTINIT int QGuiApplicationPrivate::m_fakeMouseSourcePointId = -1;
186
187#ifndef QT_NO_CLIPBOARD
188Q_CONSTINIT QClipboard *QGuiApplicationPrivate::qt_clipboard = nullptr;
189#endif
190
191Q_CONSTINIT QList<QScreen *> QGuiApplicationPrivate::screen_list;
192
193Q_CONSTINIT QWindowList QGuiApplicationPrivate::window_list;
194Q_CONSTINIT QWindowList QGuiApplicationPrivate::popup_list;
195Q_CONSTINIT const QWindow *QGuiApplicationPrivate::active_popup_on_press = nullptr;
196Q_CONSTINIT QWindow *QGuiApplicationPrivate::focus_window = nullptr;
197
198Q_CONSTINIT static QBasicMutex applicationFontMutex;
199Q_CONSTINIT QFont *QGuiApplicationPrivate::app_font = nullptr;
200Q_CONSTINIT QStyleHints *QGuiApplicationPrivate::styleHints = nullptr;
201Q_CONSTINIT bool QGuiApplicationPrivate::obey_desktop_settings = true;
202Q_CONSTINIT bool QGuiApplicationPrivate::popup_closed_on_press = false;
203
204Q_CONSTINIT QInputDeviceManager *QGuiApplicationPrivate::m_inputDeviceManager = nullptr;
205
206Q_CONSTINIT qreal QGuiApplicationPrivate::m_maxDevicePixelRatio = 0.0;
207Q_CONSTINIT QBasicAtomicInt QGuiApplicationPrivate::m_primaryScreenDpis = Q_BASIC_ATOMIC_INITIALIZER(0);
208
209Q_CONSTINIT static qreal fontSmoothingGamma = 1.7;
210
211Q_CONSTINIT bool QGuiApplicationPrivate::quitOnLastWindowClosed = true;
212
213extern void qRegisterGuiVariant();
214#if QT_CONFIG(animation)
215extern void qRegisterGuiGetInterpolator();
216#endif
217
219{
220 return force_reverse ^
221 (QGuiApplication::tr("QT_LAYOUT_DIRECTION",
222 "Translate this string to the string 'LTR' in left-to-right"
223 " languages or to 'RTL' in right-to-left languages (such as Hebrew"
224 " and Arabic) to get proper widget layout.") == "RTL"_L1);
225}
226
227static void initFontUnlocked()
228{
229 if (!QGuiApplicationPrivate::app_font) {
230 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
231 if (const QFont *font = theme->font(QPlatformTheme::SystemFont))
232 QGuiApplicationPrivate::app_font = new QFont(*font);
233 }
234 if (!QGuiApplicationPrivate::app_font)
235 QGuiApplicationPrivate::app_font =
236 new QFont(QGuiApplicationPrivate::platformIntegration()->fontDatabase()->defaultFont());
237}
238
239static inline void clearFontUnlocked()
240{
241 delete QGuiApplicationPrivate::app_font;
242 QGuiApplicationPrivate::app_font = nullptr;
243}
244
245static void initThemeHints()
246{
247 mouseDoubleClickDistance = QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::MouseDoubleClickDistance).toInt();
248 touchDoubleTapDistance = QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::TouchDoubleTapDistance).toInt();
249}
250
251#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
252static bool checkNeedPortalSupport()
253{
254#if QT_CONFIG(dbus)
255 return QFileInfo::exists("/.flatpak-info"_L1) || qEnvironmentVariableIsSet("SNAP");
256#else
257 return false;
258#endif // QT_CONFIG(dbus)
259}
260#endif
261
262// Using aggregate initialization instead of ctor so we can have a POD global static
263#define Q_WINDOW_GEOMETRY_SPECIFICATION_INITIALIZER { Qt::TopLeftCorner, -1, -1, -1, -1 }
264
265// Geometry specification for top level windows following the convention of the
266// -geometry command line arguments in X11 (see XParseGeometry).
268{
269 static QWindowGeometrySpecification fromArgument(const QByteArray &a);
270 void applyTo(QWindow *window) const;
271
275 int width;
277};
278
279// Parse a token of a X11 geometry specification "200x100+10-20".
280static inline int nextGeometryToken(const QByteArray &a, int &pos, char *op)
281{
282 *op = 0;
283 const qsizetype size = a.size();
284 if (pos >= size)
285 return -1;
286
287 *op = a.at(pos);
288 if (*op == '+' || *op == '-' || *op == 'x')
289 pos++;
290 else if (isAsciiDigit(*op))
291 *op = 'x'; // If it starts with a digit, it is supposed to be a width specification.
292 else
293 return -1;
294
295 const int numberPos = pos;
296 for ( ; pos < size && isAsciiDigit(a.at(pos)); ++pos) ;
297
298 bool ok;
299 const int result = a.mid(numberPos, pos - numberPos).toInt(&ok);
300 return ok ? result : -1;
301}
302
304{
306 int pos = 0;
307 for (int i = 0; i < 4; ++i) {
308 char op;
309 const int value = nextGeometryToken(a, pos, &op);
310 if (value < 0)
311 break;
312 switch (op) {
313 case 'x':
314 (result.width >= 0 ? result.height : result.width) = value;
315 break;
316 case '+':
317 case '-':
318 if (result.xOffset >= 0) {
319 result.yOffset = value;
320 if (op == '-')
321 result.corner = result.corner == Qt::TopRightCorner ? Qt::BottomRightCorner : Qt::BottomLeftCorner;
322 } else {
323 result.xOffset = value;
324 if (op == '-')
325 result.corner = Qt::TopRightCorner;
326 }
327 }
328 }
329 return result;
330}
331
332void QWindowGeometrySpecification::applyTo(QWindow *window) const
333{
334 QRect windowGeometry = window->frameGeometry();
335 QSize size = windowGeometry.size();
336 if (width >= 0 || height >= 0) {
337 const QSize windowMinimumSize = window->minimumSize();
338 const QSize windowMaximumSize = window->maximumSize();
339 if (width >= 0)
340 size.setWidth(qBound(windowMinimumSize.width(), width, windowMaximumSize.width()));
341 if (height >= 0)
342 size.setHeight(qBound(windowMinimumSize.height(), height, windowMaximumSize.height()));
343 window->resize(size);
344 }
345 if (xOffset >= 0 || yOffset >= 0) {
346 const QRect availableGeometry = window->screen()->virtualGeometry();
347 QPoint topLeft = windowGeometry.topLeft();
348 if (xOffset >= 0) {
349 topLeft.setX(corner == Qt::TopLeftCorner || corner == Qt::BottomLeftCorner ?
350 xOffset :
351 qMax(availableGeometry.right() - size.width() - xOffset, availableGeometry.left()));
352 }
353 if (yOffset >= 0) {
354 topLeft.setY(corner == Qt::TopLeftCorner || corner == Qt::TopRightCorner ?
355 yOffset :
356 qMax(availableGeometry.bottom() - size.height() - yOffset, availableGeometry.top()));
357 }
358 window->setFramePosition(topLeft);
359 }
360}
361
363
364/*!
365 \macro qGuiApp
366 \relates QGuiApplication
367
368 A global pointer referring to the unique application object.
369 Only valid for use when that object is a QGuiApplication.
370
371 \sa QCoreApplication::instance(), qApp
372*/
373
374/*!
375 \class QGuiApplication
376 \brief The QGuiApplication class manages the GUI application's control
377 flow and main settings.
378
379 \inmodule QtGui
380 \since 5.0
381
382 QGuiApplication contains the main event loop, where all events from the window
383 system and other sources are processed and dispatched. It also handles the
384 application's initialization and finalization, and provides session management.
385 In addition, QGuiApplication handles most of the system-wide and application-wide
386 settings.
387
388 For any GUI application using Qt, there is precisely \b one QGuiApplication
389 object no matter whether the application has 0, 1, 2 or more windows at
390 any given time. For non-GUI Qt applications, use QCoreApplication instead,
391 as it does not depend on the Qt GUI module. For QWidget based Qt applications,
392 use QApplication instead, as it provides some functionality needed for creating
393 QWidget instances.
394
395 The QGuiApplication object is accessible through the instance() function, which
396 returns a pointer equivalent to the global \l qApp pointer.
397
398 QGuiApplication's main areas of responsibility are:
399 \list
400 \li It initializes the application with the user's desktop settings,
401 such as palette(), font() and styleHints(). It keeps
402 track of these properties in case the user changes the desktop
403 globally, for example, through some kind of control panel.
404
405 \li It performs event handling, meaning that it receives events
406 from the underlying window system and dispatches them to the
407 relevant widgets. You can send your own events to windows by
408 using sendEvent() and postEvent().
409
410 \li It parses common command line arguments and sets its internal
411 state accordingly. See the \l{QGuiApplication::QGuiApplication()}
412 {constructor documentation} below for more details.
413
414 \li It provides localization of strings that are visible to the
415 user via translate().
416
417 \li It provides some magical objects like the clipboard().
418
419 \li It knows about the application's windows. You can ask which
420 window is at a certain position using topLevelAt(), get a list of
421 topLevelWindows(), etc.
422
423 \li It manages the application's mouse cursor handling, see
424 setOverrideCursor()
425
426 \li It provides support for sophisticated \l{Session Management}
427 {session management}. This makes it possible for applications
428 to terminate gracefully when the user logs out, to cancel a
429 shutdown process if termination isn't possible and even to
430 preserve the entire application's state for a future session.
431 See isSessionRestored(), sessionId() and commitDataRequest() and
432 saveStateRequest() for details.
433 \endlist
434
435 Since the QGuiApplication object does so much initialization, it \e{must} be
436 created before any other objects related to the user interface are created.
437 QGuiApplication also deals with common command line arguments. Hence, it is
438 usually a good idea to create it \e before any interpretation or
439 modification of \c argv is done in the application itself.
440
441 \table
442 \header
443 \li{2,1} Groups of functions
444
445 \row
446 \li System settings
447 \li desktopSettingsAware(),
448 setDesktopSettingsAware(),
449 styleHints(),
450 palette(),
451 setPalette(),
452 font(),
453 setFont().
454
455 \row
456 \li Event handling
457 \li exec(),
458 processEvents(),
459 exit(),
460 quit().
461 sendEvent(),
462 postEvent(),
463 sendPostedEvents(),
464 removePostedEvents(),
465 notify().
466
467 \row
468 \li Windows
469 \li allWindows(),
470 topLevelWindows(),
471 focusWindow(),
472 clipboard(),
473 topLevelAt().
474
475 \row
476 \li Advanced cursor handling
477 \li overrideCursor(),
478 setOverrideCursor(),
479 restoreOverrideCursor().
480
481 \row
482 \li Session management
483 \li isSessionRestored(),
484 sessionId(),
485 commitDataRequest(),
486 saveStateRequest().
487
488 \row
489 \li Miscellaneous
490 \li startingUp(),
491 closingDown().
492 \endtable
493
494 \sa QCoreApplication, QAbstractEventDispatcher, QEventLoop
495*/
496
497/*!
498 \class QGuiApplicationPrivate
499 \inmodule QtGui
500 \internal
501*/
502
503/*!
504 Initializes the window system and constructs an application object with
505 \a argc command line arguments in \a argv.
506
507 \warning The data referred to by \a argc and \a argv must stay valid for
508 the entire lifetime of the QGuiApplication object. In addition, \a argc must
509 be greater than zero and \a argv must contain at least one valid character
510 string.
511
512 The global \c qApp pointer refers to this application object. Only one
513 application object should be created.
514
515 This application object must be constructed before any \l{QPaintDevice}
516 {paint devices} (including pixmaps, bitmaps etc.).
517
518 \note \a argc and \a argv might be changed as Qt removes command line
519 arguments that it recognizes.
520
521 \section1 Supported Command Line Options
522
523 All Qt programs automatically support a set of command-line options that
524 allow modifying the way Qt will interact with the windowing system. Some of
525 the options are also accessible via environment variables, which are the
526 preferred form if the application can launch GUI sub-processes or other
527 applications (environment variables will be inherited by child processes).
528 When in doubt, use the environment variables.
529
530 The options currently supported are the following:
531 \list
532
533 \li \c{-platform} \e {platformName[:options]}, specifies the
534 \l{Qt Platform Abstraction} (QPA) plugin.
535
536 Overrides the \c QT_QPA_PLATFORM environment variable.
537 \li \c{-platformpluginpath} \e path, specifies the path to platform
538 plugins.
539
540 Overrides the \c QT_QPA_PLATFORM_PLUGIN_PATH environment variable.
541
542 \li \c{-platformtheme} \e platformTheme, specifies the platform theme.
543
544 Overrides the \c QT_QPA_PLATFORMTHEME environment variable.
545
546 \li \c{-plugin} \e plugin, specifies additional plugins to load. The argument
547 may appear multiple times.
548
549 Concatenated with the plugins in the \c QT_QPA_GENERIC_PLUGINS environment
550 variable.
551
552 \li \c{-qmljsdebugger=}, activates the QML/JS debugger with a specified port.
553 The value must be of format \c{port:1234}\e{[,block]}, where
554 \e block is optional
555 and will make the application wait until a debugger connects to it.
556 \li \c {-qwindowgeometry} \e geometry, specifies window geometry for
557 the main window using the X11-syntax. For example:
558 \c {-qwindowgeometry 100x100+50+50}
559 \li \c {-qwindowicon}, sets the default window icon
560 \li \c {-qwindowtitle}, sets the title of the first window
561 \li \c{-reverse}, sets the application's layout direction to
562 Qt::RightToLeft. This option is intended to aid debugging and should
563 not be used in production. The default value is automatically detected
564 from the user's locale (see also QLocale::textDirection()).
565 \li \c{-session} \e session, restores the application from an earlier
566 \l{Session Management}{session}.
567 \endlist
568
569 The following standard command line options are available for X11:
570
571 \list
572 \li \c {-display} \e {hostname:screen_number}, switches displays on X11.
573
574 Overrides the \c DISPLAY environment variable.
575 \li \c {-geometry} \e geometry, same as \c {-qwindowgeometry}.
576 \endlist
577
578 \section1 Platform-Specific Arguments
579
580 You can specify platform-specific arguments for the \c{-platform} option.
581 Place them after the platform plugin name following a colon as a
582 comma-separated list. For example,
583 \c{-platform windows:dialogs=xp,fontengine=freetype}.
584
585 The following parameters are available for \c {-platform windows}:
586
587 \list
588 \li \c {altgr}, detect the key \c {AltGr} found on some keyboards as
589 Qt::GroupSwitchModifier (since Qt 5.12).
590 \li \c {darkmode=[0|1|2]} controls how Qt responds to the activation
591 of the \e{Dark Mode for applications} introduced in Windows 10
592 1903 (since Qt 5.15).
593
594 A value of 0 disables dark mode support.
595
596 A value of 1 causes Qt to switch the window borders to black
597 when \e{Dark Mode for applications} is activated and no High
598 Contrast Theme is in use. This is intended for applications
599 that implement their own theming.
600
601 A value of 2 will in addition cause the Windows Vista style to
602 be deactivated and switch to the Windows style using a
603 simplified palette in dark mode. This is currently
604 experimental pending the introduction of new style that
605 properly adapts to dark mode.
606
607 As of Qt 6.5, the default value is 2; to disable dark mode
608 support, set the value to 0 or 1.
609
610 \li \c {dialogs=[xp|none]}, \c xp uses XP-style native dialogs and
611 \c none disables them.
612
613 \li \c {fontengine=freetype}, uses the FreeType font engine.
614 \li \c {fontengine=gdi}, uses the legacy GDI-based
615 font database and defaults to using the GDI font
616 engine (which is otherwise only used for some font types
617 or font properties.) (Since Qt 6.8).
618 \li \c {menus=[native|none]}, controls the use of native menus.
619
620 Native menus are implemented using Win32 API and are simpler than
621 QMenu-based menus in for example that they do allow for placing
622 widgets on them or changing properties like fonts and do not
623 provide hover signals. They are mainly intended for Qt Quick.
624 By default, they will be used if the application is not an
625 instance of QApplication or for Qt Quick Controls 2
626 applications (since Qt 5.10).
627
628 \li \c {nocolorfonts} Turn off DirectWrite Color fonts
629 (since Qt 5.8).
630
631 \li \c {nodirectwrite} Turn off DirectWrite fonts (since Qt 5.8). This implicitly
632 also selects the GDI font engine.
633
634 \li \c {nomousefromtouch} Ignores mouse events synthesized
635 from touch events by the operating system.
636
637 \li \c {nowmpointer} Switches from Pointer Input Messages handling
638 to legacy mouse handling (since Qt 5.12).
639 \li \c {reverse} Activates Right-to-left mode (experimental).
640 Windows title bars will be shown accordingly in Right-to-left locales
641 (since Qt 5.13).
642 \li \c {tabletabsoluterange=<value>} Sets a value for mouse mode detection
643 of WinTab tablets (Legacy, since Qt 5.3).
644 \endlist
645
646 The following parameter is available for \c {-platform cocoa} (on macOS):
647
648 \list
649 \li \c {fontengine=freetype}, uses the FreeType font engine.
650 \endlist
651
652 For more information about the platform-specific arguments available for
653 embedded Linux platforms, see \l{Qt for Embedded Linux}.
654
655 \sa arguments(), QGuiApplication::platformName
656*/
657#ifdef Q_QDOC
658QGuiApplication::QGuiApplication(int &argc, char **argv)
659#else
660QGuiApplication::QGuiApplication(int &argc, char **argv, int)
661#endif
662 : QCoreApplication(*new QGuiApplicationPrivate(argc, argv))
663{
664 d_func()->init();
665
666 QCoreApplicationPrivate::eventDispatcher->startingUp();
667}
668
669/*!
670 \internal
671*/
672QGuiApplication::QGuiApplication(QGuiApplicationPrivate &p)
673 : QCoreApplication(p)
674{
675}
676
677/*!
678 Destructs the application.
679*/
680QGuiApplication::~QGuiApplication()
681{
682 Q_D(QGuiApplication);
683
684 qt_call_post_routines();
685
686 QGuiApplicationPrivate::destroyEventDispatcher();
687
688#ifndef QT_NO_CLIPBOARD
689 delete QGuiApplicationPrivate::qt_clipboard;
690 QGuiApplicationPrivate::qt_clipboard = nullptr;
691#endif
692
693#ifndef QT_NO_SESSIONMANAGER
694 delete d->session_manager;
695 d->session_manager = nullptr;
696#endif //QT_NO_SESSIONMANAGER
697
698 QGuiApplicationPrivate::clearPalette();
699 QFontDatabase::removeAllApplicationFonts();
700
701#ifndef QT_NO_CURSOR
702 d->cursor_list.clear();
703#endif
704
705#if QT_CONFIG(qtgui_threadpool)
706 // Synchronize and stop the gui thread pool threads.
707 QThreadPool *guiThreadPool = nullptr;
708 QT_TRY {
709 guiThreadPool = QGuiApplicationPrivate::qtGuiThreadPool();
710 } QT_CATCH (...) {
711 // swallow the exception, since destructors shouldn't throw
712 }
713 if (guiThreadPool) {
714 guiThreadPool->waitForDone();
715 delete guiThreadPool;
716 }
717#endif
718
719 delete QGuiApplicationPrivate::app_icon;
720 QGuiApplicationPrivate::app_icon = nullptr;
721 delete QGuiApplicationPrivate::platform_name;
722 QGuiApplicationPrivate::platform_name = nullptr;
723 delete QGuiApplicationPrivate::displayName;
724 QGuiApplicationPrivate::displayName = nullptr;
725 delete QGuiApplicationPrivate::m_inputDeviceManager;
726 QGuiApplicationPrivate::m_inputDeviceManager = nullptr;
727 delete QGuiApplicationPrivate::desktopFileName;
728 QGuiApplicationPrivate::desktopFileName = nullptr;
729 QGuiApplicationPrivate::mouse_buttons = Qt::NoButton;
730 QGuiApplicationPrivate::modifier_buttons = Qt::NoModifier;
731 QGuiApplicationPrivate::lastCursorPosition.reset();
732 QGuiApplicationPrivate::currentMousePressWindow = QGuiApplicationPrivate::currentMouseWindow = nullptr;
733 QGuiApplicationPrivate::applicationState = Qt::ApplicationInactive;
734 QGuiApplicationPrivate::highDpiScaleFactorRoundingPolicy = Qt::HighDpiScaleFactorRoundingPolicy::PassThrough;
735 QGuiApplicationPrivate::currentDragWindow = nullptr;
736 QGuiApplicationPrivate::tabletDevicePoints.clear();
737 QGuiApplicationPrivate::m_primaryScreenDpis.storeRelaxed(0);
738}
739
740QGuiApplicationPrivate::QGuiApplicationPrivate(int &argc, char **argv)
741 : QCoreApplicationPrivate(argc, argv),
742 inputMethod(nullptr),
743 lastTouchType(QEvent::TouchEnd)
744{
745 // Note: Not same as QCoreApplication::self
746 QT_IGNORE_DEPRECATIONS(QGuiApplicationPrivate::self = this;)
747
748 application_type = QCoreApplicationPrivate::Gui;
749#ifndef QT_NO_SESSIONMANAGER
750 is_session_restored = false;
751 is_saving_session = false;
752#endif
753}
754
755/*!
756 \property QGuiApplication::applicationDisplayName
757 \brief the user-visible name of this application
758 \since 5.0
759
760 This name is shown to the user, for instance in window titles.
761 It can be translated, if necessary.
762
763 If not set, the application display name defaults to the application name.
764
765 \sa applicationName
766*/
767void QGuiApplication::setApplicationDisplayName(const QString &name)
768{
769 if (!QGuiApplicationPrivate::displayName) {
770 QGuiApplicationPrivate::displayName = new QString(name);
771 if (qGuiApp) {
772 disconnect(qGuiApp, &QGuiApplication::applicationNameChanged,
773 qGuiApp, &QGuiApplication::applicationDisplayNameChanged);
774
775 if (*QGuiApplicationPrivate::displayName != applicationName())
776 emit qGuiApp->applicationDisplayNameChanged();
777 }
778 } else if (name != *QGuiApplicationPrivate::displayName) {
779 *QGuiApplicationPrivate::displayName = name;
780 if (qGuiApp)
781 emit qGuiApp->applicationDisplayNameChanged();
782 }
783}
784
785QString QGuiApplication::applicationDisplayName()
786{
787 return QGuiApplicationPrivate::displayName ? *QGuiApplicationPrivate::displayName : applicationName();
788}
789
790/*!
791 \property QGuiApplication::badgeNumber
792 \brief the number shown in the application's badge
793
794 Useful for providing feedback to the user about the number
795 of unread messages or similar.
796
797 The badge will be overlaid on the application's icon in the Dock
798 on \macos, the home screen icon on iOS, or the task bar on Windows
799 and Linux.
800
801 If the number is outside the range supported by the platform, the
802 number will be clamped to the supported range. If the number does
803 not fit within the badge, the number may be visually elided.
804
805 Setting the number to 0 will clear the badge. The default value is 0.
806
807 \since 6.5
808 \sa applicationName, applicationProgress
809*/
810qint64 QGuiApplication::badgeNumber() const
811{
812 Q_D(const QGuiApplication);
813 return d->badgeNumber;
814}
815
816void QGuiApplication::setBadgeNumber(qint64 number)
817{
818 Q_D(QGuiApplication);
819 // Always forward to the platform, even if unchanged, as some platforms
820 // (e.g. iOS) persist the badge across launches, and applications rely
821 // on setBadgeNumber(0) to clear a stale badge.
822 QGuiApplicationPrivate::platformIntegration()->setApplicationBadge(number);
823 if (d->badgeNumber == number)
824 return;
825 d->badgeNumber = number;
826 emit badgeNumberChanged(number);
827}
828
829/*!
830 \property QGuiApplication::desktopFileName
831 \brief the base name of the desktop entry for this application
832 \since 5.7
833
834 This is the file name, without the full path or the trailing ".desktop"
835 extension of the desktop entry that represents this application
836 according to the freedesktop desktop entry specification.
837
838 This property gives a precise indication of what desktop entry represents
839 the application and it is needed by the windowing system to retrieve
840 such information without resorting to imprecise heuristics.
841
842 The latest version of the freedesktop desktop entry specification can be obtained
843 \l{http://standards.freedesktop.org/desktop-entry-spec/latest/}{here}.
844*/
845void QGuiApplication::setDesktopFileName(const QString &name)
846{
847 if (!QGuiApplicationPrivate::desktopFileName)
848 QGuiApplicationPrivate::desktopFileName = new QString;
849 *QGuiApplicationPrivate::desktopFileName = name;
850 if (name.endsWith(QLatin1String(".desktop"))) { // ### Qt 7: remove
851 const QString filePath = QStandardPaths::locate(QStandardPaths::ApplicationsLocation, name);
852 if (!filePath.isEmpty()) {
853 qWarning("QGuiApplication::setDesktopFileName: the specified desktop file name "
854 "ends with .desktop. For compatibility reasons, the .desktop suffix will "
855 "be removed. Please specify a desktop file name without .desktop suffix");
856 (*QGuiApplicationPrivate::desktopFileName).chop(8);
857 }
858 }
859}
860
861QString QGuiApplication::desktopFileName()
862{
863 return QGuiApplicationPrivate::desktopFileName ? *QGuiApplicationPrivate::desktopFileName : QString();
864}
865
866/*!
867 Returns the most recently shown modal window. If no modal windows are
868 visible, this function returns zero.
869
870 A modal window is a window which has its
871 \l{QWindow::modality}{modality} property set to Qt::WindowModal
872 or Qt::ApplicationModal. A modal window must be closed before the user can
873 continue with other parts of the program.
874
875 Modal window are organized in a stack. This function returns the modal
876 window at the top of the stack.
877
878 \sa Qt::WindowModality, QWindow::setModality()
879*/
880QWindow *QGuiApplication::modalWindow()
881{
882 CHECK_QAPP_INSTANCE(nullptr)
883 const auto &modalWindows = QGuiApplicationPrivate::instance()->modalWindowList;
884 if (modalWindows.isEmpty())
885 return nullptr;
886 return modalWindows.constFirst();
887}
888
889static void updateBlockedStatusRecursion(QWindow *window, bool shouldBeBlocked)
890{
891 QWindowPrivate *p = qt_window_private(window);
892 if (p->blockedByModalWindow != shouldBeBlocked) {
893 p->blockedByModalWindow = shouldBeBlocked;
894 QEvent e(shouldBeBlocked ? QEvent::WindowBlocked : QEvent::WindowUnblocked);
895 QGuiApplication::sendEvent(window, &e);
896 for (QObject *c : window->children()) {
897 if (c->isWindowType())
898 updateBlockedStatusRecursion(static_cast<QWindow *>(c), shouldBeBlocked);
899 }
900 }
901}
902
903void QGuiApplicationPrivate::updateBlockedStatus(QWindow *window)
904{
905 bool shouldBeBlocked = false;
906 const bool popupType = (window->type() == Qt::ToolTip) || (window->type() == Qt::Popup);
907 if (!popupType && !QGuiApplicationPrivate::instance()->modalWindowList.isEmpty())
908 shouldBeBlocked = QGuiApplicationPrivate::instance()->isWindowBlocked(window);
909 updateBlockedStatusRecursion(window, shouldBeBlocked);
910}
911
912// Return whether the window needs to be notified about window blocked events.
913// As opposed to QGuiApplication::topLevelWindows(), embedded windows are
914// included in this list (QTBUG-18099).
915static inline bool needsWindowBlockedEvent(const QWindow *w)
916{
917 return w->isTopLevel();
918}
919
920void QGuiApplicationPrivate::showModalWindow(QWindow *modal)
921{
922 auto *guiAppPrivate = QGuiApplicationPrivate::instance();
923 guiAppPrivate->modalWindowList.prepend(modal);
924
925 // Send leave for currently entered window if it should be blocked
926 if (currentMouseWindow && !QWindowPrivate::get(currentMouseWindow)->isPopup()) {
927 bool shouldBeBlocked = guiAppPrivate->isWindowBlocked(currentMouseWindow);
928 if (shouldBeBlocked) {
929 // Remove the new window from modalWindowList temporarily so leave can go through
930 guiAppPrivate->modalWindowList.removeFirst();
931 QEvent e(QEvent::Leave);
932 QGuiApplication::sendEvent(currentMouseWindow, &e);
933 currentMouseWindow = nullptr;
934 guiAppPrivate->modalWindowList.prepend(modal);
935 }
936 }
937
938 for (QWindow *window : std::as_const(QGuiApplicationPrivate::window_list)) {
939 if (needsWindowBlockedEvent(window) && !window->d_func()->blockedByModalWindow)
940 updateBlockedStatus(window);
941 }
942
943 updateBlockedStatus(modal);
944}
945
946void QGuiApplicationPrivate::hideModalWindow(QWindow *window)
947{
948 QGuiApplicationPrivate::instance()->modalWindowList.removeAll(window);
949
950 for (QWindow *window : std::as_const(QGuiApplicationPrivate::window_list)) {
951 if (needsWindowBlockedEvent(window) && window->d_func()->blockedByModalWindow)
952 updateBlockedStatus(window);
953 }
954}
955
956Qt::WindowModality QGuiApplicationPrivate::defaultModality() const
957{
958 return Qt::NonModal;
959}
960
961bool QGuiApplicationPrivate::windowNeverBlocked(QWindow *window) const
962{
963 Q_UNUSED(window);
964 return false;
965}
966
967/*
968 Returns \c true if \a window is blocked by a modal window. If \a
969 blockingWindow is non-zero, *blockingWindow will be set to the blocking
970 window (or to zero if \a window is not blocked).
971*/
972bool QGuiApplicationPrivate::isWindowBlocked(QWindow *window, QWindow **blockingWindow) const
973{
974 Q_ASSERT_X(window, Q_FUNC_INFO, "The window must not be null");
975
976 QWindow *unused = nullptr;
977 if (!blockingWindow)
978 blockingWindow = &unused;
979 *blockingWindow = nullptr;
980
981 if (modalWindowList.isEmpty() || windowNeverBlocked(window))
982 return false;
983
984 for (int i = 0; i < modalWindowList.size(); ++i) {
985 QWindow *modalWindow = modalWindowList.at(i);
986
987 // A window is not blocked by another modal window if the two are
988 // the same, or if the window is a child of the modal window.
989 if (window == modalWindow || modalWindow->isAncestorOf(window, QWindow::IncludeTransients))
990 return false;
991
992 switch (modalWindow->modality() == Qt::NonModal ? defaultModality()
993 : modalWindow->modality()) {
994 case Qt::ApplicationModal:
995 *blockingWindow = modalWindow;
996 return true;
997 case Qt::WindowModal: {
998 // Find the nearest ancestor of window which is also an ancestor of modal window to
999 // determine if the modal window blocks the window.
1000 auto *current = window;
1001 do {
1002 if (current->isAncestorOf(modalWindow, QWindow::IncludeTransients)) {
1003 *blockingWindow = modalWindow;
1004 return true;
1005 }
1006 current = current->parent(QWindow::IncludeTransients);
1007 } while (current);
1008 break;
1009 }
1010 default:
1011 Q_ASSERT_X(false, "QGuiApplication", "internal error, a modal widget cannot be modeless");
1012 break;
1013 }
1014 }
1015 return false;
1016}
1017
1018QWindow *QGuiApplicationPrivate::activePopupWindow()
1019{
1020 // might be the same as focusWindow() if that's a popup
1021 return QGuiApplicationPrivate::popup_list.isEmpty() ?
1022 nullptr : QGuiApplicationPrivate::popup_list.constLast();
1023}
1024
1025void QGuiApplicationPrivate::activatePopup(QWindow *popup)
1026{
1027 if (!popup->isVisible())
1028 return;
1029 popup_list.removeOne(popup); // ensure that there's only one entry, and it's the last
1030 qCDebug(lcPopup) << "appending popup" << popup << "to existing" << popup_list;
1031 popup_list.append(popup);
1032}
1033
1034bool QGuiApplicationPrivate::closePopup(QWindow *popup)
1035{
1036 const auto removed = QGuiApplicationPrivate::popup_list.removeAll(popup);
1037 qCDebug(lcPopup) << "removed?" << removed << "popup" << popup << "; remaining" << popup_list;
1038 return removed; // >= 1 if something was removed
1039}
1040
1041/*!
1042 Returns \c true if there are no more open popups.
1043*/
1044bool QGuiApplicationPrivate::closeAllPopups()
1045{
1046 // Close all popups: In case some popup refuses to close,
1047 // we give up after 1024 attempts (to avoid an infinite loop).
1048 int maxiter = 1024;
1049 QWindow *popup;
1050 while ((popup = activePopupWindow()) && maxiter--)
1051 popup->close(); // this will call QApplicationPrivate::closePopup
1052 return QGuiApplicationPrivate::popup_list.isEmpty();
1053}
1054
1055/*!
1056 Returns the QWindow that receives events tied to focus,
1057 such as key events.
1058
1059 \sa QWindow::requestActivate()
1060*/
1061QWindow *QGuiApplication::focusWindow()
1062{
1063 return QGuiApplicationPrivate::focus_window;
1064}
1065
1066/*!
1067 \fn QGuiApplication::focusObjectChanged(QObject *focusObject)
1068
1069 This signal is emitted when final receiver of events tied to focus is changed.
1070 \a focusObject is the new receiver.
1071
1072 \sa focusObject()
1073*/
1074
1075/*!
1076 \fn QGuiApplication::focusWindowChanged(QWindow *focusWindow)
1077
1078 This signal is emitted when the focused window changes.
1079 \a focusWindow is the new focused window.
1080
1081 \sa focusWindow()
1082*/
1083
1084/*!
1085 Returns the QObject in currently active window that will be final receiver of events
1086 tied to focus, such as key events.
1087 */
1088QObject *QGuiApplication::focusObject()
1089{
1090 if (focusWindow())
1091 return focusWindow()->focusObject();
1092 return nullptr;
1093}
1094
1095/*!
1096 \fn QGuiApplication::allWindows()
1097
1098 Returns a list of all the windows in the application.
1099
1100 The list is empty if there are no windows.
1101
1102 \sa topLevelWindows()
1103 */
1104QWindowList QGuiApplication::allWindows()
1105{
1106 return QGuiApplicationPrivate::window_list;
1107}
1108
1109/*!
1110 \fn QGuiApplication::topLevelWindows()
1111
1112 Returns a list of the top-level windows in the application.
1113
1114 \sa allWindows()
1115 */
1116QWindowList QGuiApplication::topLevelWindows()
1117{
1118 const QWindowList &list = QGuiApplicationPrivate::window_list;
1119 QWindowList topLevelWindows;
1120 for (int i = 0; i < list.size(); ++i) {
1121 QWindow *window = list.at(i);
1122 if (!window->isTopLevel())
1123 continue;
1124
1125 // Windows embedded in native windows do not have QWindow parents,
1126 // but they are not true top level windows, so do not include them.
1127 if (window->handle() && window->handle()->isEmbedded())
1128 continue;
1129
1130 topLevelWindows.prepend(window);
1131 }
1132
1133 return topLevelWindows;
1134}
1135
1136QScreen *QGuiApplication::primaryScreen()
1137{
1138 if (QGuiApplicationPrivate::screen_list.isEmpty())
1139 return nullptr;
1140 return QGuiApplicationPrivate::screen_list.at(0);
1141}
1142
1143/*!
1144 Returns a list of all the screens associated with the
1145 windowing system the application is connected to.
1146*/
1147QList<QScreen *> QGuiApplication::screens()
1148{
1149 return QGuiApplicationPrivate::screen_list;
1150}
1151
1152/*!
1153 Returns the screen at \a point, or \nullptr if outside of any screen.
1154
1155 The \a point is in relation to the virtualGeometry() of each set of virtual
1156 siblings. If the point maps to more than one set of virtual siblings the first
1157 match is returned. If you wish to search only the virtual desktop siblings
1158 of a known screen (for example siblings of the screen of your application
1159 window \c QWidget::windowHandle()->screen()), use QScreen::virtualSiblingAt().
1160
1161 \since 5.10
1162*/
1163QScreen *QGuiApplication::screenAt(const QPoint &point)
1164{
1165 QVarLengthArray<const QScreen *, 8> visitedScreens;
1166 for (const QScreen *screen : QGuiApplication::screens()) {
1167 if (visitedScreens.contains(screen))
1168 continue;
1169
1170 // The virtual siblings include the screen itself, so iterate directly
1171 for (QScreen *sibling : screen->virtualSiblings()) {
1172 if (sibling->geometry().contains(point))
1173 return sibling;
1174
1175 visitedScreens.append(sibling);
1176 }
1177 }
1178
1179 return nullptr;
1180}
1181
1182/*!
1183 \fn void QGuiApplication::screenAdded(QScreen *screen)
1184
1185 This signal is emitted whenever a new screen \a screen has been added to the system.
1186
1187 \sa screens(), primaryScreen, screenRemoved()
1188*/
1189
1190/*!
1191 \fn void QGuiApplication::screenRemoved(QScreen *screen)
1192
1193 This signal is emitted whenever a \a screen is removed from the system. It
1194 provides an opportunity to manage the windows on the screen before Qt falls back
1195 to moving them to the primary screen.
1196
1197 \sa screens(), screenAdded(), QObject::destroyed(), QWindow::setScreen()
1198
1199 \since 5.4
1200*/
1201
1202
1203/*!
1204 \property QGuiApplication::primaryScreen
1205
1206 \brief the primary (or default) screen of the application.
1207
1208 This will be the screen where QWindows are initially shown, unless otherwise specified.
1209
1210 The primaryScreenChanged signal was introduced in Qt 5.6.
1211
1212 \sa screens()
1213*/
1214
1215/*!
1216 Returns the highest screen device pixel ratio found on
1217 the system. This is the ratio between physical pixels and
1218 device-independent pixels.
1219
1220 Use this function only when you don't know which window you are targeting.
1221 If you do know the target window, use QWindow::devicePixelRatio() instead.
1222
1223 \sa QWindow::devicePixelRatio()
1224*/
1225qreal QGuiApplication::devicePixelRatio() const
1226{
1227 if (!qFuzzyIsNull(QGuiApplicationPrivate::m_maxDevicePixelRatio))
1228 return QGuiApplicationPrivate::m_maxDevicePixelRatio;
1229
1230 QGuiApplicationPrivate::m_maxDevicePixelRatio = 1.0; // make sure we never return 0.
1231 for (QScreen *screen : std::as_const(QGuiApplicationPrivate::screen_list))
1232 QGuiApplicationPrivate::m_maxDevicePixelRatio = qMax(QGuiApplicationPrivate::m_maxDevicePixelRatio, screen->devicePixelRatio());
1233
1234 return QGuiApplicationPrivate::m_maxDevicePixelRatio;
1235}
1236
1237void QGuiApplicationPrivate::resetCachedDevicePixelRatio()
1238{
1239 m_maxDevicePixelRatio = 0.0;
1240}
1241
1242void QGuiApplicationPrivate::_q_updatePrimaryScreenDpis()
1243{
1244 int dpis = 0;
1245 const QScreen *screen = QGuiApplication::primaryScreen();
1246 if (screen) {
1247 int dpiX = qRound(screen->logicalDotsPerInchX());
1248 int dpiY = qRound(screen->logicalDotsPerInchY());
1249 dpis = (dpiX << 16) | (dpiY & 0xffff);
1250 QObject::connect(screen, SIGNAL(logicalDotsPerInchChanged(qreal)),
1251 q_func(), SLOT(_q_updatePrimaryScreenDpis()), Qt::UniqueConnection);
1252 }
1253 m_primaryScreenDpis.storeRelaxed(dpis);
1254}
1255
1256/*!
1257 Returns the top level window at the given position \a pos, if any.
1258*/
1259QWindow *QGuiApplication::topLevelAt(const QPoint &pos)
1260{
1261 if (QScreen *windowScreen = screenAt(pos)) {
1262 const QPoint devicePosition = QHighDpi::toNativePixels(pos, windowScreen);
1263 return windowScreen->handle()->topLevelAt(devicePosition);
1264 }
1265 return nullptr;
1266}
1267
1268/*!
1269 \property QGuiApplication::platformName
1270 \brief The name of the underlying platform plugin.
1271
1272 The QPA platform plugins are located in \c {qtbase\src\plugins\platforms}.
1273 At the time of writing, the following platform plugin names are supported:
1274
1275 \list
1276 \li \c android
1277 \li \c cocoa is a platform plugin for \macos.
1278 \li \c directfb
1279 \li \c eglfs is a platform plugin for running Qt5 applications on top of
1280 EGL and OpenGL ES 2.0 without an actual windowing system (like X11
1281 or Wayland). For more information, see \l{EGLFS}.
1282 \li \c ios (also used for tvOS)
1283 \li \c linuxfb writes directly to the framebuffer. For more information,
1284 see \l{LinuxFB}.
1285 \li \c minimal is provided as an examples for developers who want to
1286 write their own platform plugins. However, you can use the plugin to
1287 run GUI applications in environments without a GUI, such as servers.
1288 \li \c minimalegl is an example plugin.
1289 \li \c offscreen
1290 \li \c qnx
1291 \li \c windows
1292 \li \c wayland is a platform plugin for the Wayland display server protocol,
1293 used on some Linux desktops and embedded systems.
1294 \li \c xcb is a plugin for the X11 window system, used on some desktop Linux platforms.
1295 \endlist
1296
1297 \note Calling this function without a QGuiApplication will return the default
1298 platform name, if available. The default platform name is not affected by the
1299 \c{-platform} command line option, or the \c QT_QPA_PLATFORM environment variable.
1300
1301 For more information about the platform plugins for embedded Linux devices,
1302 see \l{Qt for Embedded Linux}.
1303*/
1304
1305QString QGuiApplication::platformName()
1306{
1307 if (!QGuiApplication::instance()) {
1308#ifdef QT_QPA_DEFAULT_PLATFORM_NAME
1309 return QStringLiteral(QT_QPA_DEFAULT_PLATFORM_NAME);
1310#else
1311 return QString();
1312#endif
1313 } else {
1314 return QGuiApplicationPrivate::platform_name ?
1315 *QGuiApplicationPrivate::platform_name : QString();
1316 }
1317}
1318
1319Q_STATIC_LOGGING_CATEGORY(lcQpaPluginLoading, "qt.qpa.plugin");
1320Q_STATIC_LOGGING_CATEGORY(lcQpaTheme, "qt.qpa.theme");
1321Q_STATIC_LOGGING_CATEGORY(lcPtrDispatch, "qt.pointer.dispatch");
1322
1323static void init_platform(const QString &pluginNamesWithArguments, const QString &platformPluginPath, const QString &platformThemeName, int &argc, char **argv)
1324{
1325 qCDebug(lcQpaPluginLoading) << "init_platform called with"
1326 << "pluginNamesWithArguments" << pluginNamesWithArguments
1327 << "platformPluginPath" << platformPluginPath
1328 << "platformThemeName" << platformThemeName;
1329
1330 QStringList plugins = pluginNamesWithArguments.split(u';', Qt::SkipEmptyParts);
1331 QStringList platformArguments;
1332 QStringList availablePlugins = QPlatformIntegrationFactory::keys(platformPluginPath);
1333 for (const auto &pluginArgument : std::as_const(plugins)) {
1334 // Split into platform name and arguments
1335 QStringList arguments = pluginArgument.split(u':', Qt::SkipEmptyParts);
1336 if (arguments.isEmpty())
1337 continue;
1338 const QString name = arguments.takeFirst().toLower();
1339 QString argumentsKey = name;
1340 if (name.isEmpty())
1341 continue;
1342 argumentsKey[0] = argumentsKey.at(0).toUpper();
1343 arguments.append(QLibraryInfo::platformPluginArguments(argumentsKey));
1344
1345 qCDebug(lcQpaPluginLoading) << "Attempting to load Qt platform plugin" << name << "with arguments" << arguments;
1346
1347 // Create the platform integration.
1348 QGuiApplicationPrivate::platform_integration = QPlatformIntegrationFactory::create(name, arguments, argc, argv, platformPluginPath);
1349 if (Q_UNLIKELY(!QGuiApplicationPrivate::platform_integration)) {
1350 if (availablePlugins.contains(name)) {
1351 if (name == QStringLiteral("xcb") && QVersionNumber::compare(QLibraryInfo::version(), QVersionNumber(6, 5, 0)) >= 0) {
1352 qCWarning(lcQpaPluginLoading).nospace().noquote()
1353 << "From 6.5.0, xcb-cursor0 or libxcb-cursor0 is needed to load the Qt xcb platform plugin.";
1354 }
1355 qCInfo(lcQpaPluginLoading).nospace().noquote()
1356 << "Could not load the Qt platform plugin \"" << name << "\" in \""
1357 << QDir::toNativeSeparators(platformPluginPath) << "\" even though it was found.";
1358 } else {
1359 qCWarning(lcQpaPluginLoading).nospace().noquote()
1360 << "Could not find the Qt platform plugin \"" << name << "\" in \""
1361 << QDir::toNativeSeparators(platformPluginPath) << "\"";
1362 }
1363 } else {
1364 qCDebug(lcQpaPluginLoading) << "Successfully loaded Qt platform plugin" << name;
1365 QGuiApplicationPrivate::platform_name = new QString(name);
1366 platformArguments = arguments;
1367 break;
1368 }
1369 }
1370
1371 if (Q_UNLIKELY(!QGuiApplicationPrivate::platform_integration)) {
1372 QString fatalMessage = QStringLiteral("This application failed to start because no Qt platform plugin could be initialized. "
1373 "Reinstalling the application may fix this problem.\n");
1374
1375 if (!availablePlugins.isEmpty())
1376 fatalMessage += "\nAvailable platform plugins are: %1.\n"_L1.arg(availablePlugins.join(", "_L1));
1377
1378#if defined(Q_OS_WIN)
1379 // Windows: Display message box unless it is a console application
1380 // or debug build showing an assert box.
1381 if (!QLibraryInfo::isDebugBuild() && !GetConsoleWindow())
1382 MessageBox(0, (LPCTSTR)fatalMessage.utf16(), (LPCTSTR)(QCoreApplication::applicationName().utf16()), MB_OK | MB_ICONERROR);
1383#endif // Q_OS_WIN
1384 qFatal("%s", qPrintable(fatalMessage));
1385
1386 return;
1387 }
1388
1389 // Create the platform theme:
1390
1391 // 1) Try the platform name from the environment if present
1392 QStringList themeNames;
1393 if (!platformThemeName.isEmpty()) {
1394 qCDebug(lcQpaTheme) << "Adding" << platformThemeName << "from environment";
1395 themeNames.append(platformThemeName);
1396 }
1397
1398#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
1399 // 2) Special case - check whether it's a flatpak or snap app to use xdg-desktop-portal platform theme for portals support
1400 if (checkNeedPortalSupport()) {
1401 qCDebug(lcQpaTheme) << "Adding xdgdesktopportal to list of theme names";
1402 themeNames.append(QStringLiteral("xdgdesktopportal"));
1403 }
1404#endif
1405
1406 // 3) Ask the platform integration for a list of theme names
1407 const auto platformIntegrationThemeNames = QGuiApplicationPrivate::platform_integration->themeNames();
1408 qCDebug(lcQpaTheme) << "Adding platform integration's theme names to list of theme names:" << platformIntegrationThemeNames;
1409 themeNames.append(platformIntegrationThemeNames);
1410
1411 // 4) Look for a theme plugin.
1412 for (const QString &themeName : std::as_const(themeNames)) {
1413 qCDebug(lcQpaTheme) << "Attempting to create platform theme" << themeName << "via QPlatformThemeFactory::create";
1414 QGuiApplicationPrivate::platform_theme = QPlatformThemeFactory::create(themeName, platformPluginPath);
1415 if (QGuiApplicationPrivate::platform_theme) {
1416 qCDebug(lcQpaTheme) << "Successfully created platform theme" << themeName << "via QPlatformThemeFactory::create";
1417 break;
1418 }
1419 qCDebug(lcQpaTheme) << "Attempting to create platform theme" << themeName << "via createPlatformTheme";
1420 QGuiApplicationPrivate::platform_theme = QGuiApplicationPrivate::platform_integration->createPlatformTheme(themeName);
1421 if (QGuiApplicationPrivate::platform_theme) {
1422 qCDebug(lcQpaTheme) << "Successfully created platform theme" << themeName << "via createPlatformTheme";
1423 break;
1424 }
1425 }
1426
1427 // 5) Fall back on the built-in "null" platform theme.
1428 if (!QGuiApplicationPrivate::platform_theme) {
1429 qCDebug(lcQpaTheme) << "Failed to create platform theme; using \"null\" platform theme";
1430 QGuiApplicationPrivate::platform_theme = new QPlatformTheme;
1431 }
1432
1433 // Set arguments as dynamic properties on the native interface as
1434 // boolean 'foo' or strings: 'foo=bar'
1435 if (!platformArguments.isEmpty()) {
1436 if (QObject *nativeInterface = QGuiApplicationPrivate::platform_integration->nativeInterface()) {
1437 for (const QString &argument : std::as_const(platformArguments)) {
1438 const qsizetype equalsPos = argument.indexOf(u'=');
1439 const QByteArray name =
1440 equalsPos != -1 ? argument.left(equalsPos).toUtf8() : argument.toUtf8();
1441 QVariant value =
1442 equalsPos != -1 ? QVariant(argument.mid(equalsPos + 1)) : QVariant(true);
1443 nativeInterface->setProperty(name.constData(), std::move(value));
1444 }
1445 }
1446 }
1447
1448 const auto *platformIntegration = QGuiApplicationPrivate::platformIntegration();
1449 fontSmoothingGamma = platformIntegration->styleHint(QPlatformIntegration::FontSmoothingGamma).toReal();
1450 QCoreApplication::setAttribute(Qt::AA_DontShowShortcutsInContextMenus,
1451 !QGuiApplication::styleHints()->showShortcutsInContextMenus());
1452
1453 if (const auto *platformTheme = QGuiApplicationPrivate::platformTheme()) {
1454 QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus,
1455 !platformTheme->themeHint(QPlatformTheme::ShowIconsInMenus).toBool());
1456 }
1457}
1458
1459static void init_plugins(const QList<QByteArray> &pluginList)
1460{
1461 for (int i = 0; i < pluginList.size(); ++i) {
1462 QByteArray pluginSpec = pluginList.at(i);
1463 qsizetype colonPos = pluginSpec.indexOf(':');
1464 QObject *plugin;
1465 if (colonPos < 0)
1466 plugin = QGenericPluginFactory::create(QLatin1StringView(pluginSpec), QString());
1467 else
1468 plugin = QGenericPluginFactory::create(QLatin1StringView(pluginSpec.mid(0, colonPos)),
1469 QLatin1StringView(pluginSpec.mid(colonPos+1)));
1470 if (plugin)
1471 QGuiApplicationPrivate::generic_plugin_list.append(plugin);
1472 else
1473 qWarning("No such plugin for spec \"%s\"", pluginSpec.constData());
1474 }
1475}
1476
1477#if QT_CONFIG(commandlineparser)
1478void QGuiApplicationPrivate::addQtOptions(QList<QCommandLineOption> *options)
1479{
1480 QCoreApplicationPrivate::addQtOptions(options);
1481
1482#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
1483 const QByteArray sessionType = qgetenv("XDG_SESSION_TYPE");
1484 const bool x11 = sessionType == "x11";
1485 // Technically the x11 aliases are only available if platformName is "xcb", but we can't know that here.
1486#else
1487 const bool x11 = false;
1488#endif
1489
1490 options->append(QCommandLineOption(QStringLiteral("platform"),
1491 QGuiApplication::tr("QPA plugin. See QGuiApplication documentation for available options for each plugin."), QStringLiteral("platformName[:options]")));
1492 options->append(QCommandLineOption(QStringLiteral("platformpluginpath"),
1493 QGuiApplication::tr("Path to the platform plugins."), QStringLiteral("path")));
1494 options->append(QCommandLineOption(QStringLiteral("platformtheme"),
1495 QGuiApplication::tr("Platform theme."), QStringLiteral("theme")));
1496 options->append(QCommandLineOption(QStringLiteral("plugin"),
1497 QGuiApplication::tr("Additional plugins to load, can be specified multiple times."), QStringLiteral("plugin")));
1498 options->append(QCommandLineOption(QStringLiteral("qwindowgeometry"),
1499 QGuiApplication::tr("Window geometry for the main window, using the X11-syntax, like 100x100+50+50."), QStringLiteral("geometry")));
1500 options->append(QCommandLineOption(QStringLiteral("qwindowicon"),
1501 QGuiApplication::tr("Default window icon."), QStringLiteral("icon")));
1502 options->append(QCommandLineOption(QStringLiteral("qwindowtitle"),
1503 QGuiApplication::tr("Title of the first window."), QStringLiteral("title")));
1504 options->append(QCommandLineOption(QStringLiteral("reverse"),
1505 QGuiApplication::tr("Sets the application's layout direction to Qt::RightToLeft (debugging helper).")));
1506 options->append(QCommandLineOption(QStringLiteral("session"),
1507 QGuiApplication::tr("Restores the application from an earlier session."), QStringLiteral("session")));
1508
1509 if (x11) {
1510 options->append(QCommandLineOption(QStringLiteral("display"),
1511 QGuiApplication::tr("Display name, overrides $DISPLAY."), QStringLiteral("display")));
1512 options->append(QCommandLineOption(QStringLiteral("name"),
1513 QGuiApplication::tr("Instance name according to ICCCM 4.1.2.5."), QStringLiteral("name")));
1514 options->append(QCommandLineOption(QStringLiteral("nograb"),
1515 QGuiApplication::tr("Disable mouse grabbing (useful in debuggers).")));
1516 options->append(QCommandLineOption(QStringLiteral("dograb"),
1517 QGuiApplication::tr("Force mouse grabbing (even when running in a debugger).")));
1518 options->append(QCommandLineOption(QStringLiteral("visual"),
1519 QGuiApplication::tr("ID of the X11 Visual to use."), QStringLiteral("id")));
1520 // Not using the "QStringList names" solution for those aliases, because it makes the first column too wide
1521 options->append(QCommandLineOption(QStringLiteral("geometry"),
1522 QGuiApplication::tr("Alias for --qwindowgeometry."), QStringLiteral("geometry")));
1523 options->append(QCommandLineOption(QStringLiteral("icon"),
1524 QGuiApplication::tr("Alias for --qwindowicon."), QStringLiteral("icon")));
1525 options->append(QCommandLineOption(QStringLiteral("title"),
1526 QGuiApplication::tr("Alias for --qwindowtitle."), QStringLiteral("title")));
1527 }
1528}
1529#endif // QT_CONFIG(commandlineparser)
1530
1531void QGuiApplicationPrivate::createPlatformIntegration()
1532{
1533 QHighDpiScaling::initHighDpiScaling();
1534
1535 // Load the platform integration
1536 QString platformPluginPath = qEnvironmentVariable("QT_QPA_PLATFORM_PLUGIN_PATH");
1537
1538
1539 QByteArray platformName;
1540#ifdef QT_QPA_DEFAULT_PLATFORM_NAME
1541 platformName = QT_QPA_DEFAULT_PLATFORM_NAME;
1542#endif
1543#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
1544 QList<QByteArray> platformArguments = platformName.split(':');
1545 QByteArray platformPluginBase = platformArguments.first();
1546
1547 const bool hasWaylandDisplay = qEnvironmentVariableIsSet("WAYLAND_DISPLAY");
1548 const bool isWaylandSessionType = qgetenv("XDG_SESSION_TYPE") == "wayland";
1549
1550 QVector<QByteArray> preferredPlatformOrder;
1551 const bool defaultIsXcb = platformPluginBase == "xcb";
1552 const QByteArray xcbPlatformName = defaultIsXcb ? platformName : "xcb";
1553 if (qEnvironmentVariableIsSet("DISPLAY")) {
1554 preferredPlatformOrder << xcbPlatformName;
1555 if (defaultIsXcb)
1556 platformName.clear();
1557 }
1558
1559 const bool defaultIsWayland = !defaultIsXcb && platformPluginBase.startsWith("wayland");
1560 const QByteArray waylandPlatformName = defaultIsWayland ? platformName : "wayland";
1561 if (hasWaylandDisplay || isWaylandSessionType) {
1562 preferredPlatformOrder.prepend(waylandPlatformName);
1563
1564 if (defaultIsWayland)
1565 platformName.clear();
1566 }
1567
1568 if (!platformName.isEmpty())
1569 preferredPlatformOrder.append(platformName);
1570
1571 platformName = preferredPlatformOrder.join(';');
1572#endif
1573
1574 bool platformExplicitlySelected = false;
1575 QByteArray platformNameEnv = qgetenv("QT_QPA_PLATFORM");
1576 if (!platformNameEnv.isEmpty()) {
1577 platformName = platformNameEnv;
1578 platformExplicitlySelected = true;
1579 }
1580
1581 QString platformThemeName = QString::fromLocal8Bit(qgetenv("QT_QPA_PLATFORMTHEME"));
1582
1583 // Get command line params
1584
1585 QString icon;
1586
1587 int j = argc ? 1 : 0;
1588 for (int i=1; i<argc; i++) {
1589 if (!argv[i])
1590 continue;
1591 if (*argv[i] != '-') {
1592 argv[j++] = argv[i];
1593 continue;
1594 }
1595 const bool xcbIsDefault = platformName.startsWith("xcb");
1596 const char *arg = argv[i];
1597 if (arg[1] == '-') // startsWith("--")
1598 ++arg;
1599 if (strcmp(arg, "-platformpluginpath") == 0) {
1600 if (++i < argc)
1601 platformPluginPath = QFile::decodeName(argv[i]);
1602 } else if (strcmp(arg, "-platform") == 0) {
1603 if (++i < argc) {
1604 platformExplicitlySelected = true;
1605 platformName = argv[i];
1606 }
1607 } else if (strcmp(arg, "-platformtheme") == 0) {
1608 if (++i < argc)
1609 platformThemeName = QString::fromLocal8Bit(argv[i]);
1610 } else if (strcmp(arg, "-qwindowgeometry") == 0 || (xcbIsDefault && strcmp(arg, "-geometry") == 0)) {
1611 if (++i < argc)
1612 windowGeometrySpecification = QWindowGeometrySpecification::fromArgument(argv[i]);
1613 } else if (strcmp(arg, "-qwindowtitle") == 0 || (xcbIsDefault && strcmp(arg, "-title") == 0)) {
1614 if (++i < argc)
1615 firstWindowTitle = QString::fromLocal8Bit(argv[i]);
1616 } else if (strcmp(arg, "-qwindowicon") == 0 || (xcbIsDefault && strcmp(arg, "-icon") == 0)) {
1617 if (++i < argc) {
1618 icon = QFile::decodeName(argv[i]);
1619 }
1620 } else {
1621 argv[j++] = argv[i];
1622 }
1623 }
1624
1625 if (j < argc) {
1626 argv[j] = nullptr;
1627 argc = j;
1628 }
1629
1630 Q_UNUSED(platformExplicitlySelected);
1631
1632 init_platform(QLatin1StringView(platformName), platformPluginPath, platformThemeName, argc, argv);
1633 QStyleHintsPrivate::get(QGuiApplication::styleHints())->update(platformTheme());
1634
1635 if (!icon.isEmpty())
1636 forcedWindowIcon = QDir::isAbsolutePath(icon) ? QIcon(icon) : QIcon::fromTheme(icon);
1637}
1638
1639/*!
1640 Called from QCoreApplication::init()
1641
1642 Responsible for creating an event dispatcher when QCoreApplication
1643 decides that it needs one (because a custom one has not been set).
1644*/
1645void QGuiApplicationPrivate::createEventDispatcher()
1646{
1647 Q_ASSERT(!eventDispatcher);
1648
1649 if (platform_integration == nullptr)
1650 createPlatformIntegration();
1651
1652 // The platform integration should not result in creating an event dispatcher
1653 Q_ASSERT_X(!threadData.loadRelaxed()->eventDispatcher, "QGuiApplication",
1654 "Creating the platform integration resulted in creating an event dispatcher");
1655
1656 // Nor should it mess with the QCoreApplication's event dispatcher
1657 Q_ASSERT(!eventDispatcher);
1658
1659 eventDispatcher = platform_integration->createEventDispatcher();
1660}
1661
1662void QGuiApplicationPrivate::eventDispatcherReady()
1663{
1664 if (platform_integration == nullptr)
1665 createPlatformIntegration();
1666
1667 platform_integration->initialize();
1668}
1669
1670void Q_TRACE_INSTRUMENT(qtgui) QGuiApplicationPrivate::init()
1671{
1672 Q_TRACE_SCOPE(QGuiApplicationPrivate_init);
1673
1674#if defined(Q_OS_MACOS)
1675 QMacAutoReleasePool pool;
1676#endif
1677
1678 QObject::connect(q_func(), SIGNAL(screenAdded(QScreen*)),
1679 q_func(), SLOT(_q_updatePrimaryScreenDpis()));
1680 QObject::connect(q_func(), SIGNAL(primaryScreenChanged(QScreen *)),
1681 q_func(), SLOT(_q_updatePrimaryScreenDpis()));
1682
1683 QCoreApplicationPrivate::init();
1684
1685 QCoreApplicationPrivate::is_app_running = false; // Starting up.
1686
1687 bool loadTestability = false;
1688 QList<QByteArray> pluginList;
1689 // Get command line params
1690#ifndef QT_NO_SESSIONMANAGER
1691 QString session_id;
1692 QString session_key;
1693# if defined(Q_OS_WIN)
1694 wchar_t guidstr[40];
1695 GUID guid;
1696 CoCreateGuid(&guid);
1697 StringFromGUID2(guid, guidstr, 40);
1698 session_id = QString::fromWCharArray(guidstr);
1699 CoCreateGuid(&guid);
1700 StringFromGUID2(guid, guidstr, 40);
1701 session_key = QString::fromWCharArray(guidstr);
1702# endif
1703#endif
1704 QString s;
1705 int j = argc ? 1 : 0;
1706 for (int i=1; i<argc; i++) {
1707 if (!argv[i])
1708 continue;
1709 if (*argv[i] != '-') {
1710 argv[j++] = argv[i];
1711 continue;
1712 }
1713 const char *arg = argv[i];
1714 if (arg[1] == '-') // startsWith("--")
1715 ++arg;
1716 if (strcmp(arg, "-plugin") == 0) {
1717 if (++i < argc)
1718 pluginList << argv[i];
1719 } else if (strcmp(arg, "-reverse") == 0) {
1720 force_reverse = true;
1721#ifdef Q_OS_MACOS
1722 } else if (strncmp(arg, "-psn_", 5) == 0) {
1723 // eat "-psn_xxxx" on Mac, which is passed when starting an app from Finder.
1724 // special hack to change working directory (for an app bundle) when running from finder
1725 if (QDir::currentPath() == "/"_L1) {
1726 QCFType<CFURLRef> bundleURL(CFBundleCopyBundleURL(CFBundleGetMainBundle()));
1727 QString qbundlePath = QCFString(CFURLCopyFileSystemPath(bundleURL,
1728 kCFURLPOSIXPathStyle));
1729 if (qbundlePath.endsWith(".app"_L1))
1730 QDir::setCurrent(qbundlePath.section(u'/', 0, -2));
1731 }
1732#endif
1733#ifndef QT_NO_SESSIONMANAGER
1734 } else if (strcmp(arg, "-session") == 0 && i < argc - 1) {
1735 ++i;
1736 if (argv[i] && *argv[i]) {
1737 session_id = QString::fromLatin1(argv[i]);
1738 qsizetype p = session_id.indexOf(u'_');
1739 if (p >= 0) {
1740 session_key = session_id.mid(p +1);
1741 session_id = session_id.left(p);
1742 }
1743 is_session_restored = true;
1744 }
1745#endif
1746 } else if (strcmp(arg, "-testability") == 0) {
1747 loadTestability = true;
1748 } else if (strncmp(arg, "-style=", 7) == 0) {
1749 s = QString::fromLocal8Bit(arg + 7);
1750 } else if (strcmp(arg, "-style") == 0 && i < argc - 1) {
1751 s = QString::fromLocal8Bit(argv[++i]);
1752 } else {
1753 argv[j++] = argv[i];
1754 }
1755
1756 if (!s.isEmpty())
1757 styleOverride = s;
1758 }
1759
1760 if (j < argc) {
1761 argv[j] = nullptr;
1762 argc = j;
1763 }
1764
1765 // Load environment exported generic plugins
1766 QByteArray envPlugins = qgetenv("QT_QPA_GENERIC_PLUGINS");
1767 if (!envPlugins.isEmpty())
1768 pluginList += envPlugins.split(',');
1769
1770 if (platform_integration == nullptr)
1771 createPlatformIntegration();
1772
1773 updatePalette();
1774 QFont::initialize();
1775 initThemeHints();
1776
1777#ifndef QT_NO_CURSOR
1778 QCursorData::initialize();
1779#endif
1780
1781 // trigger registering of QVariant's GUI types
1782 qRegisterGuiVariant();
1783
1784#if QT_CONFIG(animation)
1785 // trigger registering of animation interpolators
1786 qRegisterGuiGetInterpolator();
1787#endif
1788
1789 QWindowSystemInterfacePrivate::eventTime.start();
1790
1791#if QT_CONFIG(accessibility)
1792 QAccessible::installFactory([](const QString &classname, QObject *object)
1793 -> QAccessibleInterface * {
1794 if (classname == "QForeignWindow"_L1)
1795 return new QAccessibleWindow(static_cast<QWindow *>(object));
1796 return nullptr;
1797 });
1798#endif
1799
1800 is_app_running = true;
1801 init_plugins(pluginList);
1802 QWindowSystemInterface::flushWindowSystemEvents();
1803
1804 Q_Q(QGuiApplication);
1805#ifndef QT_NO_SESSIONMANAGER
1806 // connect to the session manager
1807 session_manager = new QSessionManager(q, session_id, session_key);
1808#endif
1809
1810#if QT_CONFIG(library)
1811 if (qEnvironmentVariableIntValue("QT_LOAD_TESTABILITY") > 0)
1812 loadTestability = true;
1813
1814 if (loadTestability) {
1815 QLibrary testLib(QStringLiteral("qttestability"));
1816 if (Q_UNLIKELY(!testLib.load())) {
1817 qCritical() << "Library qttestability load failed:" << testLib.errorString();
1818 } else {
1819 typedef void (*TasInitialize)(void);
1820 TasInitialize initFunction = (TasInitialize)testLib.resolve("qt_testability_init");
1821 if (Q_UNLIKELY(!initFunction)) {
1822 qCritical("Library qttestability resolve failed!");
1823 } else {
1824 initFunction();
1825 }
1826 }
1827 }
1828#else
1829 Q_UNUSED(loadTestability);
1830#endif // QT_CONFIG(library)
1831
1832 // trigger changed signal and event delivery
1833 QGuiApplication::setLayoutDirection(layout_direction);
1834
1835 if (!QGuiApplicationPrivate::displayName)
1836 QObject::connect(q, &QGuiApplication::applicationNameChanged,
1837 q, &QGuiApplication::applicationDisplayNameChanged);
1838}
1839
1840extern void qt_cleanupFontDatabase();
1841
1842QGuiApplicationPrivate::~QGuiApplicationPrivate()
1843{
1844#if defined(Q_OS_MACOS)
1845 QMacAutoReleasePool pool;
1846#endif
1847
1848 is_app_closing = true;
1849 is_app_running = false;
1850
1851 for (int i = 0; i < generic_plugin_list.size(); ++i)
1852 delete generic_plugin_list.at(i);
1853 generic_plugin_list.clear();
1854
1855 clearFontUnlocked();
1856
1857 QFont::cleanup();
1858
1859#ifndef QT_NO_CURSOR
1860 QCursorData::cleanup();
1861#endif
1862
1863 layout_direction = Qt::LayoutDirectionAuto;
1864
1865 cleanupThreadData();
1866
1867 delete QGuiApplicationPrivate::styleHints;
1868 QGuiApplicationPrivate::styleHints = nullptr;
1869 delete inputMethod;
1870
1871 qt_cleanupFontDatabase();
1872
1873 QPixmapCache::clear();
1874
1875#ifndef QT_NO_OPENGL
1876 if (ownGlobalShareContext) {
1877 delete qt_gl_global_share_context();
1878 qt_gl_set_global_share_context(nullptr);
1879 }
1880#endif
1881
1882#if QT_CONFIG(vulkan)
1883 QVulkanDefaultInstance::cleanup();
1884#endif
1885
1886 platform_integration->destroy();
1887
1888 delete platform_theme;
1889 platform_theme = nullptr;
1890 delete platform_integration;
1891 platform_integration = nullptr;
1892
1893 window_list.clear();
1894 popup_list.clear();
1895 screen_list.clear();
1896
1897 // Note: Not same as QCoreApplication::self
1898 QT_IGNORE_DEPRECATIONS(QGuiApplicationPrivate::self = nullptr;)
1899}
1900
1901#if 0
1902#ifndef QT_NO_CURSOR
1903QCursor *overrideCursor();
1904void setOverrideCursor(const QCursor &);
1905void changeOverrideCursor(const QCursor &);
1906void restoreOverrideCursor();
1907#endif
1908
1909static QFont font();
1910static QFont font(const QWidget*);
1911static QFont font(const char *className);
1912static void setFont(const QFont &, const char *className = nullptr);
1913static QFontMetrics fontMetrics();
1914
1915#ifndef QT_NO_CLIPBOARD
1916static QClipboard *clipboard();
1917#endif
1918#endif
1919
1920/*!
1921 Returns the current state of the modifier keys on the keyboard. The current
1922 state is updated synchronously as the event queue is emptied of events that
1923 will spontaneously change the keyboard state (QEvent::KeyPress and
1924 QEvent::KeyRelease events).
1925
1926 It should be noted this may not reflect the actual keys held on the input
1927 device at the time of calling but rather the modifiers as last reported in
1928 one of the above events. If no keys are being held Qt::NoModifier is
1929 returned.
1930
1931 \sa mouseButtons(), queryKeyboardModifiers()
1932*/
1933Qt::KeyboardModifiers QGuiApplication::keyboardModifiers()
1934{
1935 return QGuiApplicationPrivate::modifier_buttons;
1936}
1937
1938/*!
1939 \fn Qt::KeyboardModifiers QGuiApplication::queryKeyboardModifiers()
1940
1941 Queries and returns the state of the modifier keys on the keyboard.
1942 Unlike keyboardModifiers, this method returns the actual keys held
1943 on the input device at the time of calling the method.
1944
1945 It does not rely on the keypress events having been received by this
1946 process, which makes it possible to check the modifiers while moving
1947 a window, for instance. Note that in most cases, you should use
1948 keyboardModifiers(), which is faster and more accurate since it contains
1949 the state of the modifiers as they were when the currently processed
1950 event was received.
1951
1952 \sa keyboardModifiers()
1953*/
1954Qt::KeyboardModifiers QGuiApplication::queryKeyboardModifiers()
1955{
1956 CHECK_QAPP_INSTANCE(Qt::KeyboardModifiers{})
1957 QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
1958 return pi->keyMapper()->queryKeyboardModifiers();
1959}
1960
1961/*!
1962 Returns the current state of the buttons on the mouse. The current state is
1963 updated synchronously as the event queue is emptied of events that will
1964 spontaneously change the mouse state (QEvent::MouseButtonPress and
1965 QEvent::MouseButtonRelease events).
1966
1967 It should be noted this may not reflect the actual buttons held on the
1968 input device at the time of calling but rather the mouse buttons as last
1969 reported in one of the above events. If no mouse buttons are being held
1970 Qt::NoButton is returned.
1971
1972 \sa keyboardModifiers()
1973*/
1974Qt::MouseButtons QGuiApplication::mouseButtons()
1975{
1976 return QGuiApplicationPrivate::mouse_buttons;
1977}
1978
1979/*!
1980 \internal
1981 Returns the platform's native interface, for platform specific
1982 functionality.
1983*/
1984QPlatformNativeInterface *QGuiApplication::platformNativeInterface()
1985{
1986 QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
1987 return pi ? pi->nativeInterface() : nullptr;
1988}
1989
1990/*!
1991 \internal
1992 Returns a function pointer from the platformplugin matching \a function
1993*/
1994QFunctionPointer QGuiApplication::platformFunction(const QByteArray &function)
1995{
1996 QPlatformIntegration *pi = QGuiApplicationPrivate::platformIntegration();
1997 if (!pi) {
1998 qWarning("QGuiApplication::platformFunction(): Must construct a QGuiApplication before accessing a platform function");
1999 return nullptr;
2000 }
2001
2002 return pi->nativeInterface() ? pi->nativeInterface()->platformFunction(function) : nullptr;
2003}
2004
2005/*!
2006 Enters the main event loop and waits until exit() is called, and then
2007 returns the value that was set to exit() (which is 0 if exit() is called
2008 via quit()).
2009
2010 It is necessary to call this function to start event handling. The main
2011 event loop receives events from the window system and dispatches these to
2012 the application widgets.
2013
2014 Generally, no user interaction can take place before calling exec().
2015
2016 To make your application perform idle processing, e.g., executing a
2017 special function whenever there are no pending events, use a QChronoTimer
2018 with 0ns timeout. More advanced idle processing schemes can be achieved
2019 using processEvents().
2020
2021 We recommend that you connect clean-up code to the
2022 \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
2023 application's \c{main()} function. This is because, on some platforms, the
2024 QApplication::exec() call may not return.
2025
2026 \sa quitOnLastWindowClosed, quit(), exit(), processEvents(),
2027 QCoreApplication::exec()
2028*/
2029int QGuiApplication::exec()
2030{
2031#if QT_CONFIG(accessibility)
2032 QAccessible::setRootObject(qApp);
2033#endif
2034 return QCoreApplication::exec();
2035}
2036
2037void QGuiApplicationPrivate::captureGlobalModifierState(QEvent *e)
2038{
2039 if (e->spontaneous()) {
2040 // Capture the current mouse and keyboard states. Doing so here is
2041 // required in order to support Qt Test synthesized events. Real mouse
2042 // and keyboard state updates from the platform plugin are managed by
2043 // QGuiApplicationPrivate::process(Mouse|Wheel|Key|Touch|Tablet)Event();
2044 // ### FIXME: Qt Test should not call qapp->notify(), but rather route
2045 // the events through the proper QPA interface. This is required to
2046 // properly generate all other events such as enter/leave etc.
2047 switch (e->type()) {
2048 case QEvent::MouseButtonPress: {
2049 QMouseEvent *me = static_cast<QMouseEvent *>(e);
2050 QGuiApplicationPrivate::modifier_buttons = me->modifiers();
2051 QGuiApplicationPrivate::mouse_buttons |= me->button();
2052 break;
2053 }
2054 case QEvent::MouseButtonDblClick: {
2055 QMouseEvent *me = static_cast<QMouseEvent *>(e);
2056 QGuiApplicationPrivate::modifier_buttons = me->modifiers();
2057 QGuiApplicationPrivate::mouse_buttons |= me->button();
2058 break;
2059 }
2060 case QEvent::MouseButtonRelease: {
2061 QMouseEvent *me = static_cast<QMouseEvent *>(e);
2062 QGuiApplicationPrivate::modifier_buttons = me->modifiers();
2063 QGuiApplicationPrivate::mouse_buttons &= ~me->button();
2064 break;
2065 }
2066 case QEvent::KeyPress:
2067 case QEvent::KeyRelease:
2068 case QEvent::MouseMove:
2069#if QT_CONFIG(wheelevent)
2070 case QEvent::Wheel:
2071#endif
2072 case QEvent::TouchBegin:
2073 case QEvent::TouchUpdate:
2074 case QEvent::TouchEnd:
2075#if QT_CONFIG(tabletevent)
2076 case QEvent::TabletMove:
2077 case QEvent::TabletPress:
2078 case QEvent::TabletRelease:
2079#endif
2080 {
2081 QInputEvent *ie = static_cast<QInputEvent *>(e);
2082 QGuiApplicationPrivate::modifier_buttons = ie->modifiers();
2083 break;
2084 }
2085 default:
2086 break;
2087 }
2088 }
2089}
2090
2091/*! \reimp
2092*/
2093bool QGuiApplication::notify(QObject *object, QEvent *event)
2094{
2095 Q_D(QGuiApplication);
2096 if (object->isWindowType()) {
2097 if (QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(static_cast<QWindow *>(object), event))
2098 return true; // Platform plugin ate the event
2099 }
2100
2101 switch (event->type()) {
2102 case QEvent::ApplicationDeactivate:
2103 case QEvent::OrientationChange:
2104 // Close all popups (triggers when switching applications
2105 // by pressing ALT-TAB on Windows, which is not received as a key event.
2106 // triggers when the screen rotates.)
2107 // This is also necessary on Wayland, and platforms where
2108 // QWindow::setMouseGrabEnabled(true) doesn't work.
2109 d->closeAllPopups();
2110 break;
2111 default:
2112 break;
2113 }
2114
2115 QGuiApplicationPrivate::captureGlobalModifierState(event);
2116
2117 return QCoreApplication::notify(object, event);
2118}
2119
2120/*! \reimp
2121*/
2122bool QGuiApplication::event(QEvent *e)
2123{
2124 switch (e->type()) {
2125 case QEvent::LanguageChange:
2126 // if the layout direction was set explicitly, then don't override it here
2127 if (layout_direction == Qt::LayoutDirectionAuto)
2128 setLayoutDirection(layout_direction);
2129 for (auto *topLevelWindow : QGuiApplication::topLevelWindows())
2130 postEvent(topLevelWindow, new QEvent(QEvent::LanguageChange));
2131 break;
2132 case QEvent::ApplicationFontChange:
2133 case QEvent::ApplicationPaletteChange:
2134 postEvent(QGuiApplication::styleHints(), e->clone());
2135 for (auto *topLevelWindow : QGuiApplication::topLevelWindows())
2136 postEvent(topLevelWindow, new QEvent(e->type()));
2137 break;
2138 case QEvent::ThemeChange:
2139 forwardEvent(QGuiApplication::styleHints(), e);
2140 for (auto *w : QGuiApplication::allWindows())
2141 forwardEvent(w, e);
2142 break;
2143 default:
2144 break;
2145 }
2146 return QCoreApplication::event(e);
2147}
2148
2149#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
2150/*!
2151 \internal
2152*/
2153bool QGuiApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
2154{
2155 QT_IGNORE_DEPRECATIONS(
2156 return QCoreApplication::compressEvent(event, receiver, postedEvents);
2157 )
2158}
2159#endif
2160
2161bool QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(QWindow *window, QEvent *event)
2162{
2163 if (!window)
2164 return false;
2165 QPlatformWindow *platformWindow = window->handle();
2166 if (!platformWindow)
2167 return false;
2168 // spontaneous events come from the platform integration already, we don't need to send the events back
2169 if (event->spontaneous())
2170 return false;
2171 // let the platform window do any handling it needs to as well
2172 return platformWindow->windowEvent(event);
2173}
2174
2175bool QGuiApplicationPrivate::processNativeEvent(QWindow *window, const QByteArray &eventType, void *message, qintptr *result)
2176{
2177 return window->nativeEvent(eventType, message, result);
2178}
2179
2180bool QGuiApplicationPrivate::isUsingVirtualKeyboard()
2181{
2182 static const bool usingVirtualKeyboard = getenv("QT_IM_MODULE") == QByteArrayView("qtvirtualkeyboard");
2183 return usingVirtualKeyboard;
2184}
2185
2186// If a virtual keyboard exists, forward mouse event
2187bool QGuiApplicationPrivate::maybeForwardEventToVirtualKeyboard(QEvent *e)
2188{
2189 if (!isUsingVirtualKeyboard()) {
2190 qCDebug(lcVirtualKeyboard) << "Virtual keyboard not supported.";
2191 return false;
2192 }
2193
2194 static QPointer<QWindow> virtualKeyboard;
2195 const QEvent::Type type = e->type();
2196 Q_ASSERT(type == QEvent::MouseButtonPress || type == QEvent::MouseButtonRelease);
2197 const auto me = static_cast<QMouseEvent *>(e);
2198 const QPointF posF = me->globalPosition();
2199 const QPoint pos = posF.toPoint();
2200
2201 // Is there a visible virtual keyboard at event position?
2202 if (!virtualKeyboard) {
2203 if (QWindow *win = QGuiApplication::topLevelAt(pos);
2204 win->inherits("QtVirtualKeyboard::InputView")) {
2205 virtualKeyboard = win;
2206 } else {
2207 qCDebug(lcVirtualKeyboard) << "Virtual keyboard supported, but inactive.";
2208 return false;
2209 }
2210 }
2211
2212 Q_ASSERT(virtualKeyboard);
2213 const bool virtualKeyboardUnderMouse = virtualKeyboard->isVisible()
2214 && virtualKeyboard->geometry().contains(pos);
2215
2216 if (!virtualKeyboardUnderMouse) {
2217 qCDebug(lcVirtualKeyboard) << type << "at" << pos << "is outside geometry"
2218 << virtualKeyboard->geometry() << "of" << virtualKeyboard.data();
2219 return false;
2220 }
2221
2222 QMouseEvent vkbEvent(type, virtualKeyboard->mapFromGlobal(pos), pos,
2223 me->button(), me->buttons(), me->modifiers(),
2224 me->pointingDevice());
2225
2226 QGuiApplication::sendEvent(virtualKeyboard, &vkbEvent);
2227 qCDebug(lcVirtualKeyboard) << "Forwarded" << type << "to" << virtualKeyboard.data()
2228 << "at" << pos;
2229
2230 return true;
2231}
2232
2233void Q_TRACE_INSTRUMENT(qtgui) QGuiApplicationPrivate::processWindowSystemEvent(QWindowSystemInterfacePrivate::WindowSystemEvent *e)
2234{
2235 Q_TRACE_PARAM_REPLACE(QWindowSystemInterfacePrivate::WindowSystemEvent *, int);
2236 Q_TRACE_SCOPE(QGuiApplicationPrivate_processWindowSystemEvent, e->type);
2237
2238 const bool haveGuiApplication = QGuiApplication::instance() && QGuiApplicationPrivate::instance();
2239 Q_ASSERT_X(haveGuiApplication, "QGuiApplication", "Asked to process QPA event without a QGuiApplication");
2240 if (!haveGuiApplication) {
2241 qWarning("QGuiApplication was asked to process QPA event without a QGuiApplication instance");
2242 e->eventAccepted = false;
2243 return;
2244 }
2245
2246 switch(e->type) {
2247 case QWindowSystemInterfacePrivate::Mouse:
2248 QGuiApplicationPrivate::processMouseEvent(static_cast<QWindowSystemInterfacePrivate::MouseEvent *>(e));
2249 break;
2250 case QWindowSystemInterfacePrivate::Wheel:
2251 QGuiApplicationPrivate::processWheelEvent(static_cast<QWindowSystemInterfacePrivate::WheelEvent *>(e));
2252 break;
2253 case QWindowSystemInterfacePrivate::Key:
2254 QGuiApplicationPrivate::processKeyEvent(static_cast<QWindowSystemInterfacePrivate::KeyEvent *>(e));
2255 break;
2256 case QWindowSystemInterfacePrivate::Touch:
2257 QGuiApplicationPrivate::processTouchEvent(static_cast<QWindowSystemInterfacePrivate::TouchEvent *>(e));
2258 break;
2259 case QWindowSystemInterfacePrivate::GeometryChange:
2260 QGuiApplicationPrivate::processGeometryChangeEvent(static_cast<QWindowSystemInterfacePrivate::GeometryChangeEvent*>(e));
2261 break;
2262 case QWindowSystemInterfacePrivate::Enter:
2263 QGuiApplicationPrivate::processEnterEvent(static_cast<QWindowSystemInterfacePrivate::EnterEvent *>(e));
2264 break;
2265 case QWindowSystemInterfacePrivate::Leave:
2266 QGuiApplicationPrivate::processLeaveEvent(static_cast<QWindowSystemInterfacePrivate::LeaveEvent *>(e));
2267 break;
2268 case QWindowSystemInterfacePrivate::FocusWindow:
2269 QGuiApplicationPrivate::processFocusWindowEvent(static_cast<QWindowSystemInterfacePrivate::FocusWindowEvent *>(e));
2270 break;
2271 case QWindowSystemInterfacePrivate::WindowStateChanged:
2272 QGuiApplicationPrivate::processWindowStateChangedEvent(static_cast<QWindowSystemInterfacePrivate::WindowStateChangedEvent *>(e));
2273 break;
2274 case QWindowSystemInterfacePrivate::WindowScreenChanged:
2275 QGuiApplicationPrivate::processWindowScreenChangedEvent(static_cast<QWindowSystemInterfacePrivate::WindowScreenChangedEvent *>(e));
2276 break;
2277 case QWindowSystemInterfacePrivate::WindowDevicePixelRatioChanged:
2278 QGuiApplicationPrivate::processWindowDevicePixelRatioChangedEvent(static_cast<QWindowSystemInterfacePrivate::WindowDevicePixelRatioChangedEvent *>(e));
2279 break;
2280 case QWindowSystemInterfacePrivate::SafeAreaMarginsChanged:
2281 QGuiApplicationPrivate::processSafeAreaMarginsChangedEvent(static_cast<QWindowSystemInterfacePrivate::SafeAreaMarginsChangedEvent *>(e));
2282 break;
2283 case QWindowSystemInterfacePrivate::ApplicationStateChanged: {
2284 QWindowSystemInterfacePrivate::ApplicationStateChangedEvent * changeEvent = static_cast<QWindowSystemInterfacePrivate::ApplicationStateChangedEvent *>(e);
2285 QGuiApplicationPrivate::setApplicationState(changeEvent->newState, changeEvent->forcePropagate); }
2286 break;
2287 case QWindowSystemInterfacePrivate::ApplicationTermination:
2288 QGuiApplicationPrivate::processApplicationTermination(e);
2289 break;
2290 case QWindowSystemInterfacePrivate::FlushEvents: {
2291 QWindowSystemInterfacePrivate::FlushEventsEvent *flushEventsEvent = static_cast<QWindowSystemInterfacePrivate::FlushEventsEvent *>(e);
2292 QWindowSystemInterface::deferredFlushWindowSystemEvents(flushEventsEvent->flags); }
2293 break;
2294 case QWindowSystemInterfacePrivate::Close:
2295 QGuiApplicationPrivate::processCloseEvent(
2296 static_cast<QWindowSystemInterfacePrivate::CloseEvent *>(e));
2297 break;
2298 case QWindowSystemInterfacePrivate::ScreenOrientation:
2299 QGuiApplicationPrivate::processScreenOrientationChange(
2300 static_cast<QWindowSystemInterfacePrivate::ScreenOrientationEvent *>(e));
2301 break;
2302 case QWindowSystemInterfacePrivate::ScreenGeometry:
2303 QGuiApplicationPrivate::processScreenGeometryChange(
2304 static_cast<QWindowSystemInterfacePrivate::ScreenGeometryEvent *>(e));
2305 break;
2306 case QWindowSystemInterfacePrivate::ScreenLogicalDotsPerInch:
2307 QGuiApplicationPrivate::processScreenLogicalDotsPerInchChange(
2308 static_cast<QWindowSystemInterfacePrivate::ScreenLogicalDotsPerInchEvent *>(e));
2309 break;
2310 case QWindowSystemInterfacePrivate::ScreenRefreshRate:
2311 QGuiApplicationPrivate::processScreenRefreshRateChange(
2312 static_cast<QWindowSystemInterfacePrivate::ScreenRefreshRateEvent *>(e));
2313 break;
2314 case QWindowSystemInterfacePrivate::ThemeChange:
2315 QGuiApplicationPrivate::processThemeChanged(
2316 static_cast<QWindowSystemInterfacePrivate::ThemeChangeEvent *>(e));
2317 break;
2318 case QWindowSystemInterfacePrivate::Expose:
2319 QGuiApplicationPrivate::processExposeEvent(static_cast<QWindowSystemInterfacePrivate::ExposeEvent *>(e));
2320 break;
2321 case QWindowSystemInterfacePrivate::Paint:
2322 QGuiApplicationPrivate::processPaintEvent(static_cast<QWindowSystemInterfacePrivate::PaintEvent *>(e));
2323 break;
2324 case QWindowSystemInterfacePrivate::Tablet:
2325 QGuiApplicationPrivate::processTabletEvent(
2326 static_cast<QWindowSystemInterfacePrivate::TabletEvent *>(e));
2327 break;
2328 case QWindowSystemInterfacePrivate::TabletEnterProximity:
2329 QGuiApplicationPrivate::processTabletEnterProximityEvent(
2330 static_cast<QWindowSystemInterfacePrivate::TabletEnterProximityEvent *>(e));
2331 break;
2332 case QWindowSystemInterfacePrivate::TabletLeaveProximity:
2333 QGuiApplicationPrivate::processTabletLeaveProximityEvent(
2334 static_cast<QWindowSystemInterfacePrivate::TabletLeaveProximityEvent *>(e));
2335 break;
2336#ifndef QT_NO_GESTURES
2337 case QWindowSystemInterfacePrivate::Gesture:
2338 QGuiApplicationPrivate::processGestureEvent(
2339 static_cast<QWindowSystemInterfacePrivate::GestureEvent *>(e));
2340 break;
2341#endif
2342 case QWindowSystemInterfacePrivate::PlatformPanel:
2343 QGuiApplicationPrivate::processPlatformPanelEvent(
2344 static_cast<QWindowSystemInterfacePrivate::PlatformPanelEvent *>(e));
2345 break;
2346 case QWindowSystemInterfacePrivate::FileOpen:
2347 QGuiApplicationPrivate::processFileOpenEvent(
2348 static_cast<QWindowSystemInterfacePrivate::FileOpenEvent *>(e));
2349 break;
2350#ifndef QT_NO_CONTEXTMENU
2351 case QWindowSystemInterfacePrivate::ContextMenu:
2352 QGuiApplicationPrivate::processContextMenuEvent(
2353 static_cast<QWindowSystemInterfacePrivate::ContextMenuEvent *>(e));
2354 break;
2355#endif
2356 case QWindowSystemInterfacePrivate::EnterWhatsThisMode:
2357 QGuiApplication::postEvent(QGuiApplication::instance(), new QEvent(QEvent::EnterWhatsThisMode));
2358 break;
2359 default:
2360 qWarning() << "Unknown user input event type:" << e->type;
2361 break;
2362 }
2363}
2364
2365/*! \internal
2366
2367 History is silent on why Qt splits mouse events that change position and
2368 button state at the same time. We believe that this was done to emulate mouse
2369 behavior on touch screens. If mouse tracking is enabled, we will get move
2370 events before the button is pressed. A touch panel does not generally give
2371 move events when not pressed, so without event splitting code path we would
2372 only see a press in a new location without any intervening moves. This could
2373 confuse code that is written for a real mouse. The same is true for mouse
2374 release events that change position, see tst_QWidget::touchEventSynthesizedMouseEvent()
2375 and tst_QWindow::generatedMouseMove() auto tests.
2376*/
2377void QGuiApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::MouseEvent *e)
2378{
2379 QEvent::Type type = QEvent::None;
2380 Qt::MouseButton button = Qt::NoButton;
2381 QWindow *window = e->window.data();
2382 const QPointingDevice *device = static_cast<const QPointingDevice *>(e->device);
2383 Q_ASSERT(device);
2384 QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(const_cast<QPointingDevice*>(device));
2385 bool positionChanged = QGuiApplicationPrivate::lastCursorPosition != e->globalPos;
2386 bool mouseMove = false;
2387 bool mousePress = false;
2388 const QPointF lastGlobalPosition = QGuiApplicationPrivate::lastCursorPosition;
2389 QPointF globalPoint = e->globalPos;
2390
2391 if (qIsNaN(e->globalPos.x()) || qIsNaN(e->globalPos.y())) {
2392 qWarning("QGuiApplicationPrivate::processMouseEvent: Got NaN in mouse position");
2393 return;
2394 }
2395
2396 type = e->buttonType;
2397 button = e->button;
2398
2399 if (type == QEvent::NonClientAreaMouseMove || type == QEvent::MouseMove)
2400 mouseMove = true;
2401 else if (type == QEvent::NonClientAreaMouseButtonPress || type == QEvent::MouseButtonPress)
2402 mousePress = true;
2403
2404 if (!mouseMove && positionChanged) {
2405 QWindowSystemInterfacePrivate::MouseEvent moveEvent(window, e->timestamp,
2406 e->localPos, e->globalPos, e->buttons ^ button, e->modifiers, Qt::NoButton,
2407 e->nonClientArea ? QEvent::NonClientAreaMouseMove : QEvent::MouseMove,
2408 e->source, e->nonClientArea, device, e->eventPointId);
2409 if (e->synthetic())
2410 moveEvent.flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
2411 processMouseEvent(&moveEvent); // mouse move excluding state change
2412 processMouseEvent(e); // the original mouse event
2413 return;
2414 }
2415 if (type == QEvent::MouseMove && !positionChanged) {
2416 // On Windows, and possibly other platforms, a touchpad can send a mouse move
2417 // that does not change position, between a press and a release. This may
2418 // confuse applications, so we always filter out these mouse events for
2419 // consistent behavior among platforms.
2420 return;
2421 }
2422
2423 modifier_buttons = e->modifiers;
2424 QPointF localPoint = e->localPos;
2425 bool doubleClick = false;
2426 auto persistentEPD = devPriv->pointById(0);
2427
2428 if (e->synthetic(); auto *originalDeviceEPD = devPriv->queryPointById(e->eventPointId))
2429 QMutableEventPoint::update(originalDeviceEPD->eventPoint, persistentEPD->eventPoint);
2430
2431 if (mouseMove) {
2432 QGuiApplicationPrivate::lastCursorPosition = globalPoint;
2433 const auto doubleClickDistance = (e->device && e->device->type() == QInputDevice::DeviceType::Mouse ?
2434 mouseDoubleClickDistance : touchDoubleTapDistance);
2435 const auto pressPos = persistentEPD->eventPoint.globalPressPosition();
2436 if (qAbs(globalPoint.x() - pressPos.x()) > doubleClickDistance ||
2437 qAbs(globalPoint.y() - pressPos.y()) > doubleClickDistance)
2438 mousePressButton = Qt::NoButton;
2439 } else {
2440 static unsigned long lastPressTimestamp = 0;
2441 static QPointer<QWindow> lastPressWindow = nullptr;
2442 mouse_buttons = e->buttons;
2443 if (mousePress) {
2444 ulong doubleClickInterval = static_cast<ulong>(QGuiApplication::styleHints()->mouseDoubleClickInterval());
2445 const auto timestampDelta = e->timestamp - lastPressTimestamp;
2446 doubleClick = timestampDelta > 0 && timestampDelta < doubleClickInterval
2447 && button == mousePressButton && lastPressWindow == e->window;
2448 mousePressButton = button;
2449 lastPressTimestamp = e ->timestamp;
2450 lastPressWindow = e->window;
2451 }
2452 }
2453
2454 if (e->nullWindow()) {
2455 window = QGuiApplication::topLevelAt(globalPoint.toPoint());
2456 if (window) {
2457 // Moves and the release following a press must go to the same
2458 // window, even if the cursor has moved on over another window.
2459 if (e->buttons != Qt::NoButton) {
2460 if (!currentMousePressWindow)
2461 currentMousePressWindow = window;
2462 else
2463 window = currentMousePressWindow;
2464 } else if (currentMousePressWindow) {
2465 window = currentMousePressWindow;
2466 currentMousePressWindow = nullptr;
2467 }
2468 localPoint = window->mapFromGlobal(globalPoint);
2469 }
2470 }
2471
2472 if (!window)
2473 return;
2474
2475#ifndef QT_NO_CURSOR
2476 if (!e->synthetic()) {
2477 if (const QScreen *screen = window->screen())
2478 if (QPlatformCursor *cursor = screen->handle()->cursor()) {
2479 const QPointF nativeLocalPoint = QHighDpi::toNativePixels(localPoint, screen);
2480 const QPointF nativeGlobalPoint = QHighDpi::toNativePixels(globalPoint, screen);
2481 QMouseEvent ev(type, nativeLocalPoint, nativeLocalPoint, nativeGlobalPoint,
2482 button, e->buttons, e->modifiers, e->source, device);
2483 // avoid incorrect velocity calculation: ev is in the native coordinate system,
2484 // but we need to consistently use the logical coordinate system for velocity
2485 // whenever QEventPoint::setTimestamp() is called
2486 ev.QInputEvent::setTimestamp(e->timestamp);
2487 cursor->pointerEvent(ev);
2488 }
2489 }
2490#endif
2491
2492 const auto *activePopup = activePopupWindow();
2493 if (type == QEvent::MouseButtonPress)
2494 active_popup_on_press = activePopup;
2495 if (window->d_func()->blockedByModalWindow && !activePopup) {
2496 // a modal window is blocking this window, don't allow mouse events through
2497 return;
2498 }
2499
2500 QMouseEvent ev(type, localPoint, localPoint, globalPoint, button, e->buttons, e->modifiers, e->source, device);
2501 Q_ASSERT(devPriv->pointById(0) == persistentEPD); // we don't expect reallocation in QPlatformCursor::pointerEvenmt()
2502 // restore globalLastPosition to avoid invalidating the velocity calculations,
2503 // because the QPlatformCursor mouse event above was in native coordinates
2504 QMutableEventPoint::setGlobalLastPosition(persistentEPD->eventPoint, lastGlobalPosition);
2505 persistentEPD = nullptr; // incoming and synth events can cause reallocation during delivery, so don't use this again
2506 // ev now contains a detached copy of the QEventPoint from QPointingDevicePrivate::activePoints
2507 ev.setTimestamp(e->timestamp);
2508
2509 if (activePopup && activePopup != window && (!popup_closed_on_press || type == QEvent::MouseButtonRelease)) {
2510 // If the popup handles the event, we're done.
2511 auto *handlingPopup = window->d_func()->forwardToPopup(&ev, active_popup_on_press);
2512 if (handlingPopup) {
2513 if (type == QEvent::MouseButtonPress)
2514 active_popup_on_press = handlingPopup;
2515 return;
2516 }
2517 }
2518
2519 if (doubleClick && (ev.type() == QEvent::MouseButtonPress)) {
2520 // QtBUG-25831, used to suppress delivery in qwidgetwindow.cpp
2521 QMutableSinglePointEvent::setDoubleClick(&ev, true);
2522 }
2523
2524 QGuiApplication::sendSpontaneousEvent(window, &ev);
2525 e->eventAccepted = ev.isAccepted();
2526 if (!e->synthetic() && !ev.isAccepted()
2527 && !e->nonClientArea
2528 && qApp->testAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents)) {
2529 QList<QWindowSystemInterface::TouchPoint> points;
2530 QWindowSystemInterface::TouchPoint point;
2531 point.id = 1;
2532 point.area = QHighDpi::toNativePixels(QRectF(globalPoint.x() - 2, globalPoint.y() - 2, 4, 4), window);
2533
2534 // only translate left button related events to
2535 // avoid strange touch event sequences when several
2536 // buttons are pressed
2537 if (type == QEvent::MouseButtonPress && button == Qt::LeftButton) {
2538 point.state = QEventPoint::State::Pressed;
2539 } else if (type == QEvent::MouseButtonRelease && button == Qt::LeftButton) {
2540 point.state = QEventPoint::State::Released;
2541 } else if (type == QEvent::MouseMove && (e->buttons & Qt::LeftButton)) {
2542 point.state = QEventPoint::State::Updated;
2543 } else {
2544 return;
2545 }
2546
2547 points << point;
2548
2549 QEvent::Type type;
2550 const QList<QEventPoint> &touchPoints =
2551 QWindowSystemInterfacePrivate::fromNativeTouchPoints(points, window, &type);
2552
2553 QWindowSystemInterfacePrivate::TouchEvent fake(window, e->timestamp, type, device, touchPoints, e->modifiers);
2554 fake.flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
2555 processTouchEvent(&fake);
2556 }
2557 if (doubleClick) {
2558 mousePressButton = Qt::NoButton;
2559 if (!e->window.isNull() || e->nullWindow()) { // QTBUG-36364, check if window closed in response to press
2560 const QEvent::Type doubleClickType = e->nonClientArea ? QEvent::NonClientAreaMouseButtonDblClick : QEvent::MouseButtonDblClick;
2561 QMouseEvent dblClickEvent(doubleClickType, localPoint, localPoint, globalPoint,
2562 button, e->buttons, e->modifiers, e->source, device);
2563 dblClickEvent.setTimestamp(e->timestamp);
2564 QGuiApplication::sendSpontaneousEvent(window, &dblClickEvent);
2565 }
2566 }
2567 if (type == QEvent::MouseButtonRelease && e->buttons == Qt::NoButton) {
2568 popup_closed_on_press = false;
2569 if (auto *persistentEPD = devPriv->queryPointById(0)) {
2570 ev.setExclusiveGrabber(persistentEPD->eventPoint, nullptr);
2571 ev.clearPassiveGrabbers(persistentEPD->eventPoint);
2572 }
2573 }
2574}
2575
2576void QGuiApplicationPrivate::processWheelEvent(QWindowSystemInterfacePrivate::WheelEvent *e)
2577{
2578#if QT_CONFIG(wheelevent)
2579 QWindow *window = e->window.data();
2580 QPointF globalPoint = e->globalPos;
2581 QPointF localPoint = e->localPos;
2582
2583 if (e->nullWindow()) {
2584 window = QGuiApplication::topLevelAt(globalPoint.toPoint());
2585 if (window)
2586 localPoint = window->mapFromGlobal(globalPoint);
2587 }
2588
2589 if (!window)
2590 return;
2591
2592 QGuiApplicationPrivate::lastCursorPosition = globalPoint;
2593 modifier_buttons = e->modifiers;
2594
2595 if (window->d_func()->blockedByModalWindow) {
2596 // a modal window is blocking this window, don't allow wheel events through
2597 return;
2598 }
2599
2600 const QPointingDevice *device = static_cast<const QPointingDevice *>(e->device);
2601 QWheelEvent ev(localPoint, globalPoint, e->pixelDelta, e->angleDelta,
2602 mouse_buttons, e->modifiers, e->phase, e->inverted, e->source, device);
2603 ev.setTimestamp(e->timestamp);
2604 QGuiApplication::sendSpontaneousEvent(window, &ev);
2605 e->eventAccepted = ev.isAccepted();
2606#else
2607 Q_UNUSED(e);
2608#endif // QT_CONFIG(wheelevent)
2609}
2610
2611void QGuiApplicationPrivate::processKeyEvent(QWindowSystemInterfacePrivate::KeyEvent *e)
2612{
2613 QWindow *window = e->window.data();
2614 modifier_buttons = e->modifiers;
2615 if (e->nullWindow())
2616 window = QGuiApplication::focusWindow();
2617
2618 if (!window) {
2619 e->eventAccepted = false;
2620 return;
2621 }
2622
2623#if !defined(Q_OS_MACOS)
2624 // FIXME: Include OS X in this code path by passing the key event through
2625 // QPlatformInputContext::filterEvent().
2626 if (e->keyType == QEvent::KeyPress) {
2627 if (QWindowSystemInterface::handleShortcutEvent(window, e->timestamp, e->key, e->modifiers,
2628 e->nativeScanCode, e->nativeVirtualKey, e->nativeModifiers, e->unicode, e->repeat, e->repeatCount)) {
2629 return;
2630 }
2631 }
2632#endif
2633
2634 QKeyEvent ev(e->keyType, e->key, e->modifiers,
2635 e->nativeScanCode, e->nativeVirtualKey, e->nativeModifiers,
2636 e->unicode, e->repeat, e->repeatCount);
2637 ev.setTimestamp(e->timestamp);
2638
2639 const auto *activePopup = activePopupWindow();
2640 if (activePopup && activePopup != window) {
2641 // If the popup handles the event, we're done.
2642 if (window->d_func()->forwardToPopup(&ev, active_popup_on_press))
2643 return;
2644 }
2645
2646 // only deliver key events when we have a window, and no modal window is blocking this window
2647
2648 if (!window->d_func()->blockedByModalWindow)
2649 QGuiApplication::sendSpontaneousEvent(window, &ev);
2650#ifdef Q_OS_ANDROID
2651 else
2652 ev.setAccepted(false);
2653#endif
2654 e->eventAccepted = ev.isAccepted();
2655}
2656
2657void QGuiApplicationPrivate::processEnterEvent(QWindowSystemInterfacePrivate::EnterEvent *e)
2658{
2659 if (!e->enter)
2660 return;
2661 if (e->enter.data()->d_func()->blockedByModalWindow) {
2662 // a modal window is blocking this window, don't allow enter events through
2663 return;
2664 }
2665
2666 currentMouseWindow = e->enter;
2667
2668 // TODO later: EnterEvent must report _which_ mouse entered the window; for now we assume primaryPointingDevice()
2669 QEnterEvent event(e->localPos, e->localPos, e->globalPos);
2670
2671 // Since we don't always track mouse moves that occur outside a window, any residual velocity
2672 // stored in the persistent QEventPoint may be inaccurate (especially in fast-moving autotests).
2673 // Reset the Kalman filter so that the velocity of the first mouse event after entering the window
2674 // will be based on a zero residual velocity (but the result can still be non-zero if the mouse
2675 // moves to a different position from where this enter event occurred; tests often do that).
2676 const QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(event.pointingDevice());
2677 auto epd = devPriv->queryPointById(event.points().first().id());
2678 Q_ASSERT(epd);
2679 QMutableEventPoint::setVelocity(epd->eventPoint, {});
2680
2681 QCoreApplication::sendSpontaneousEvent(e->enter.data(), &event);
2682}
2683
2684void QGuiApplicationPrivate::processLeaveEvent(QWindowSystemInterfacePrivate::LeaveEvent *e)
2685{
2686 if (!e->leave)
2687 return;
2688 if (e->leave.data()->d_func()->blockedByModalWindow) {
2689 // a modal window is blocking this window, don't allow leave events through
2690 return;
2691 }
2692
2693 currentMouseWindow = nullptr;
2694
2695 QEvent event(QEvent::Leave);
2696 QCoreApplication::sendSpontaneousEvent(e->leave.data(), &event);
2697}
2698
2699void QGuiApplicationPrivate::processFocusWindowEvent(QWindowSystemInterfacePrivate::FocusWindowEvent *e)
2700{
2701 QWindow *previous = QGuiApplicationPrivate::focus_window;
2702 QWindow *newFocus = e->focused.data();
2703
2704 if (previous == newFocus)
2705 return;
2706
2707 bool activatedPopup = false;
2708 if (newFocus) {
2709 if (QPlatformWindow *platformWindow = newFocus->handle())
2710 if (platformWindow->isAlertState())
2711 platformWindow->setAlertState(false);
2712 activatedPopup = (newFocus->flags() & Qt::WindowType_Mask) == Qt::Popup;
2713 if (activatedPopup)
2714 activatePopup(newFocus);
2715 }
2716
2717 QObject *previousFocusObject = previous ? previous->focusObject() : nullptr;
2718
2719 if (previous) {
2720 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange);
2721 QCoreApplication::sendSpontaneousEvent(previous, &focusAboutToChange);
2722 }
2723
2724 QGuiApplicationPrivate::focus_window = newFocus;
2725 if (!qApp)
2726 return;
2727
2728 if (previous) {
2729 Qt::FocusReason r = e->reason;
2730 if ((r == Qt::OtherFocusReason || r == Qt::ActiveWindowFocusReason) && activatedPopup)
2731 r = Qt::PopupFocusReason;
2732 QFocusEvent focusOut(QEvent::FocusOut, r);
2733 QCoreApplication::sendSpontaneousEvent(previous, &focusOut);
2734 QObject::disconnect(previous, SIGNAL(focusObjectChanged(QObject*)),
2735 qApp, SLOT(_q_updateFocusObject(QObject*)));
2736 } else if (!platformIntegration()->hasCapability(QPlatformIntegration::ApplicationState)) {
2737 setApplicationState(Qt::ApplicationActive);
2738 }
2739
2740 if (QGuiApplicationPrivate::focus_window) {
2741 Qt::FocusReason r = e->reason;
2742 if ((r == Qt::OtherFocusReason || r == Qt::ActiveWindowFocusReason) &&
2743 previous && (previous->flags() & Qt::Popup) == Qt::Popup)
2744 r = Qt::PopupFocusReason;
2745 QFocusEvent focusIn(QEvent::FocusIn, r);
2746 QCoreApplication::sendSpontaneousEvent(QGuiApplicationPrivate::focus_window, &focusIn);
2747 QObject::connect(QGuiApplicationPrivate::focus_window, SIGNAL(focusObjectChanged(QObject*)),
2748 qApp, SLOT(_q_updateFocusObject(QObject*)));
2749 } else if (!platformIntegration()->hasCapability(QPlatformIntegration::ApplicationState)) {
2750 setApplicationState(Qt::ApplicationInactive);
2751 }
2752
2753 if (auto *guiAppPrivate = QGuiApplicationPrivate::instance()) {
2754 guiAppPrivate->notifyActiveWindowChange(previous);
2755
2756 if (previousFocusObject != qApp->focusObject() ||
2757 // We are getting an activation change but there is no new focusObject, and we also
2758 // don't have a previousFocusObject in the previously active window anymore. This can
2759 // happen when window gets destroyed (see QWidgetWindow::focusObject returning nullptr
2760 // when already in the QWidget destructor), so update the focusObject to avoid dangling
2761 // pointers. See also QWidget::clearFocus(), which tries to cover for this as well.
2762 (previous && previousFocusObject == nullptr && qApp->focusObject() == nullptr)) {
2763 guiAppPrivate->_q_updateFocusObject(qApp->focusObject());
2764 }
2765 }
2766
2767 emit qApp->focusWindowChanged(newFocus);
2768 if (previous)
2769 emit previous->activeChanged();
2770 if (newFocus)
2771 emit newFocus->activeChanged();
2772}
2773
2774void QGuiApplicationPrivate::processWindowStateChangedEvent(QWindowSystemInterfacePrivate::WindowStateChangedEvent *wse)
2775{
2776 if (QWindow *window = wse->window.data()) {
2777 QWindowPrivate *windowPrivate = qt_window_private(window);
2778 const auto originalEffectiveState = QWindowPrivate::effectiveState(windowPrivate->windowState);
2779
2780 windowPrivate->windowState = wse->newState;
2781 const auto newEffectiveState = QWindowPrivate::effectiveState(windowPrivate->windowState);
2782 if (newEffectiveState != originalEffectiveState)
2783 emit window->windowStateChanged(newEffectiveState);
2784
2785 windowPrivate->updateVisibility();
2786
2787 QWindowStateChangeEvent e(wse->oldState);
2788 QGuiApplication::sendSpontaneousEvent(window, &e);
2789 }
2790}
2791
2792void QGuiApplicationPrivate::processWindowScreenChangedEvent(QWindowSystemInterfacePrivate::WindowScreenChangedEvent *wse)
2793{
2794 QWindow *window = wse->window.data();
2795 if (!window)
2796 return;
2797
2798 QScreen *screen = wse->screen.data();
2799 if (window->screen() == screen)
2800 return;
2801
2802 auto *windowPrivate = QWindowPrivate::get(window);
2803 QWindow *topLevelWindow = windowPrivate->topLevelWindow(QWindow::ExcludeTransients);
2804 if (window == topLevelWindow) {
2805 if (screen)
2806 topLevelWindow->d_func()->setTopLevelScreen(screen, false /* recreate */);
2807 else // Fall back to default behavior, and try to find some appropriate screen
2808 topLevelWindow->setScreen(nullptr);
2809 } else if (screen) {
2810 // Child windows reflect the screen of their top level parent. When a
2811 // window is reparented into a window that lives on a different screen
2812 // we don't need to update the top level screen, but do need to emit
2813 // screen changes for the child and its children,
2814 windowPrivate->emitScreenChangedRecursion(screen);
2815 }
2816}
2817
2818void QGuiApplicationPrivate::processWindowDevicePixelRatioChangedEvent(QWindowSystemInterfacePrivate::WindowDevicePixelRatioChangedEvent *wde)
2819{
2820 if (wde->window.isNull())
2821 return;
2822 QWindowPrivate::get(wde->window)->updateDevicePixelRatio();
2823}
2824
2825void QGuiApplicationPrivate::processSafeAreaMarginsChangedEvent(QWindowSystemInterfacePrivate::SafeAreaMarginsChangedEvent *wse)
2826{
2827 if (wse->window.isNull())
2828 return;
2829
2830 emit wse->window->safeAreaMarginsChanged(wse->window->safeAreaMargins());
2831
2832 QEvent event(QEvent::SafeAreaMarginsChange);
2833 QGuiApplication::sendSpontaneousEvent(wse->window, &event);
2834}
2835
2836void QGuiApplicationPrivate::processThemeChanged(QWindowSystemInterfacePrivate::ThemeChangeEvent *)
2837{
2838 // FIXME: Remove check once we ensure that the platform plugin is
2839 // torn down before QGuiApplication.
2840 if (!qGuiApp)
2841 return;
2842
2843 if (auto *guiAppPrivate = QGuiApplicationPrivate::instance())
2844 guiAppPrivate->handleThemeChanged();
2845
2846 QIconPrivate::clearIconCache();
2847
2848 QEvent themeChangeEvent(QEvent::ThemeChange);
2849 QGuiApplication::sendSpontaneousEvent(qGuiApp, &themeChangeEvent);
2850}
2851
2852void QGuiApplicationPrivate::handleThemeChanged()
2853{
2854 QStyleHintsPrivate::get(QGuiApplication::styleHints())->update(platformTheme());
2855 updatePalette();
2856
2857 QIconLoader::instance()->updateSystemTheme();
2858 QAbstractFileIconProviderPrivate::clearIconTypeCache();
2859
2860 if (!(applicationResourceFlags & ApplicationFontExplicitlySet)) {
2861 const auto locker = qt_scoped_lock(applicationFontMutex);
2862 clearFontUnlocked();
2863 initFontUnlocked();
2864 }
2865 initThemeHints();
2866}
2867
2868void QGuiApplicationPrivate::processGeometryChangeEvent(QWindowSystemInterfacePrivate::GeometryChangeEvent *e)
2869{
2870 if (e->window.isNull())
2871 return;
2872
2873 QWindow *window = e->window.data();
2874 if (!window)
2875 return;
2876
2877 const QRect lastReportedGeometry = window->d_func()->geometry;
2878 const QRect requestedGeometry = e->requestedGeometry;
2879 const QRect actualGeometry = e->newGeometry;
2880
2881 // We send size and move events only if the geometry has changed from
2882 // what was last reported, or if the user tried to set a new geometry,
2883 // but the window manager responded by keeping the old geometry. In the
2884 // latter case we send move/resize events with the same geometry as the
2885 // last reported geometry, to indicate that the window wasn't moved or
2886 // resized. Note that this logic does not apply to the property changes
2887 // of the window, as we don't treat them as part of this request/response
2888 // protocol of QWindow/QPA.
2889 const bool isResize = actualGeometry.size() != lastReportedGeometry.size()
2890 || requestedGeometry.size() != actualGeometry.size();
2891 const bool isMove = actualGeometry.topLeft() != lastReportedGeometry.topLeft()
2892 || requestedGeometry.topLeft() != actualGeometry.topLeft();
2893
2894 window->d_func()->geometry = actualGeometry;
2895
2896 if (isResize || window->d_func()->resizeEventPending) {
2897 QResizeEvent e(actualGeometry.size(), lastReportedGeometry.size());
2898 QGuiApplication::sendSpontaneousEvent(window, &e);
2899
2900 window->d_func()->resizeEventPending = false;
2901
2902 if (actualGeometry.width() != lastReportedGeometry.width())
2903 emit window->widthChanged(actualGeometry.width());
2904 if (actualGeometry.height() != lastReportedGeometry.height())
2905 emit window->heightChanged(actualGeometry.height());
2906 }
2907
2908 if (isMove) {
2909 //### frame geometry
2910 QMoveEvent e(actualGeometry.topLeft(), lastReportedGeometry.topLeft());
2911 QGuiApplication::sendSpontaneousEvent(window, &e);
2912
2913 if (actualGeometry.x() != lastReportedGeometry.x())
2914 emit window->xChanged(actualGeometry.x());
2915 if (actualGeometry.y() != lastReportedGeometry.y())
2916 emit window->yChanged(actualGeometry.y());
2917 }
2918}
2919
2920void QGuiApplicationPrivate::processCloseEvent(QWindowSystemInterfacePrivate::CloseEvent *e)
2921{
2922 if (e->window.isNull())
2923 return;
2924 if (e->window.data()->d_func()->blockedByModalWindow && !e->window.data()->d_func()->inClose) {
2925 // a modal window is blocking this window, don't allow close events through, unless they
2926 // originate from a call to QWindow::close.
2927 e->eventAccepted = false;
2928 return;
2929 }
2930
2931 QCloseEvent event;
2932 QGuiApplication::sendSpontaneousEvent(e->window.data(), &event);
2933
2934 e->eventAccepted = event.isAccepted();
2935}
2936
2937void QGuiApplicationPrivate::processFileOpenEvent(QWindowSystemInterfacePrivate::FileOpenEvent *e)
2938{
2939 if (e->url.isEmpty())
2940 return;
2941
2942 QFileOpenEvent event(e->url);
2943 QGuiApplication::sendSpontaneousEvent(qApp, &event);
2944}
2945
2946QGuiApplicationPrivate::TabletPointData &QGuiApplicationPrivate::tabletDevicePoint(qint64 deviceId)
2947{
2948 for (int i = 0; i < tabletDevicePoints.size(); ++i) {
2949 TabletPointData &pointData = tabletDevicePoints[i];
2950 if (pointData.deviceId == deviceId)
2951 return pointData;
2952 }
2953
2954 tabletDevicePoints.append(TabletPointData(deviceId));
2955 return tabletDevicePoints.last();
2956}
2957
2958void QGuiApplicationPrivate::processTabletEvent(QWindowSystemInterfacePrivate::TabletEvent *e)
2959{
2960#if QT_CONFIG(tabletevent)
2961 const auto device = static_cast<const QPointingDevice *>(e->device);
2962 TabletPointData &pointData = tabletDevicePoint(device->uniqueId().numericId());
2963
2964 QEvent::Type type = QEvent::TabletMove;
2965 if (e->buttons != pointData.state)
2966 type = (e->buttons > pointData.state) ? QEvent::TabletPress : QEvent::TabletRelease;
2967
2968 QWindow *window = e->window.data();
2969 modifier_buttons = e->modifiers;
2970
2971 bool localValid = true;
2972 // If window is null, pick one based on the global position and make sure all
2973 // subsequent events up to the release are delivered to that same window.
2974 // If window is given, just send to that.
2975 if (type == QEvent::TabletPress) {
2976 if (e->nullWindow()) {
2977 window = QGuiApplication::topLevelAt(e->global.toPoint());
2978 localValid = false;
2979 }
2980 if (!window)
2981 return;
2982 active_popup_on_press = activePopupWindow();
2983 pointData.target = window;
2984 } else {
2985 if (e->nullWindow()) {
2986 window = pointData.target;
2987 localValid = false;
2988 }
2989 if (type == QEvent::TabletRelease)
2990 pointData.target = nullptr;
2991 if (!window)
2992 return;
2993 }
2994 QPointF local = e->local;
2995 if (!localValid) {
2996 QPointF delta = e->global - e->global.toPoint();
2997 local = window->mapFromGlobal(e->global.toPoint()) + delta;
2998 }
2999
3000 // TODO stop deducing the button state change here: rather require it from the platform plugin, as with mouse events
3001 Qt::MouseButtons stateChange = e->buttons ^ pointData.state;
3002 Qt::MouseButton button = Qt::NoButton;
3003 for (int check = Qt::LeftButton; check <= int(Qt::MaxMouseButton); check = check << 1) {
3004 if (check & stateChange) {
3005 button = Qt::MouseButton(check);
3006 break;
3007 }
3008 }
3009
3010 const auto *activePopup = activePopupWindow();
3011 if (window->d_func()->blockedByModalWindow && !activePopup) {
3012 // a modal window is blocking this window, don't allow events through
3013 return;
3014 }
3015
3016 QTabletEvent tabletEvent(type, device, local, e->global,
3017 e->pressure, e->xTilt, e->yTilt,
3018 e->tangentialPressure, e->rotation, e->z,
3019 e->modifiers, button, e->buttons);
3020 tabletEvent.setAccepted(false);
3021 tabletEvent.setTimestamp(e->timestamp);
3022
3023 if (activePopup && activePopup != window) {
3024 // If the popup handles the event, we're done.
3025 if (window->d_func()->forwardToPopup(&tabletEvent, active_popup_on_press))
3026 return;
3027 }
3028
3029 QGuiApplication::sendSpontaneousEvent(window, &tabletEvent);
3030 pointData.state = e->buttons;
3031 if (!tabletEvent.isAccepted()
3032 && !QWindowSystemInterfacePrivate::TabletEvent::platformSynthesizesMouse
3033 && qApp->testAttribute(Qt::AA_SynthesizeMouseForUnhandledTabletEvents)) {
3034
3035 const QEvent::Type mouseType = [&]() {
3036 switch (type) {
3037 case QEvent::TabletPress: return QEvent::MouseButtonPress;
3038 case QEvent::TabletMove: return QEvent::MouseMove;
3039 case QEvent::TabletRelease: return QEvent::MouseButtonRelease;
3040 default: Q_UNREACHABLE();
3041 }
3042 }();
3043 QWindowSystemInterfacePrivate::MouseEvent mouseEvent(window, e->timestamp, e->local,
3044 e->global, e->buttons, e->modifiers, button, mouseType, Qt::MouseEventNotSynthesized, false, device);
3045 mouseEvent.flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
3046 qCDebug(lcPtrDispatch) << "synthesizing mouse from tablet event" << mouseType
3047 << e->local << button << e->buttons << e->modifiers;
3048 processMouseEvent(&mouseEvent);
3049 }
3050#else
3051 Q_UNUSED(e);
3052#endif
3053}
3054
3055void QGuiApplicationPrivate::processTabletEnterProximityEvent(QWindowSystemInterfacePrivate::TabletEnterProximityEvent *e)
3056{
3057#if QT_CONFIG(tabletevent)
3058 const QPointingDevice *dev = static_cast<const QPointingDevice *>(e->device);
3059 QTabletEvent ev(QEvent::TabletEnterProximity, dev, e->local, e->global,
3060 e->pressure, e->xTilt, e->yTilt,
3061 e->tangentialPressure, e->rotation, e->z,
3062 e->modifiers, Qt::NoButton,
3063 tabletDevicePoint(dev->uniqueId().numericId()).state);
3064 ev.setTimestamp(e->timestamp);
3065 QGuiApplication::sendSpontaneousEvent(qGuiApp, &ev);
3066#else
3067 Q_UNUSED(e);
3068#endif
3069}
3070
3071void QGuiApplicationPrivate::processTabletLeaveProximityEvent(QWindowSystemInterfacePrivate::TabletLeaveProximityEvent *e)
3072{
3073#if QT_CONFIG(tabletevent)
3074 const QPointingDevice *dev = static_cast<const QPointingDevice *>(e->device);
3075 QTabletEvent ev(QEvent::TabletLeaveProximity, dev, e->local, e->global,
3076 e->pressure, e->xTilt, e->yTilt,
3077 e->tangentialPressure, e->rotation, e->z,
3078 e->modifiers, Qt::NoButton,
3079 tabletDevicePoint(dev->uniqueId().numericId()).state);
3080 ev.setTimestamp(e->timestamp);
3081 QGuiApplication::sendSpontaneousEvent(qGuiApp, &ev);
3082#else
3083 Q_UNUSED(e);
3084#endif
3085}
3086
3087#ifndef QT_NO_GESTURES
3088void QGuiApplicationPrivate::processGestureEvent(QWindowSystemInterfacePrivate::GestureEvent *e)
3089{
3090 if (e->window.isNull())
3091 return;
3092
3093 const QPointingDevice *device = static_cast<const QPointingDevice *>(e->device);
3094 QNativeGestureEvent ev(e->type, device, e->fingerCount, e->pos, e->pos, e->globalPos, (e->intValue ? e->intValue : e->realValue),
3095 e->delta, e->sequenceId);
3096 ev.setTimestamp(e->timestamp);
3097 QGuiApplication::sendSpontaneousEvent(e->window, &ev);
3098}
3099#endif // QT_NO_GESTURES
3100
3101void QGuiApplicationPrivate::processPlatformPanelEvent(QWindowSystemInterfacePrivate::PlatformPanelEvent *e)
3102{
3103 if (!e->window)
3104 return;
3105
3106 if (e->window->d_func()->blockedByModalWindow) {
3107 // a modal window is blocking this window, don't allow events through
3108 return;
3109 }
3110
3111 QEvent ev(QEvent::PlatformPanel);
3112 QGuiApplication::sendSpontaneousEvent(e->window.data(), &ev);
3113}
3114
3115#ifndef QT_NO_CONTEXTMENU
3116void QGuiApplicationPrivate::processContextMenuEvent(QWindowSystemInterfacePrivate::ContextMenuEvent *e)
3117{
3118 if (!e->window || e->window->d_func()->blockedByModalWindow) {
3119 e->eventAccepted = false;
3120 return;
3121 }
3122
3123 QContextMenuEvent ev(e->pos, e->globalPos, e->modifiers, e->device);
3124 QGuiApplication::sendSpontaneousEvent(e->window.data(), &ev);
3125 e->eventAccepted = ev.isAccepted();
3126}
3127#endif
3128
3129void QGuiApplicationPrivate::processTouchEvent(QWindowSystemInterfacePrivate::TouchEvent *e)
3130{
3131 // The QPA side might need to know whether the touch event was accepted on
3132 // Qt side. In the flow below we might send multiple QTouchEvents, with
3133 // multiple QTouchPoints, and even synthesize mouse events if the touch
3134 // was not handled. Lacking a more granular reporting structure we treat
3135 // a single event acceptance as the QWSI event being accepted.
3136 e->eventAccepted = false;
3137
3138 if (!QInputDevicePrivate::isRegistered(e->device))
3139 return;
3140
3141 modifier_buttons = e->modifiers;
3142 QPointingDevice *device = const_cast<QPointingDevice *>(static_cast<const QPointingDevice *>(e->device));
3143 QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(device);
3144
3145 auto *guiAppPrivate = QGuiApplicationPrivate::instance();
3146
3147 if (e->touchType == QEvent::TouchCancel) {
3148 // The touch sequence has been canceled (e.g. by the compositor).
3149 // Send the TouchCancel to all windows with active touches and clean up.
3150 QTouchEvent touchEvent(QEvent::TouchCancel, device, e->modifiers);
3151 touchEvent.setTimestamp(e->timestamp);
3152 constexpr qsizetype Prealloc = decltype(devPriv->activePoints)::mapped_container_type::PreallocatedSize;
3153 QMinimalVarLengthFlatSet<QWindow *, Prealloc> windowsNeedingCancel;
3154
3155 for (auto &epd : devPriv->activePoints.values()) {
3156 if (QWindow *w = QMutableEventPoint::window(epd.eventPoint))
3157 windowsNeedingCancel.insert(w);
3158 }
3159
3160 for (QWindow *w : windowsNeedingCancel) {
3161 QGuiApplication::sendSpontaneousEvent(w, &touchEvent);
3162 e->eventAccepted |= touchEvent.isAccepted();
3163 }
3164
3165 if (!guiAppPrivate->synthesizedMousePoints.isEmpty() && !e->synthetic()) {
3166 for (QHash<QWindow *, SynthesizedMouseData>::const_iterator synthIt = guiAppPrivate->synthesizedMousePoints.constBegin(),
3167 synthItEnd = guiAppPrivate->synthesizedMousePoints.constEnd(); synthIt != synthItEnd; ++synthIt) {
3168 if (!synthIt->window)
3169 continue;
3170 QWindowSystemInterfacePrivate::MouseEvent fake(synthIt->window.data(),
3171 e->timestamp,
3172 synthIt->pos,
3173 synthIt->screenPos,
3174 Qt::NoButton,
3175 e->modifiers,
3176 Qt::LeftButton,
3177 QEvent::MouseButtonRelease,
3178 Qt::MouseEventNotSynthesized,
3179 false,
3180 device);
3181 fake.flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
3182 processMouseEvent(&fake);
3183 }
3184 guiAppPrivate->synthesizedMousePoints.clear();
3185 }
3186
3187 guiAppPrivate->lastTouchType = e->touchType;
3188 devPriv->activePoints.clear();
3189 return;
3190 }
3191
3192 // Prevent sending ill-formed event sequences: Cancel can only be followed by a Begin.
3193 if (guiAppPrivate->lastTouchType == QEvent::TouchCancel && e->touchType != QEvent::TouchBegin)
3194 return;
3195
3196 guiAppPrivate->lastTouchType = e->touchType;
3197
3198 QPointer<QWindow> window = e->window; // the platform hopefully tells us which window received the event
3199 QVarLengthArray<QMutableTouchEvent, 2> touchEvents;
3200
3201 // For each temporary QEventPoint from the QPA TouchEvent:
3202 // - update the persistent QEventPoint in QPointingDevicePrivate::activePoints with current values
3203 // - determine which window to deliver it to
3204 // - add it to the QTouchEvent instance for that window (QMutableTouchEvent::target() will be QWindow*, for now)
3205 for (auto &tempPt : e->points) {
3206 // update state
3207 auto epd = devPriv->pointById(tempPt.id());
3208 auto &ep = epd->eventPoint;
3209 epd->eventPoint.setAccepted(false);
3210 switch (tempPt.state()) {
3211 case QEventPoint::State::Pressed:
3212 // On touchpads, send all touch points to the same window.
3213 if (!window && e->device && e->device->type() == QInputDevice::DeviceType::TouchPad)
3214 window = devPriv->firstActiveWindow();
3215 // If the QPA event didn't tell us which window, find the one under the touchpoint position.
3216 if (!window)
3217 window = QGuiApplication::topLevelAt(tempPt.globalPosition().toPoint());
3218 QMutableEventPoint::setWindow(ep, window);
3219 active_popup_on_press = activePopupWindow();
3220 break;
3221
3222 case QEventPoint::State::Released:
3223 if (Q_UNLIKELY(!window.isNull() && window != QMutableEventPoint::window(ep)))
3224 qCDebug(lcPtrDispatch) << "delivering touch release to same window"
3225 << QMutableEventPoint::window(ep) << "not" << window.data();
3226 window = QMutableEventPoint::window(ep);
3227 break;
3228
3229 default: // update or stationary
3230 if (Q_UNLIKELY(!window.isNull() && window != QMutableEventPoint::window(ep)))
3231 qCDebug(lcPtrDispatch) << "delivering touch update to same window"
3232 << QMutableEventPoint::window(ep) << "not" << window.data();
3233 window = QMutableEventPoint::window(ep);
3234 break;
3235 }
3236 // If we somehow still don't have a window, we can't deliver this touchpoint. (should never happen)
3237 if (Q_UNLIKELY(!window)) {
3238 qCDebug(lcPtrDispatch) << "skipping" << &tempPt << ": no target window";
3239 continue;
3240 }
3241 QMutableEventPoint::update(tempPt, ep);
3242
3243 Q_ASSERT(window.data() != nullptr);
3244
3245 // make the *scene* position the same as the *global* position
3246 QMutableEventPoint::setScenePosition(ep, tempPt.globalPosition());
3247
3248 // store the scene position as local position, for now
3249 QMutableEventPoint::setPosition(ep, window->mapFromGlobal(tempPt.globalPosition()));
3250
3251 // setTimeStamp has side effects, so we do it last
3252 QMutableEventPoint::setTimestamp(ep, e->timestamp);
3253
3254 // add the touchpoint to the event that will be delivered to the window
3255 bool added = false;
3256 for (QMutableTouchEvent &ev : touchEvents) {
3257 if (ev.target() == window.data()) {
3258 ev.addPoint(ep);
3259 added = true;
3260 break;
3261 }
3262 }
3263 if (!added) {
3264 QMutableTouchEvent mte(e->touchType, device, e->modifiers, {ep});
3265 mte.setTimestamp(e->timestamp);
3266 mte.setTarget(window.data());
3267 touchEvents.append(mte);
3268 }
3269 }
3270
3271 if (touchEvents.isEmpty())
3272 return;
3273
3274 for (QMutableTouchEvent &touchEvent : touchEvents) {
3275 QWindow *window = static_cast<QWindow *>(touchEvent.target());
3276
3277 QEvent::Type eventType;
3278 switch (touchEvent.touchPointStates()) {
3279 case QEventPoint::State::Pressed:
3280 eventType = QEvent::TouchBegin;
3281 break;
3282 case QEventPoint::State::Released:
3283 eventType = QEvent::TouchEnd;
3284 break;
3285 default:
3286 eventType = QEvent::TouchUpdate;
3287 break;
3288 }
3289
3290 const auto *activePopup = activePopupWindow();
3291 if (window->d_func()->blockedByModalWindow && !activePopup) {
3292 // a modal window is blocking this window, don't allow touch events through
3293
3294 // QTBUG-37371 temporary fix; TODO: revisit when we have a forwarding solution
3295 if (touchEvent.type() == QEvent::TouchEnd) {
3296 // but don't leave dangling state: e.g.
3297 // QQuickWindowPrivate::itemForTouchPointId needs to be cleared.
3298 QTouchEvent touchEvent(QEvent::TouchCancel, device, e->modifiers);
3299 touchEvent.setTimestamp(e->timestamp);
3300 QGuiApplication::sendSpontaneousEvent(window, &touchEvent);
3301 }
3302 continue;
3303 }
3304
3305 if (activePopup && activePopup != window) {
3306 // If the popup handles the event, we're done.
3307 if (window->d_func()->forwardToPopup(&touchEvent, active_popup_on_press))
3308 return;
3309 }
3310
3311 // Note: after the call to sendSpontaneousEvent, touchEvent.position() will have
3312 // changed to reflect the local position inside the last (random) widget it tried
3313 // to deliver the touch event to, and will therefore be invalid afterwards.
3314 QGuiApplication::sendSpontaneousEvent(window, &touchEvent);
3315 e->eventAccepted |= touchEvent.isAccepted();
3316
3317 if (!e->synthetic() && !touchEvent.isAccepted() && qApp->testAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents)) {
3318 // exclude devices which generate their own mouse events
3319 if (!(touchEvent.device()->capabilities().testFlag(QInputDevice::Capability::MouseEmulation))) {
3320
3321 QEvent::Type mouseEventType = QEvent::MouseMove;
3322 Qt::MouseButton button = Qt::NoButton;
3323 Qt::MouseButtons buttons = Qt::LeftButton;
3324 if (eventType == QEvent::TouchBegin || m_fakeMouseSourcePointId < 0) {
3325 m_fakeMouseSourcePointId = touchEvent.point(0).id();
3326 qCDebug(lcPtrDispatch) << "synthesizing mouse events from touchpoint" << m_fakeMouseSourcePointId;
3327 }
3328 if (m_fakeMouseSourcePointId >= 0) {
3329 const auto *touchPoint = touchEvent.pointById(m_fakeMouseSourcePointId);
3330 if (touchPoint) {
3331 switch (touchPoint->state()) {
3332 case QEventPoint::State::Pressed:
3333 mouseEventType = QEvent::MouseButtonPress;
3334 button = Qt::LeftButton;
3335 break;
3336 case QEventPoint::State::Released:
3337 mouseEventType = QEvent::MouseButtonRelease;
3338 button = Qt::LeftButton;
3339 buttons = Qt::NoButton;
3340 Q_ASSERT(m_fakeMouseSourcePointId == touchPoint->id());
3341 m_fakeMouseSourcePointId = -1;
3342 break;
3343 default:
3344 break;
3345 }
3346 if (touchPoint->state() != QEventPoint::State::Released) {
3347 guiAppPrivate->synthesizedMousePoints.insert(window, SynthesizedMouseData(
3348 touchPoint->position(), touchPoint->globalPosition(), window));
3349 }
3350 // All touch events that are not accepted by the application will be translated to
3351 // left mouse button events instead (see AA_SynthesizeMouseForUnhandledTouchEvents docs).
3352 // Sending a QPA event (rather than simply sending a QMouseEvent) takes care of
3353 // side-effects such as double-click synthesis.
3354 QWindowSystemInterfacePrivate::MouseEvent fake(window, e->timestamp,
3355 window->mapFromGlobal(touchPoint->globalPosition().toPoint()),
3356 touchPoint->globalPosition(),
3357 buttons,
3358 e->modifiers,
3359 button,
3360 mouseEventType,
3361 Qt::MouseEventSynthesizedByQt,
3362 false,
3363 device,
3364 touchPoint->id());
3365 fake.flags |= QWindowSystemInterfacePrivate::WindowSystemEvent::Synthetic;
3366 processMouseEvent(&fake);
3367 e->eventAccepted |= fake.eventAccepted;
3368 }
3369 }
3370 if (eventType == QEvent::TouchEnd)
3371 guiAppPrivate->synthesizedMousePoints.clear();
3372 }
3373 }
3374 }
3375
3376 // Remove released points from QPointingDevicePrivate::activePoints only after the event is
3377 // delivered. Widgets and Qt Quick are allowed to access them at any time before this.
3378 for (const QEventPoint &touchPoint : e->points) {
3379 if (touchPoint.state() == QEventPoint::State::Released)
3380 devPriv->removePointById(touchPoint.id());
3381 }
3382}
3383
3384void QGuiApplicationPrivate::processScreenOrientationChange(QWindowSystemInterfacePrivate::ScreenOrientationEvent *e)
3385{
3386 // This operation only makes sense after the QGuiApplication constructor runs
3387 if (QCoreApplication::startingUp())
3388 return;
3389
3390 if (!e->screen)
3391 return;
3392
3393 QScreen *s = e->screen.data();
3394 s->d_func()->orientation = e->orientation;
3395
3396 emit s->orientationChanged(s->orientation());
3397
3398 QScreenOrientationChangeEvent event(s, s->orientation());
3399 QCoreApplication::sendEvent(QCoreApplication::instance(), &event);
3400}
3401
3402void QGuiApplicationPrivate::processScreenGeometryChange(QWindowSystemInterfacePrivate::ScreenGeometryEvent *e)
3403{
3404 // This operation only makes sense after the QGuiApplication constructor runs
3405 if (QCoreApplication::startingUp())
3406 return;
3407
3408 if (!e->screen)
3409 return;
3410
3411 {
3412 QScreen *s = e->screen.data();
3413 QScreenPrivate::UpdateEmitter updateEmitter(s);
3414
3415 // Note: The incoming geometries have already been scaled by QHighDpi
3416 // in the QWSI layer, so we don't need to call updateGeometry() here.
3417 s->d_func()->geometry = e->geometry;
3418 s->d_func()->availableGeometry = e->availableGeometry;
3419
3420 s->d_func()->updatePrimaryOrientation();
3421 }
3422
3423 resetCachedDevicePixelRatio();
3424}
3425
3426void QGuiApplicationPrivate::processScreenLogicalDotsPerInchChange(QWindowSystemInterfacePrivate::ScreenLogicalDotsPerInchEvent *e)
3427{
3428 // This operation only makes sense after the QGuiApplication constructor runs
3429 if (QCoreApplication::startingUp())
3430 return;
3431
3432 QHighDpiScaling::updateHighDpiScaling();
3433
3434 if (!e->screen)
3435 return;
3436
3437 {
3438 QScreen *s = e->screen.data();
3439 QScreenPrivate::UpdateEmitter updateEmitter(s);
3440 s->d_func()->logicalDpi = QDpi(e->dpiX, e->dpiY);
3441 s->d_func()->updateGeometry();
3442 }
3443
3444 for (QWindow *window : QGuiApplication::allWindows())
3445 if (window->screen() == e->screen)
3446 QWindowPrivate::get(window)->updateDevicePixelRatio();
3447
3448 resetCachedDevicePixelRatio();
3449}
3450
3451void QGuiApplicationPrivate::processScreenRefreshRateChange(QWindowSystemInterfacePrivate::ScreenRefreshRateEvent *e)
3452{
3453 // This operation only makes sense after the QGuiApplication constructor runs
3454 if (QCoreApplication::startingUp())
3455 return;
3456
3457 if (!e->screen)
3458 return;
3459
3460 QScreen *s = e->screen.data();
3461 qreal rate = e->rate;
3462 // safeguard ourselves against buggy platform behavior...
3463 if (rate < 1.0)
3464 rate = 60.0;
3465 if (!qFuzzyCompare(s->d_func()->refreshRate, rate)) {
3466 s->d_func()->refreshRate = rate;
3467 emit s->refreshRateChanged(s->refreshRate());
3468 }
3469}
3470
3471void QGuiApplicationPrivate::processExposeEvent(QWindowSystemInterfacePrivate::ExposeEvent *e)
3472{
3473 if (!e->window)
3474 return;
3475
3476 QWindow *window = e->window.data();
3477 if (!window)
3478 return;
3479 QWindowPrivate *p = qt_window_private(window);
3480
3481 if (e->isExposed) {
3482 // If the window has been automatically positioned or resized by the
3483 // window manager, we now assume those have taken effect, even for
3484 // asynchronous window managers. From this point on we want the window
3485 // to keep its geometry, even when recreated.
3486 p->positionAutomatic = false;
3487 p->resizeAutomatic = false;
3488 }
3489
3490 if (!p->receivedExpose) {
3491 if (p->resizeEventPending) {
3492 // as a convenience for plugins, send a resize event before the first expose event if they haven't done so
3493 // window->geometry() should have a valid size as soon as a handle exists.
3494 QResizeEvent e(window->geometry().size(), p->geometry.size());
3495 QGuiApplication::sendSpontaneousEvent(window, &e);
3496
3497 p->resizeEventPending = false;
3498 }
3499
3500 // FIXME: It would logically make sense to set this _after_ we've sent the
3501 // expose event to the window, to mark that it now has received an expose.
3502 // But some parts of Qt (mis)use this private member to check whether the
3503 // window has been mapped yet, which they do in code that is triggered
3504 // by the very same expose event we send below. To keep the code working
3505 // we need to set the variable up front, until the code has been fixed.
3506 p->receivedExpose = true;
3507 }
3508
3509 // If the platform does not send paint events we need to synthesize them from expose events
3510 const bool shouldSynthesizePaintEvents = !platformIntegration()->hasCapability(QPlatformIntegration::PaintEvents);
3511
3512 const bool wasExposed = p->exposed;
3513 p->exposed = e->isExposed && window->screen();
3514
3515 // We expect that the platform plugins send DevicePixelRatioChange events.
3516 // As a fail-safe make a final check here to make sure the cached DPR value is
3517 // always up to date before sending the expose event.
3518 if (e->isExposed && !e->region.isEmpty()) {
3519 const bool dprWasChanged = QWindowPrivate::get(window)->updateDevicePixelRatio();
3520 if (dprWasChanged)
3521 qWarning() << "The cached device pixel ratio value was stale on window expose. "
3522 << "Please file a QTBUG which explains how to reproduce.";
3523 }
3524
3525 // We treat expose events for an already exposed window as paint events
3526 if (wasExposed && p->exposed && shouldSynthesizePaintEvents) {
3527 QPaintEvent paintEvent(e->region);
3528 QCoreApplication::sendSpontaneousEvent(window, &paintEvent);
3529 if (paintEvent.isAccepted())
3530 return; // No need to send expose
3531
3532 // The paint event was not accepted, so we fall through and send an expose
3533 // event instead, to maintain compatibility for clients that haven't adopted
3534 // paint events yet.
3535 }
3536
3537 QExposeEvent exposeEvent(e->region);
3538 QCoreApplication::sendSpontaneousEvent(window, &exposeEvent);
3539 e->eventAccepted = exposeEvent.isAccepted();
3540
3541 // If the window was just exposed we also need to send a paint event,
3542 // so that clients that implement paint events will draw something.
3543 // Note that we we can not skip this based on the expose event being
3544 // accepted, as clients may implement exposeEvent to track the state
3545 // change, but without drawing anything.
3546 if (!wasExposed && p->exposed && shouldSynthesizePaintEvents) {
3547 QPaintEvent paintEvent(e->region);
3548 QCoreApplication::sendSpontaneousEvent(window, &paintEvent);
3549 }
3550}
3551
3552void QGuiApplicationPrivate::processPaintEvent(QWindowSystemInterfacePrivate::PaintEvent *e)
3553{
3554 Q_ASSERT_X(platformIntegration()->hasCapability(QPlatformIntegration::PaintEvents), "QGuiApplication",
3555 "The platform sent paint events without claiming support for it in QPlatformIntegration::capabilities()");
3556
3557 if (!e->window)
3558 return;
3559
3560 QPaintEvent paintEvent(e->region);
3561 QCoreApplication::sendSpontaneousEvent(e->window, &paintEvent);
3562
3563 // We report back the accepted state to the platform, so that it can
3564 // decide when the best time to send the fallback expose event is.
3565 e->eventAccepted = paintEvent.isAccepted();
3566}
3567
3568#if QT_CONFIG(draganddrop)
3569
3570/*! \internal
3571
3572 This function updates an internal state to keep the source compatibility.
3573 ### Qt 6 - Won't need after QTBUG-73829
3574*/
3575static void updateMouseAndModifierButtonState(Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers)
3576{
3577 QGuiApplicationPrivate::mouse_buttons = buttons;
3578 QGuiApplicationPrivate::modifier_buttons = modifiers;
3579}
3580
3581QPlatformDragQtResponse QGuiApplicationPrivate::processDrag(QWindow *w, const QMimeData *dropData,
3582 const QPoint &p, Qt::DropActions supportedActions,
3583 Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers)
3584{
3585 updateMouseAndModifierButtonState(buttons, modifiers);
3586
3587 static Qt::DropAction lastAcceptedDropAction = Qt::IgnoreAction;
3588 QPlatformDrag *platformDrag = platformIntegration()->drag();
3589 if (!platformDrag || (w && w->d_func()->blockedByModalWindow)) {
3590 lastAcceptedDropAction = Qt::IgnoreAction;
3591 return QPlatformDragQtResponse(false, lastAcceptedDropAction, QRect());
3592 }
3593
3594 if (!dropData) {
3595 currentDragWindow = nullptr;
3596 QDragLeaveEvent e;
3597 QGuiApplication::sendEvent(w, &e);
3598 lastAcceptedDropAction = Qt::IgnoreAction;
3599 return QPlatformDragQtResponse(false, lastAcceptedDropAction, QRect());
3600 }
3601 QDragMoveEvent me(QPointF(p), supportedActions, dropData, buttons, modifiers);
3602
3603 if (w != currentDragWindow) {
3604 lastAcceptedDropAction = Qt::IgnoreAction;
3605 if (currentDragWindow) {
3606 QDragLeaveEvent e;
3607 QGuiApplication::sendEvent(currentDragWindow, &e);
3608 }
3609 currentDragWindow = w;
3610 QDragEnterEvent e(QPointF(p), supportedActions, dropData, buttons, modifiers);
3611 QGuiApplication::sendEvent(w, &e);
3612 if (e.isAccepted() && e.dropAction() != Qt::IgnoreAction)
3613 lastAcceptedDropAction = e.dropAction();
3614 }
3615
3616 // Handling 'DragEnter' should suffice for the application.
3617 if (lastAcceptedDropAction != Qt::IgnoreAction
3618 && (supportedActions & lastAcceptedDropAction)) {
3619 me.setDropAction(lastAcceptedDropAction);
3620 me.accept();
3621 }
3622 QGuiApplication::sendEvent(w, &me);
3623 lastAcceptedDropAction = me.isAccepted() ?
3624 me.dropAction() : Qt::IgnoreAction;
3625 return QPlatformDragQtResponse(me.isAccepted(), lastAcceptedDropAction, me.answerRect());
3626}
3627
3628QPlatformDropQtResponse QGuiApplicationPrivate::processDrop(QWindow *w, const QMimeData *dropData,
3629 const QPoint &p, Qt::DropActions supportedActions,
3630 Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers)
3631{
3632 updateMouseAndModifierButtonState(buttons, modifiers);
3633
3634 currentDragWindow = nullptr;
3635
3636 QDropEvent de(p, supportedActions, dropData, buttons, modifiers);
3637 QGuiApplication::sendEvent(w, &de);
3638
3639 Qt::DropAction acceptedAction = de.isAccepted() ? de.dropAction() : Qt::IgnoreAction;
3640 QPlatformDropQtResponse response(de.isAccepted(),acceptedAction);
3641 return response;
3642}
3643
3644#endif // QT_CONFIG(draganddrop)
3645
3646#ifndef QT_NO_CLIPBOARD
3647/*!
3648 Returns the object for interacting with the clipboard.
3649*/
3650QClipboard * QGuiApplication::clipboard()
3651{
3652 if (QGuiApplicationPrivate::qt_clipboard == nullptr) {
3653 if (!qApp) {
3654 qWarning("QGuiApplication: Must construct a QGuiApplication before accessing a QClipboard");
3655 return nullptr;
3656 }
3657 QGuiApplicationPrivate::qt_clipboard = new QClipboard(nullptr);
3658 }
3659 return QGuiApplicationPrivate::qt_clipboard;
3660}
3661#endif
3662
3663/*!
3664 \since 5.4
3665 \fn void QGuiApplication::paletteChanged(const QPalette &palette)
3666 \deprecated [6.0] Handle QEvent::ApplicationPaletteChange instead.
3667
3668 This signal is emitted when the \a palette of the application changes. Use
3669 QEvent::ApplicationPaletteChanged instead.
3670
3671 \sa palette()
3672*/
3673
3674/*!
3675 Returns the current application palette.
3676
3677 Roles that have not been explicitly set will reflect the system's platform theme.
3678
3679 \sa setPalette()
3680*/
3681
3682QPalette QGuiApplication::palette()
3683{
3684 if (!QGuiApplicationPrivate::app_pal)
3685 QGuiApplicationPrivate::updatePalette();
3686
3687 return *QGuiApplicationPrivate::app_pal;
3688}
3689
3690void QGuiApplicationPrivate::updatePalette()
3691{
3692 if (app_pal) {
3693 if (setPalette(*app_pal) && qGuiApp)
3694 qGuiApp->d_func()->handlePaletteChanged();
3695 } else {
3696 setPalette(QPalette());
3697 }
3698}
3699
3700QEvent::Type QGuiApplicationPrivate::contextMenuEventType()
3701{
3702 switch (QGuiApplication::styleHints()->contextMenuTrigger()) {
3703 case Qt::ContextMenuTrigger::Press: return QEvent::MouseButtonPress;
3704 case Qt::ContextMenuTrigger::Release: return QEvent::MouseButtonRelease;
3705 }
3706 return QEvent::None;
3707}
3708
3709void QGuiApplicationPrivate::clearPalette()
3710{
3711 delete app_pal;
3712 app_pal = nullptr;
3713}
3714
3715/*!
3716 Changes the application palette to \a pal.
3717
3718 The color roles from this palette are combined with the system's platform
3719 theme to form the application's final palette.
3720
3721 \sa palette()
3722*/
3723void QGuiApplication::setPalette(const QPalette &pal)
3724{
3725 if (QGuiApplicationPrivate::setPalette(pal) && qGuiApp)
3726 qGuiApp->d_func()->handlePaletteChanged();
3727}
3728
3729bool QGuiApplicationPrivate::setPalette(const QPalette &palette)
3730{
3731 // Resolve the palette against the theme palette, filling in
3732 // any missing roles, while keeping the original resolve mask.
3733 QPalette basePalette = qGuiApp ? qGuiApp->d_func()->basePalette() : Qt::gray;
3734 basePalette.setResolveMask(0); // The base palette only contributes missing colors roles
3735 QPalette resolvedPalette = palette.resolve(basePalette);
3736
3737 if (app_pal && resolvedPalette == *app_pal && resolvedPalette.resolveMask() == app_pal->resolveMask())
3738 return false;
3739
3740 if (!app_pal)
3741 app_pal = new QPalette(resolvedPalette);
3742 else
3743 *app_pal = resolvedPalette;
3744
3745 QCoreApplication::setAttribute(Qt::AA_SetPalette, app_pal->resolveMask() != 0);
3746
3747 return true;
3748}
3749
3750/*
3751 Returns the base palette used to fill in missing roles in
3752 the current application palette.
3753
3754 Normally this is the theme palette, but QApplication
3755 overrides this for compatibility reasons.
3756*/
3757QPalette QGuiApplicationPrivate::basePalette() const
3758{
3759 const auto pf = platformTheme();
3760 return pf && pf->palette() ? *pf->palette() : Qt::gray;
3761}
3762
3763void QGuiApplicationPrivate::handlePaletteChanged(const char *className)
3764{
3765#if QT_DEPRECATED_SINCE(6, 0)
3766 if (!className) {
3767 Q_ASSERT(app_pal);
3768QT_WARNING_PUSH
3769QT_WARNING_DISABLE_DEPRECATED
3770 emit qGuiApp->paletteChanged(*QGuiApplicationPrivate::app_pal);
3771QT_WARNING_POP
3772 }
3773#else
3774 Q_UNUSED(className);
3775#endif // QT_DEPRECATED_SINCE(6, 0)
3776
3777 if (is_app_running && !is_app_closing) {
3778 QEvent event(QEvent::ApplicationPaletteChange);
3779 QGuiApplication::sendEvent(qGuiApp, &event);
3780 }
3781}
3782
3783void QGuiApplicationPrivate::applyWindowGeometrySpecificationTo(QWindow *window)
3784{
3785 windowGeometrySpecification.applyTo(window);
3786}
3787
3788/*!
3789 \since 5.11
3790 \fn void QGuiApplication::fontChanged(const QFont &font)
3791 \deprecated [6.0] Handle QEvent::ApplicationFontChange instead.
3792
3793 This signal is emitted when the \a font of the application changes. Use
3794 QEvent::ApplicationFontChanged instead.
3795
3796 \sa font()
3797*/
3798
3799/*!
3800 Returns the default application font.
3801
3802 \sa setFont()
3803*/
3804QFont QGuiApplication::font()
3805{
3806 const auto locker = qt_scoped_lock(applicationFontMutex);
3807 if (!QGuiApplicationPrivate::instance() && !QGuiApplicationPrivate::app_font) {
3808 qWarning("QGuiApplication::font(): no QGuiApplication instance and no application font set.");
3809 return QFont(); // in effect: QFont((QFontPrivate*)nullptr), so no recursion
3810 }
3811 initFontUnlocked();
3812 return *QGuiApplicationPrivate::app_font;
3813}
3814
3815/*!
3816 Changes the default application font to \a font.
3817
3818 \sa font()
3819*/
3820void QGuiApplication::setFont(const QFont &font)
3821{
3822 auto locker = qt_unique_lock(applicationFontMutex);
3823 const bool emitChange = !QGuiApplicationPrivate::app_font
3824 || (*QGuiApplicationPrivate::app_font != font);
3825 if (!QGuiApplicationPrivate::app_font)
3826 QGuiApplicationPrivate::app_font = new QFont(font);
3827 else
3828 *QGuiApplicationPrivate::app_font = font;
3829 applicationResourceFlags |= ApplicationFontExplicitlySet;
3830
3831 if (emitChange && qGuiApp) {
3832 auto font = *QGuiApplicationPrivate::app_font;
3833 locker.unlock();
3834#if QT_DEPRECATED_SINCE(6, 0)
3835QT_WARNING_PUSH
3836QT_WARNING_DISABLE_DEPRECATED
3837 emit qGuiApp->fontChanged(font);
3838QT_WARNING_POP
3839#else
3840 Q_UNUSED(font);
3841#endif // QT_DEPRECATED_SINCE(6, 0)
3842 QEvent event(QEvent::ApplicationFontChange);
3843 QGuiApplication::sendEvent(qGuiApp, &event);
3844 }
3845}
3846
3847/*!
3848 \fn bool QGuiApplication::isRightToLeft()
3849
3850 Returns \c true if the application's layout direction is
3851 Qt::RightToLeft; otherwise returns \c false.
3852
3853 \sa layoutDirection(), isLeftToRight()
3854*/
3855
3856/*!
3857 \fn bool QGuiApplication::isLeftToRight()
3858
3859 Returns \c true if the application's layout direction is
3860 Qt::LeftToRight; otherwise returns \c false.
3861
3862 \sa layoutDirection(), isRightToLeft()
3863*/
3864
3865void QGuiApplicationPrivate::notifyLayoutDirectionChange()
3866{
3867 const QWindowList list = QGuiApplication::topLevelWindows();
3868 for (int i = 0; i < list.size(); ++i) {
3869 QEvent ev(QEvent::ApplicationLayoutDirectionChange);
3870 QCoreApplication::sendEvent(list.at(i), &ev);
3871 }
3872}
3873
3874void QGuiApplicationPrivate::notifyActiveWindowChange(QWindow *prev)
3875{
3876 if (prev) {
3877 QEvent de(QEvent::WindowDeactivate);
3878 QCoreApplication::sendEvent(prev, &de);
3879 }
3880 if (QGuiApplicationPrivate::instance()->focus_window) {
3881 QEvent ae(QEvent::WindowActivate);
3882 QCoreApplication::sendEvent(focus_window, &ae);
3883 }
3884}
3885
3886/*!
3887 \property QGuiApplication::windowIcon
3888 \brief the default window icon
3889
3890 \sa QWindow::setIcon(), {Setting the Application Icon}
3891*/
3892QIcon QGuiApplication::windowIcon()
3893{
3894 return QGuiApplicationPrivate::app_icon ? *QGuiApplicationPrivate::app_icon : QIcon();
3895}
3896
3897void QGuiApplication::setWindowIcon(const QIcon &icon)
3898{
3899 if (!QGuiApplicationPrivate::app_icon)
3900 QGuiApplicationPrivate::app_icon = new QIcon();
3901 *QGuiApplicationPrivate::app_icon = icon;
3902 if (QGuiApplicationPrivate::platform_integration
3903 && QGuiApplicationPrivate::platform_integration->hasCapability(QPlatformIntegration::ApplicationIcon))
3904 QGuiApplicationPrivate::platform_integration->setApplicationIcon(icon);
3905 if (QGuiApplicationPrivate::is_app_running && !QGuiApplicationPrivate::is_app_closing)
3906 QGuiApplicationPrivate::instance()->notifyWindowIconChanged();
3907}
3908
3909void QGuiApplicationPrivate::notifyWindowIconChanged()
3910{
3911 QEvent ev(QEvent::ApplicationWindowIconChange);
3912 const QWindowList list = QGuiApplication::topLevelWindows();
3913 for (int i = 0; i < list.size(); ++i)
3914 QCoreApplication::sendEvent(list.at(i), &ev);
3915}
3916
3917
3918
3919/*!
3920 \property QGuiApplication::quitOnLastWindowClosed
3921
3922 \brief whether the application implicitly quits when the last window is
3923 closed.
3924
3925 The default is \c true.
3926
3927 If this property is \c true, the application will attempt to
3928 quit when the last visible \l{Primary and Secondary Windows}{primary window}
3929 (i.e. top level window with no transient parent) is closed.
3930
3931 Note that attempting a quit may not necessarily result in the
3932 application quitting, for example if there still are active
3933 QEventLoopLocker instances, or the QEvent::Quit event is ignored.
3934
3935 \sa quit(), QWindow::close()
3936 */
3937
3938void QGuiApplication::setQuitOnLastWindowClosed(bool quit)
3939{
3940 QGuiApplicationPrivate::quitOnLastWindowClosed = quit;
3941}
3942
3943bool QGuiApplication::quitOnLastWindowClosed()
3944{
3945 return QGuiApplicationPrivate::quitOnLastWindowClosed;
3946}
3947
3948void QGuiApplicationPrivate::maybeLastWindowClosed()
3949{
3950 if (!lastWindowClosed())
3951 return;
3952
3953 if (in_exec)
3954 emit q_func()->lastWindowClosed();
3955
3956 if (quitOnLastWindowClosed && canQuitAutomatically())
3957 quitAutomatically();
3958}
3959
3960/*!
3961 \fn void QGuiApplication::lastWindowClosed()
3962
3963 This signal is emitted from exec() when the last visible
3964 \l{Primary and Secondary Windows}{primary window} (i.e.
3965 top level window with no transient parent) is closed.
3966
3967 By default, QGuiApplication quits after this signal is emitted. This feature
3968 can be turned off by setting \l quitOnLastWindowClosed to \c false.
3969
3970 \sa QWindow::close(), QWindow::isTopLevel(), QWindow::transientParent()
3971*/
3972
3973bool QGuiApplicationPrivate::lastWindowClosed() const
3974{
3975 for (auto *window : QGuiApplication::topLevelWindows()) {
3976 auto *windowPrivate = qt_window_private(window);
3977 if (!windowPrivate->participatesInLastWindowClosed())
3978 continue;
3979
3980 if (windowPrivate->treatAsVisible())
3981 return false;
3982 }
3983
3984 return true;
3985}
3986
3987bool QGuiApplicationPrivate::canQuitAutomatically()
3988{
3989 // The automatic quit functionality is triggered by
3990 // both QEventLoopLocker and maybeLastWindowClosed.
3991 // Although the former is a QCoreApplication feature
3992 // we don't want to quit the application when there
3993 // are open windows, regardless of whether the app
3994 // also quits automatically on maybeLastWindowClosed.
3995 if (!lastWindowClosed())
3996 return false;
3997
3998 return QCoreApplicationPrivate::canQuitAutomatically();
3999}
4000
4001void QGuiApplicationPrivate::quit()
4002{
4003 if (auto *platformIntegration = QGuiApplicationPrivate::platformIntegration())
4004 platformIntegration->quit();
4005 else
4006 QCoreApplicationPrivate::quit();
4007}
4008
4009bool QGuiApplicationPrivate::handleQuitEvent()
4010{
4011 // Close open windows. This is done in order to deliver de-expose
4012 // events while the event loop is still running.
4013 for (QWindow *topLevelWindow : QGuiApplication::topLevelWindows()) {
4014 // Already closed windows will not have a platform window, skip those
4015 if (!topLevelWindow->handle())
4016 continue;
4017 if (!topLevelWindow->close())
4018 return false;
4019 }
4020
4021 return QCoreApplicationPrivate::handleQuitEvent();
4022}
4023
4024void QGuiApplicationPrivate::processApplicationTermination(QWindowSystemInterfacePrivate::WindowSystemEvent *windowSystemEvent)
4025{
4026 QEvent event(QEvent::Quit);
4027 QGuiApplication::sendSpontaneousEvent(QGuiApplication::instance(), &event);
4028 windowSystemEvent->eventAccepted = event.isAccepted();
4029}
4030
4031/*!
4032 \since 5.2
4033 \fn Qt::ApplicationState QGuiApplication::applicationState()
4034
4035
4036 Returns the current state of the application.
4037
4038 You can react to application state changes to perform actions such as
4039 stopping/resuming CPU-intensive tasks, freeing/loading resources or
4040 saving/restoring application data.
4041 */
4042
4043Qt::ApplicationState QGuiApplication::applicationState()
4044{
4045 return QGuiApplicationPrivate::applicationState;
4046}
4047
4048/*!
4049 \since 5.14
4050
4051 Sets the high-DPI scale factor rounding policy for the application. The
4052 \a policy decides how non-integer scale factors (such as Windows 150%) are
4053 handled.
4054
4055 The two principal options are whether fractional scale factors should
4056 be rounded to an integer or not. Keeping the scale factor as-is will
4057 make the user interface size match the OS setting exactly, but may cause
4058 painting errors, for example with the Windows style.
4059
4060 If rounding is wanted, then which type of rounding should be decided
4061 next. Mathematically correct rounding is supported but may not give
4062 the best visual results: Consider if you want to render 1.5x as 1x
4063 ("small UI") or as 2x ("large UI"). See the Qt::HighDpiScaleFactorRoundingPolicy
4064 enum for a complete list of all options.
4065
4066 This function must be called before creating the application object.
4067 The QGuiApplication::highDpiScaleFactorRoundingPolicy()
4068 accessor will reflect the environment, if set.
4069
4070 The default value is Qt::HighDpiScaleFactorRoundingPolicy::PassThrough.
4071*/
4072void QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy policy)
4073{
4074 if (qApp)
4075 qWarning("setHighDpiScaleFactorRoundingPolicy must be called before creating the QGuiApplication instance");
4076 QGuiApplicationPrivate::highDpiScaleFactorRoundingPolicy = policy;
4077}
4078
4079/*!
4080 \since 5.14
4081
4082 Returns the high-DPI scale factor rounding policy.
4083*/
4084Qt::HighDpiScaleFactorRoundingPolicy QGuiApplication::highDpiScaleFactorRoundingPolicy()
4085{
4086 return QGuiApplicationPrivate::highDpiScaleFactorRoundingPolicy;
4087}
4088
4089/*!
4090 \since 5.2
4091 \fn void QGuiApplication::applicationStateChanged(Qt::ApplicationState state)
4092
4093 This signal is emitted when the \a state of the application changes.
4094
4095 \sa applicationState()
4096*/
4097
4098void QGuiApplicationPrivate::setApplicationState(Qt::ApplicationState state, bool forcePropagate)
4099{
4100 if ((applicationState == state) && !forcePropagate)
4101 return;
4102
4103 applicationState = state;
4104
4105 switch (state) {
4106 case Qt::ApplicationActive: {
4107 QEvent appActivate(QEvent::ApplicationActivate);
4108 QCoreApplication::sendSpontaneousEvent(qApp, &appActivate);
4109 break; }
4110 case Qt::ApplicationInactive: {
4111 QEvent appDeactivate(QEvent::ApplicationDeactivate);
4112 QCoreApplication::sendSpontaneousEvent(qApp, &appDeactivate);
4113 break; }
4114 default:
4115 break;
4116 }
4117
4118 QApplicationStateChangeEvent event(applicationState);
4119 QCoreApplication::sendSpontaneousEvent(qApp, &event);
4120
4121 emit qApp->applicationStateChanged(applicationState);
4122}
4123
4124/*!
4125 \since 4.2
4126 \fn void QGuiApplication::commitDataRequest(QSessionManager &manager)
4127
4128 This signal deals with \l{Session Management}{session management}. It is
4129 emitted when the QSessionManager wants the application to commit all its
4130 data.
4131
4132 Usually this means saving all open files, after getting permission from
4133 the user. Furthermore you may want to provide a means by which the user
4134 can cancel the shutdown.
4135
4136 You should not exit the application within this signal. Instead,
4137 the session manager may or may not do this afterwards, depending on the
4138 context.
4139
4140 \warning Within this signal, no user interaction is possible, \e
4141 unless you ask the \a manager for explicit permission. See
4142 QSessionManager::allowsInteraction() and
4143 QSessionManager::allowsErrorInteraction() for details and example
4144 usage.
4145
4146 \note You should use Qt::DirectConnection when connecting to this signal.
4147
4148 \sa isSessionRestored(), sessionId(), saveStateRequest(), {Session Management}
4149*/
4150
4151/*!
4152 \since 4.2
4153 \fn void QGuiApplication::saveStateRequest(QSessionManager &manager)
4154
4155 This signal deals with \l{Session Management}{session management}. It is
4156 invoked when the \l{QSessionManager}{session manager} wants the application
4157 to preserve its state for a future session.
4158
4159 For example, a text editor would create a temporary file that includes the
4160 current contents of its edit buffers, the location of the cursor and other
4161 aspects of the current editing session.
4162
4163 You should never exit the application within this signal. Instead, the
4164 session manager may or may not do this afterwards, depending on the
4165 context. Furthermore, most session managers will very likely request a saved
4166 state immediately after the application has been started. This permits the
4167 session manager to learn about the application's restart policy.
4168
4169 \warning Within this signal, no user interaction is possible, \e
4170 unless you ask the \a manager for explicit permission. See
4171 QSessionManager::allowsInteraction() and
4172 QSessionManager::allowsErrorInteraction() for details.
4173
4174 \note You should use Qt::DirectConnection when connecting to this signal.
4175
4176 \sa isSessionRestored(), sessionId(), commitDataRequest(), {Session Management}
4177*/
4178
4179/*!
4180 \fn bool QGuiApplication::isSessionRestored() const
4181
4182 Returns \c true if the application has been restored from an earlier
4183 \l{Session Management}{session}; otherwise returns \c false.
4184
4185 \sa sessionId(), commitDataRequest(), saveStateRequest()
4186*/
4187
4188/*!
4189 \since 5.0
4190 \fn bool QGuiApplication::isSavingSession() const
4191
4192 Returns \c true if the application is currently saving the
4193 \l{Session Management}{session}; otherwise returns \c false.
4194
4195 This is \c true when commitDataRequest() and saveStateRequest() are emitted,
4196 but also when the windows are closed afterwards by session management.
4197
4198 \sa sessionId(), commitDataRequest(), saveStateRequest()
4199*/
4200
4201/*!
4202 \fn QString QGuiApplication::sessionId() const
4203
4204 Returns the current \l{Session Management}{session's} identifier.
4205
4206 If the application has been restored from an earlier session, this
4207 identifier is the same as it was in that previous session. The session
4208 identifier is guaranteed to be unique both for different applications
4209 and for different instances of the same application.
4210
4211 \sa isSessionRestored(), sessionKey(), commitDataRequest(), saveStateRequest()
4212*/
4213
4214/*!
4215 \fn QString QGuiApplication::sessionKey() const
4216
4217 Returns the session key in the current \l{Session Management}{session}.
4218
4219 If the application has been restored from an earlier session, this key is
4220 the same as it was when the previous session ended.
4221
4222 The session key changes every time the session is saved. If the shutdown process
4223 is cancelled, another session key will be used when shutting down again.
4224
4225 \sa isSessionRestored(), sessionId(), commitDataRequest(), saveStateRequest()
4226*/
4227#ifndef QT_NO_SESSIONMANAGER
4228bool QGuiApplication::isSessionRestored() const
4229{
4230 Q_D(const QGuiApplication);
4231 return d->is_session_restored;
4232}
4233
4234QString QGuiApplication::sessionId() const
4235{
4236 Q_D(const QGuiApplication);
4237 return d->session_manager->sessionId();
4238}
4239
4240QString QGuiApplication::sessionKey() const
4241{
4242 Q_D(const QGuiApplication);
4243 return d->session_manager->sessionKey();
4244}
4245
4246bool QGuiApplication::isSavingSession() const
4247{
4248 Q_D(const QGuiApplication);
4249 return d->is_saving_session;
4250}
4251
4252void QGuiApplicationPrivate::commitData()
4253{
4254 Q_Q(QGuiApplication);
4255 is_saving_session = true;
4256 emit q->commitDataRequest(*session_manager);
4257 is_saving_session = false;
4258}
4259
4260
4261void QGuiApplicationPrivate::saveState()
4262{
4263 Q_Q(QGuiApplication);
4264 is_saving_session = true;
4265 emit q->saveStateRequest(*session_manager);
4266 is_saving_session = false;
4267}
4268#endif //QT_NO_SESSIONMANAGER
4269
4270/*!
4271 \since 5.2
4272
4273 Function that can be used to sync Qt state with the Window Systems state.
4274
4275 This function will first empty Qts events by calling QCoreApplication::processEvents(),
4276 then the platform plugin will sync up with the windowsystem, and finally Qts events
4277 will be delived by another call to QCoreApplication::processEvents();
4278
4279 This function is timeconsuming and its use is discouraged.
4280*/
4281void QGuiApplication::sync()
4282{
4283 QCoreApplication::processEvents();
4284 if (QGuiApplicationPrivate::platform_integration
4285 && QGuiApplicationPrivate::platform_integration->hasCapability(QPlatformIntegration::SyncState)) {
4286 QGuiApplicationPrivate::platform_integration->sync();
4287 QCoreApplication::processEvents();
4288 QWindowSystemInterface::flushWindowSystemEvents();
4289 }
4290}
4291
4292/*!
4293 \property QGuiApplication::layoutDirection
4294 \brief the default layout direction for this application
4295
4296 On system start-up, or when the direction is explicitly set to
4297 Qt::LayoutDirectionAuto, the default layout direction depends on the
4298 application's language.
4299
4300 The notifier signal was introduced in Qt 5.4.
4301
4302 \sa QWidget::layoutDirection, isLeftToRight(), isRightToLeft()
4303 */
4304
4305void QGuiApplication::setLayoutDirection(Qt::LayoutDirection direction)
4306{
4307 layout_direction = direction;
4308 if (direction == Qt::LayoutDirectionAuto)
4309 direction = qt_detectRTLLanguage() ? Qt::RightToLeft : Qt::LeftToRight;
4310
4311 // no change to the explicitly set or auto-detected layout direction
4312 if (direction == effective_layout_direction)
4313 return;
4314
4315 effective_layout_direction = direction;
4316 if (qGuiApp) {
4317 emit qGuiApp->layoutDirectionChanged(direction);
4318 QGuiApplicationPrivate::instance()->notifyLayoutDirectionChange();
4319 }
4320}
4321
4322Qt::LayoutDirection QGuiApplication::layoutDirection()
4323{
4324 /*
4325 effective_layout_direction defaults to Qt::LeftToRight, and is updated with what is
4326 auto-detected by a call to setLayoutDirection(Qt::LayoutDirectionAuto). This happens in
4327 QGuiApplicationPrivate::init and when the language changes (or before if the application
4328 calls the static function, but then no translators are installed so the auto-detection
4329 always yields Qt::LeftToRight).
4330 So we can be certain that it's always the right value.
4331 */
4332 return effective_layout_direction;
4333}
4334
4335/*!
4336 \fn QCursor *QGuiApplication::overrideCursor()
4337
4338 Returns the active application override cursor.
4339
4340 This function returns \nullptr if no application cursor has been defined (i.e. the
4341 internal cursor stack is empty).
4342
4343 \sa setOverrideCursor(), restoreOverrideCursor()
4344*/
4345#ifndef QT_NO_CURSOR
4346QCursor *QGuiApplication::overrideCursor()
4347{
4348 CHECK_QAPP_INSTANCE(nullptr)
4349 return qGuiApp->d_func()->cursor_list.isEmpty() ? nullptr : &qGuiApp->d_func()->cursor_list.first();
4350}
4351
4352/*!
4353 Changes the currently active application override cursor to \a cursor.
4354
4355 This function has no effect if setOverrideCursor() was not called.
4356
4357 \sa setOverrideCursor(), overrideCursor(), restoreOverrideCursor(),
4358 QWidget::setCursor()
4359 */
4360void QGuiApplication::changeOverrideCursor(const QCursor &cursor)
4361{
4363 if (qGuiApp->d_func()->cursor_list.isEmpty())
4364 return;
4365 qGuiApp->d_func()->cursor_list.removeFirst();
4366 setOverrideCursor(cursor);
4367}
4368#endif
4369
4370
4371#ifndef QT_NO_CURSOR
4372static inline void applyCursor(QWindow *w, QCursor c)
4373{
4374 if (const QScreen *screen = w->screen())
4375 if (QPlatformCursor *cursor = screen->handle()->cursor())
4376 cursor->changeCursor(&c, w);
4377}
4378
4379static inline void unsetCursor(QWindow *w)
4380{
4381 if (const QScreen *screen = w->screen())
4382 if (QPlatformCursor *cursor = screen->handle()->cursor())
4383 cursor->changeCursor(nullptr, w);
4384}
4385
4386static inline void applyCursor(const QList<QWindow *> &l, const QCursor &c)
4387{
4388 for (int i = 0; i < l.size(); ++i) {
4389 QWindow *w = l.at(i);
4390 if (w->handle())
4391 applyCursor(w, c);
4392 }
4393}
4394
4395static inline void applyOverrideCursor(const QList<QScreen *> &screens, const QCursor &c)
4396{
4397 for (QScreen *screen : screens) {
4398 if (QPlatformCursor *cursor = screen->handle()->cursor())
4399 cursor->setOverrideCursor(c);
4400 }
4401}
4402
4403static inline void clearOverrideCursor(const QList<QScreen *> &screens)
4404{
4405 for (QScreen *screen : screens) {
4406 if (QPlatformCursor *cursor = screen->handle()->cursor())
4407 cursor->clearOverrideCursor();
4408 }
4409}
4410
4411static inline void applyWindowCursor(const QList<QWindow *> &l)
4412{
4413 for (int i = 0; i < l.size(); ++i) {
4414 QWindow *w = l.at(i);
4415 if (w->handle()) {
4416 if (qt_window_private(w)->hasCursor) {
4417 applyCursor(w, w->cursor());
4418 } else {
4419 unsetCursor(w);
4420 }
4421 }
4422 }
4423}
4424
4425/*!
4426 \fn void QGuiApplication::setOverrideCursor(const QCursor &cursor)
4427
4428 Sets the application override cursor to \a cursor.
4429
4430 Application override cursors are intended for showing the user that the
4431 application is in a special state, for example during an operation that
4432 might take some time.
4433
4434 This cursor will be displayed in all the application's widgets until
4435 restoreOverrideCursor() or another setOverrideCursor() is called.
4436
4437 Application cursors are stored on an internal stack. setOverrideCursor()
4438 pushes the cursor onto the stack, and restoreOverrideCursor() pops the
4439 active cursor off the stack. changeOverrideCursor() changes the currently
4440 active application override cursor.
4441
4442 Every setOverrideCursor() must eventually be followed by a corresponding
4443 restoreOverrideCursor(), otherwise the stack will never be emptied.
4444
4445 Example:
4446 \snippet code/src_gui_kernel_qguiapplication_x11.cpp 0
4447
4448 \sa overrideCursor(), restoreOverrideCursor(), changeOverrideCursor(),
4449 QWidget::setCursor()
4450*/
4451void QGuiApplication::setOverrideCursor(const QCursor &cursor)
4452{
4454 qGuiApp->d_func()->cursor_list.prepend(cursor);
4455 if (QPlatformCursor::capabilities().testFlag(QPlatformCursor::OverrideCursor))
4456 applyOverrideCursor(QGuiApplicationPrivate::screen_list, cursor);
4457 else
4458 applyCursor(QGuiApplicationPrivate::window_list, cursor);
4459}
4460
4461/*!
4462 \fn void QGuiApplication::restoreOverrideCursor()
4463
4464 Undoes the last setOverrideCursor().
4465
4466 If setOverrideCursor() has been called twice, calling
4467 restoreOverrideCursor() will activate the first cursor set. Calling this
4468 function a second time restores the original widgets' cursors.
4469
4470 \sa setOverrideCursor(), overrideCursor()
4471*/
4472void QGuiApplication::restoreOverrideCursor()
4473{
4475 if (qGuiApp->d_func()->cursor_list.isEmpty())
4476 return;
4477 qGuiApp->d_func()->cursor_list.removeFirst();
4478 if (qGuiApp->d_func()->cursor_list.size() > 0) {
4479 QCursor c(qGuiApp->d_func()->cursor_list.value(0));
4480 if (QPlatformCursor::capabilities().testFlag(QPlatformCursor::OverrideCursor))
4481 applyOverrideCursor(QGuiApplicationPrivate::screen_list, c);
4482 else
4483 applyCursor(QGuiApplicationPrivate::window_list, c);
4484 } else {
4485 if (QPlatformCursor::capabilities().testFlag(QPlatformCursor::OverrideCursor))
4486 clearOverrideCursor(QGuiApplicationPrivate::screen_list);
4487 applyWindowCursor(QGuiApplicationPrivate::window_list);
4488 }
4489}
4490#endif// QT_NO_CURSOR
4491
4492/*!
4493 Returns the application's style hints.
4494
4495 The style hints encapsulate a set of platform dependent properties
4496 such as double click intervals, full width selection and others.
4497
4498 The hints can be used to integrate tighter with the underlying platform.
4499
4500 \sa QStyleHints
4501 */
4502QStyleHints *QGuiApplication::styleHints()
4503{
4504 if (!QGuiApplicationPrivate::styleHints)
4505 QGuiApplicationPrivate::styleHints = new QStyleHints();
4506 return QGuiApplicationPrivate::styleHints;
4507}
4508
4509/*!
4510 Sets whether Qt should use the system's standard colors, fonts, etc., to
4511 \a on. By default, this is \c true.
4512
4513 This function must be called before creating the QGuiApplication object, like
4514 this:
4515
4516 \snippet code/src_gui_kernel_qguiapplication.cpp 0
4517
4518 \sa desktopSettingsAware()
4519*/
4520void QGuiApplication::setDesktopSettingsAware(bool on)
4521{
4522 QGuiApplicationPrivate::obey_desktop_settings = on;
4523}
4524
4525/*!
4526 Returns \c true if Qt is set to use the system's standard colors, fonts, etc.;
4527 otherwise returns \c false. The default is \c true.
4528
4529 \sa setDesktopSettingsAware()
4530*/
4531bool QGuiApplication::desktopSettingsAware()
4532{
4533 return QGuiApplicationPrivate::obey_desktop_settings;
4534}
4535
4536/*!
4537 returns the input method.
4538
4539 The input method returns properties about the state and position of
4540 the virtual keyboard. It also provides information about the position of the
4541 current focused input element.
4542
4543 \sa QInputMethod
4544 */
4545QInputMethod *QGuiApplication::inputMethod()
4546{
4547 CHECK_QAPP_INSTANCE(nullptr)
4548 if (!qGuiApp->d_func()->inputMethod)
4549 qGuiApp->d_func()->inputMethod = new QInputMethod();
4550 return qGuiApp->d_func()->inputMethod;
4551}
4552
4553/*!
4554 \fn void QGuiApplication::fontDatabaseChanged()
4555
4556 This signal is emitted when the available fonts have changed.
4557
4558 This can happen when application fonts are added or removed, or when the
4559 system fonts change.
4560
4561 \sa QFontDatabase::addApplicationFont(),
4562 QFontDatabase::addApplicationFontFromData(),
4563 QFontDatabase::removeAllApplicationFonts(),
4564 QFontDatabase::removeApplicationFont()
4565*/
4566
4567QPixmap QGuiApplicationPrivate::getPixmapCursor(Qt::CursorShape cshape)
4568{
4569 Q_UNUSED(cshape);
4570 return QPixmap();
4571}
4572
4573QPoint QGuiApplicationPrivate::QLastCursorPosition::toPoint() const noexcept
4574{
4575 // Guard against the default initialization of qInf() (avoid UB or SIGFPE in conversion).
4576 if (Q_UNLIKELY(qIsInf(thePoint.x())))
4577 return QPoint(std::numeric_limits<int>::max(), std::numeric_limits<int>::max());
4578 return thePoint.toPoint();
4579}
4580
4581#if QT_CONFIG(draganddrop)
4582void QGuiApplicationPrivate::notifyDragStarted(const QDrag *drag)
4583{
4584 Q_UNUSED(drag);
4585
4586}
4587#endif
4588
4589const QColorTrcLut *QGuiApplicationPrivate::colorProfileForA8Text()
4590{
4591#ifdef Q_OS_WIN
4592 if (!m_a8ColorProfile)
4593 m_a8ColorProfile = QColorTrcLut::fromGamma(2.31f); // This is a hard-coded thing for Windows text rendering
4594 return m_a8ColorProfile.get();
4595#else
4596 return colorProfileForA32Text();
4597#endif
4598}
4599
4600const QColorTrcLut *QGuiApplicationPrivate::colorProfileForA32Text()
4601{
4602 if (!m_a32ColorProfile)
4603 m_a32ColorProfile = QColorTrcLut::fromGamma(float(fontSmoothingGamma));
4604 return m_a32ColorProfile.get();
4605}
4606
4607void QGuiApplicationPrivate::_q_updateFocusObject(QObject *object)
4608{
4609 Q_Q(QGuiApplication);
4610
4611 QPlatformInputContext *inputContext = platformIntegration()->inputContext();
4612 const bool enabled = inputContext && QInputMethodPrivate::objectAcceptsInputMethod(object);
4613
4614 QPlatformInputContextPrivate::setInputMethodAccepted(enabled);
4615 if (inputContext)
4616 inputContext->setFocusObject(object);
4617 emit q->focusObjectChanged(object);
4618}
4619
4620enum MouseMasks {
4621 MouseCapsMask = 0xFF,
4622 MouseSourceMaskDst = 0xFF00,
4623 MouseSourceMaskSrc = MouseCapsMask,
4624 MouseSourceShift = 8,
4625 MouseFlagsCapsMask = 0xFF0000,
4626 MouseFlagsShift = 16
4627};
4628
4629QInputDeviceManager *QGuiApplicationPrivate::inputDeviceManager()
4630{
4631 Q_ASSERT(QGuiApplication::instance());
4632
4633 if (!m_inputDeviceManager)
4634 m_inputDeviceManager = new QInputDeviceManager(QGuiApplication::instance());
4635
4636 return m_inputDeviceManager;
4637}
4638
4639/*!
4640 Returns the QThreadPool instance for Qt Gui.
4641 \internal
4642*/
4643QThreadPool *QGuiApplicationPrivate::qtGuiThreadPool()
4644{
4645#if QT_CONFIG(qtgui_threadpool)
4646 Q_CONSTINIT static QPointer<QThreadPool> guiInstance;
4647 Q_CONSTINIT static QBasicMutex theMutex;
4648 const static bool runtime_disable = qEnvironmentVariableIsSet("QT_NO_GUI_THREADPOOL");
4649 if (runtime_disable)
4650 return nullptr;
4651 const QMutexLocker locker(&theMutex);
4652 if (guiInstance.isNull() && !QCoreApplication::closingDown()) {
4653 guiInstance = new QThreadPool();
4654 // Limit max thread to avoid too many parallel threads.
4655 // We are not optimized for much more than 4 or 8 threads.
4656 if (guiInstance && guiInstance->maxThreadCount() > 4)
4657 guiInstance->setMaxThreadCount(qBound(4, guiInstance->maxThreadCount() / 2, 8));
4658 }
4659 return guiInstance;
4660#else
4661 return nullptr;
4662#endif
4663}
4664
4665/*!
4666 \fn template <typename QNativeInterface> QNativeInterface *QGuiApplication::nativeInterface() const
4667
4668 Returns a native interface of the given type for the application.
4669
4670 This function provides access to platform specific functionality
4671 of QGuiApplication, as defined in the QNativeInterface namespace:
4672
4673 \annotatedlist native-interfaces-qguiapplication
4674
4675 If the requested interface is not available a \nullptr is returned.
4676 */
4677
4678void *QGuiApplication::resolveInterface(const char *name, int revision) const
4679{
4680 using namespace QNativeInterface;
4681 using namespace QNativeInterface::Private;
4682
4683 auto *platformIntegration = QGuiApplicationPrivate::platformIntegration();
4684 Q_UNUSED(platformIntegration);
4685
4686#if defined(Q_OS_WIN)
4687 QT_NATIVE_INTERFACE_RETURN_IF(QWindowsApplication, platformIntegration);
4688#endif
4689#if QT_CONFIG(xcb)
4690 QT_NATIVE_INTERFACE_RETURN_IF(QX11Application, platformNativeInterface());
4691#endif
4692#if QT_CONFIG(wayland)
4693 QT_NATIVE_INTERFACE_RETURN_IF(QWaylandApplication, platformNativeInterface());
4694#endif
4695#if defined(Q_OS_VISIONOS)
4696 QT_NATIVE_INTERFACE_RETURN_IF(QVisionOSApplication, platformIntegration);
4697#endif
4698
4699 return QCoreApplication::resolveInterface(name, revision);
4700}
4701
4702QT_END_NAMESPACE
4703
4704#include "moc_qguiapplication.cpp"
The QClipboard class provides access to the window system clipboard.
Definition qclipboard.h:21
\reentrant
Definition qfont.h:23
The QIcon class provides scalable icons in different modes and states.
Definition qicon.h:21
QInputDeviceManager acts as a communication hub between QtGui and the input handlers.
The QPalette class contains color groups for each widget state.
Definition qpalette.h:20
The QPlatformIntegration class is the entry for WindowSystem specific functionality.
The QPlatformTheme class allows customizing the UI based on themes.
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:177
The QStyleHints class contains platform specific hints and settings. \inmodule QtGui.
Definition qstylehints.h:20
\inmodule QtGui
Definition qwindow.h:64
#define qApp
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
static bool needsWindowBlockedEvent(const QWindow *w)
Q_CORE_EXPORT void qt_call_post_routines()
static void init_plugins(const QList< QByteArray > &pluginList)
static void initFontUnlocked()
static void clearFontUnlocked()
void qRegisterGuiVariant()
static Q_CONSTINIT unsigned applicationResourceFlags
static Q_CONSTINIT int touchDoubleTapDistance
static QWindowGeometrySpecification windowGeometrySpecification
static bool qt_detectRTLLanguage()
Q_CONSTINIT Q_GUI_EXPORT bool qt_is_tty_app
static Q_CONSTINIT bool force_reverse
static Q_CONSTINIT int mouseDoubleClickDistance
#define Q_WINDOW_GEOMETRY_SPECIFICATION_INITIALIZER
static void init_platform(const QString &pluginNamesWithArguments, const QString &platformPluginPath, const QString &platformThemeName, int &argc, char **argv)
static void initThemeHints()
static int nextGeometryToken(const QByteArray &a, int &pos, char *op)
#define CHECK_QAPP_INSTANCE(...)
ApplicationResourceFlags
@ ApplicationFontExplicitlySet
static void updateBlockedStatusRecursion(QWindow *window, bool shouldBeBlocked)
#define qGuiApp
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
QDebug Q_GUI_EXPORT & operator<<(QDebug &s, const QVectorPath &path)
void applyTo(QWindow *window) const
static QWindowGeometrySpecification fromArgument(const QByteArray &a)