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
qcoreapplication.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2021 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
8
9#ifndef QT_NO_QOBJECT
11#include "qcoreevent.h"
12#include "qcoreevent_p.h"
13#include "qeventloop.h"
14#endif
15#include "qmetaobject.h"
16#include <private/qproperty_p.h>
17#include <qdatastream.h>
18#include <qdebug.h>
19#include <qdir.h>
20#include <qfile.h>
21#include <qfileinfo.h>
22#include <private/qfilesystementry_p.h>
23#include <qmutex.h>
24#include <private/qloggingregistry_p.h>
25#include <qscopeguard.h>
26#include <qscopedvaluerollback.h>
27#include <qspan.h>
28#include <qstandardpaths.h>
29#ifndef QT_NO_QOBJECT
30#include <qthread.h>
31#include <qthreadstorage.h>
32#if QT_CONFIG(future)
33#include <QtCore/qpromise.h>
34#endif
35#include <private/qthread_p.h>
36#if QT_CONFIG(thread)
37#include <qthreadpool.h>
38#include <private/qthreadpool_p.h>
39#endif
40#endif
41#include <qlibraryinfo.h>
42#include <qpointer.h>
43#include <qvarlengtharray.h>
44#include <private/qfactoryloader_p.h>
45#include <private/qfunctions_p.h>
46#include <private/qlocale_p.h>
47#include <private/qlocking_p.h>
48#include <private/qhooks_p.h>
49#include <private/qnativeinterface_p.h>
50
51#ifdef Q_OS_WASM
52#include <private/qstdweb_p.h>
53#endif
54
55#if QT_CONFIG(permissions)
56#include <private/qpermissions_p.h>
57#endif
58
59#ifndef QT_NO_QOBJECT
60#if defined(Q_OS_UNIX)
61# if defined(Q_OS_DARWIN)
62# include "qeventdispatcher_cf_p.h"
63# else
64# if !defined(QT_NO_GLIB)
65# include "qeventdispatcher_glib_p.h"
66# endif
67# endif
68# if !defined(Q_OS_WASM)
69# include "qeventdispatcher_unix_p.h"
70# endif
71#endif
72#ifdef Q_OS_WIN
73#include "qeventdispatcher_win_p.h"
74#endif
75#endif // QT_NO_QOBJECT
76
77#if defined(Q_OS_ANDROID)
78#include <QtCore/qjniobject.h>
79#endif
80
81#if defined(Q_OS_HARMONY) && !defined(QT_BOOTSTRAPPED)
82#include <QtCore/private/qcore_ohos_p.h>
83#include <QtCore/private/qnapi_p.h>
84#include <QtCore/private/qohosmemoizingjsthreadfetcher_p.h>
85#endif
86
87#ifdef Q_OS_DARWIN
88# include "qcore_mac_p.h"
89#endif
90
91#include <stdlib.h>
92
93#ifdef Q_OS_UNIX
94# include <locale.h>
95# ifndef Q_OS_INTEGRITY
96# include <langinfo.h>
97# endif
98# include <unistd.h>
99# include <sys/types.h>
100
101# include "qcore_unix_p.h"
102#endif
103
104#if __has_include(<sys/auxv.h>) // Linux and FreeBSD
105# include <sys/auxv.h>
106#endif
107
108#ifdef Q_OS_VXWORKS
109# include <taskLib.h>
110#endif
111
112#ifdef Q_OS_WASM
113#include <emscripten/val.h>
114#endif
115
116#ifdef QT_BOOTSTRAPPED
117#include <private/qtrace_p.h>
118#else
119#include <qtcore_tracepoints_p.h>
120#endif
121
122#include <algorithm>
123#include <memory>
124#include <string>
125
126#ifdef Q_OS_WIN
127# include <qt_windows.h>
128#endif
129
130QT_BEGIN_NAMESPACE
131
132using namespace Qt::StringLiterals;
133
135 "#include <qcoreevent.h>"
136);
137Q_TRACE_METADATA(qtcore, "ENUM { AUTO, RANGE User ... MaxUser } QEvent::Type;");
138Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_entry, QObject *receiver, QEvent *event, QEvent::Type type);
141Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_event_posted, QObject *receiver, QEvent *event, QEvent::Type type);
142Q_TRACE_POINT(qtcore, QCoreApplication_sendEvent, QObject *receiver, QEvent *event, QEvent::Type type);
143Q_TRACE_POINT(qtcore, QCoreApplication_sendSpontaneousEvent, QObject *receiver, QEvent *event, QEvent::Type type);
144Q_TRACE_POINT(qtcore, QCoreApplication_notify_entry, QObject *receiver, QEvent *event, QEvent::Type type);
145Q_TRACE_POINT(qtcore, QCoreApplication_notify_exit, bool consumed, bool filtered);
146
147#if (defined(Q_OS_WIN) || defined(Q_OS_DARWIN)) && !defined(QT_BOOTSTRAPPED)
148extern QString qAppFileName();
149#endif
150
151Q_CONSTINIT bool QCoreApplicationPrivate::setuidAllowed = false;
152
153#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0)
154# warning "Audit remaining direct usages of this variable for memory ordering semantics"
155Q_CONSTINIT QBasicAtomicPointer<QCoreApplication> QCoreApplication::self = nullptr;
156#else
157Q_CONSTINIT QCoreApplication *QCoreApplication::self = nullptr;
158Q_CONSTINIT static QBasicAtomicPointer<QCoreApplication> g_self = nullptr;
159# undef qApp
160# define qApp g_self.loadRelaxed()
161
162/*!
163 \internal
164
165 This function is a Qt 6 thread-safe (no data races) version of:
166 \code
167 QCoreApplication::instance() != nullptr
168 \endcode
169
170 We may remove it in Qt 7.0 because the above will be thread-safe.
171*/
172bool QCoreApplication::instanceExists() noexcept
173{
174 return qApp != nullptr;
175}
176#endif
177
178#if !defined(Q_OS_WIN) || defined(QT_BOOTSTRAPPED)
179#ifdef Q_OS_DARWIN
180QString QCoreApplicationPrivate::infoDictionaryStringProperty(const QString &propertyName)
181{
182 QString bundleName;
183 QCFString cfPropertyName = propertyName.toCFString();
184 CFTypeRef string = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(),
185 cfPropertyName);
186 if (string)
187 bundleName = QString::fromCFString(static_cast<CFStringRef>(string));
188 return bundleName;
189}
190#endif
191QString QCoreApplicationPrivate::appName() const
192{
193 QString applicationName;
194#ifdef Q_OS_DARWIN
195 applicationName = infoDictionaryStringProperty(QStringLiteral("CFBundleName"));
196#endif
197 if (applicationName.isEmpty() && argv[0]) {
198 char *p = strrchr(argv[0], '/');
199 applicationName = QString::fromLocal8Bit(p ? p + 1 : argv[0]);
200 }
201
202 return applicationName;
203}
204
205#if defined(Q_OS_HARMONY) && !defined(QT_BOOTSTRAPPED)
206static QOhosMemoizingJsThreadFetcher<QString> bundleVersionNameFetcher(
207 [](QOhosJsState &jsState) -> std::optional<QString> {
208 const auto flag = jsState.eval<QNapi::Number>(
209 "@ohos.bundle.bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION");
210 return QString::fromStdString(
211 jsState.eval<QNapi::String>(
212 "@ohos.bundle.bundleManager.getBundleInfoForSelfSync(*).versionName",
213 {flag}));
214 },
215 "BundleInfo.versionName");
216#endif
217
218QString QCoreApplicationPrivate::appVersion() const
219{
220 QString applicationVersion;
221#if defined(Q_OS_DARWIN)
222 applicationVersion = infoDictionaryStringProperty(QStringLiteral("CFBundleVersion"));
223#elif defined(Q_OS_ANDROID) && !defined(QT_BOOTSTRAPPED)
224 QJniObject context(QNativeInterface::QAndroidApplication::context());
225 if (context.isValid()) {
226 QJniObject pm = context.callObjectMethod(
227 "getPackageManager", "()Landroid/content/pm/PackageManager;");
228 QJniObject pn = context.callObjectMethod<jstring>("getPackageName");
229 if (pm.isValid() && pn.isValid()) {
230 QJniObject packageInfo = pm.callObjectMethod(
231 "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;",
232 pn.object(), 0);
233 if (packageInfo.isValid()) {
234 QJniObject versionName = packageInfo.getObjectField(
235 "versionName", "Ljava/lang/String;");
236 if (versionName.isValid())
237 return versionName.toString();
238 }
239 }
240 }
241#elif defined(Q_OS_HARMONY) && !defined(QT_BOOTSTRAPPED)
242 applicationVersion = bundleVersionNameFetcher.optValue().value_or(QString());
243#endif
244 return applicationVersion;
245}
246#endif // !Q_OS_WIN || QT_BOOTSTRAPPED
247
248bool QCoreApplicationPrivate::checkInstance(const char *function)
249{
250 bool b = (qApp != nullptr);
251 if (!b)
252 qWarning("QApplication::%s: Please instantiate the QApplication object first", function);
253 return b;
254}
255
256#if QT_CONFIG(commandlineparser)
257void QCoreApplicationPrivate::addQtOptions(QList<QCommandLineOption> *options)
258{
259 options->append(QCommandLineOption(QStringLiteral("qmljsdebugger"),
260 QStringLiteral("Activates the QML/JS debugger with a specified port. The value must be of format port:1234[,block]. \"block\" makes the application wait for a connection."),
261 QStringLiteral("value")));
262}
263#endif
264
265void QCoreApplicationPrivate::processCommandLineArguments()
266{
267 int j = argc ? 1 : 0;
268 for (int i = 1; i < argc; ++i) {
269 if (!argv[i])
270 continue;
271 if (*argv[i] != '-') {
272 argv[j++] = argv[i];
273 continue;
274 }
275 const char *arg = argv[i];
276 if (arg[1] == '-') // startsWith("--")
277 ++arg;
278 if (strncmp(arg, "-qmljsdebugger=", 15) == 0) {
279 qmljs_debug_arguments = QString::fromLocal8Bit(arg + 15);
280 } else if (strcmp(arg, "-qmljsdebugger") == 0 && i < argc - 1) {
281 ++i;
282 qmljs_debug_arguments = QString::fromLocal8Bit(argv[i]);
283 } else {
284 argv[j++] = argv[i];
285 }
286 }
287
288 if (j < argc) {
289 argv[j] = nullptr;
290 argc = j;
291 }
292}
293
294// Support for introspection
295
296extern "C" void
297#ifdef QT_SHARED
299#endif
303
307Q_GLOBAL_STATIC(QVFuncList, postRList)
308Q_CONSTINIT static QBasicMutex globalRoutinesMutex;
309Q_CONSTINIT static bool preRoutinesCalled = false;
310
311/*!
312 \internal
313
314 Adds a global routine that will be called from the QCoreApplication
315 constructor. The public API is Q_COREAPP_STARTUP_FUNCTION.
316*/
318{
319 QStartUpFuncList *list = preRList();
320 if (!list)
321 return;
322
323 if (preRoutinesCalled) {
324 Q_ASSERT(qApp);
325 p();
326 }
327
328 // Due to C++11 parallel dynamic initialization, this can be called
329 // from multiple threads.
330 const auto locker = qt_scoped_lock(globalRoutinesMutex);
331 list->prepend(p); // in case QCoreApplication is re-created, see qt_call_pre_routines
332}
333
335{
336 QVFuncList *list = postRList();
337 if (!list)
338 return;
339 const auto locker = qt_scoped_lock(globalRoutinesMutex);
340 list->prepend(p);
341}
342
344{
345 QVFuncList *list = postRList();
346 if (!list)
347 return;
348 const auto locker = qt_scoped_lock(globalRoutinesMutex);
349 list->removeAll(p);
350}
351
353{
354 // After will be allowed invoke QtStartUpFunction when calling qAddPreRoutine
355 preRoutinesCalled = true;
356
357 if (!preRList.exists())
358 return;
359
360 const QStartUpFuncList list = [] {
361 const auto locker = qt_scoped_lock(globalRoutinesMutex);
362 // Unlike qt_call_post_routines, we don't empty the list, because
363 // Q_COREAPP_STARTUP_FUNCTION is a macro, so the user expects
364 // the function to be executed every time QCoreApplication is created.
365 return *preRList;
366 }();
367
368 for (QtStartUpFunction f : list)
369 f();
370}
371
372void Q_CORE_EXPORT qt_call_post_routines()
373{
374 if (!postRList.exists())
375 return;
376
377 forever {
378 QVFuncList list;
379 {
380 // extract the current list and make the stored list empty
381 const auto locker = qt_scoped_lock(globalRoutinesMutex);
382 qSwap(*postRList, list);
383 }
384
385 if (list.isEmpty())
386 break;
387 for (QtCleanUpFunction f : std::as_const(list))
388 f();
389 }
390}
391
392
393#ifndef QT_NO_QOBJECT
394
395// app starting up if false
396Q_CONSTINIT bool QCoreApplicationPrivate::is_app_running = false;
397 // app closing down if true
398Q_CONSTINIT bool QCoreApplicationPrivate::is_app_closing = false;
399
401{
402 const QPostEventList &l = QThreadData::current()->postEventList;
403 return l.size() - l.startOffset;
404}
405
406Q_CONSTINIT QAbstractEventDispatcher *QCoreApplicationPrivate::eventDispatcher = nullptr;
407
408#endif // QT_NO_QOBJECT
409
410Q_CONSTINIT uint QCoreApplicationPrivate::attribs =
411 (1 << Qt::AA_SynthesizeMouseForUnhandledTouchEvents) |
412 (1 << Qt::AA_SynthesizeMouseForUnhandledTabletEvents);
413
415{
417 applicationNameSet = false;
418 applicationVersionSet = false;
419 }
420
422 QString application; // application name, initially from argv[0], can then be modified.
424 bool applicationNameSet; // true if setApplicationName was called
425 bool applicationVersionSet; // true if setApplicationVersion was called
426
427#if QT_CONFIG(library)
428 // QList does not have isNull()
429 bool libPathsInitialized() const noexcept
430 { return !app_libpaths.data_ptr().isNull(); }
431 bool libPathsManuallySet() const noexcept
432 { return !manual_libpaths.data_ptr().isNull(); }
435 QRecursiveMutex libraryPathMutex; // protects this block
436#endif
437
438};
439
440Q_GLOBAL_STATIC(QCoreApplicationData, coreappdata)
441
442#ifndef QT_NO_QOBJECT
443Q_CONSTINIT static bool quitLockEnabled = true;
444#endif
445
446#if defined(Q_OS_WIN)
447// Check whether the command line arguments passed to QCoreApplication
448// match those passed into main(), to see if the user has modified them
449// before passing them on to us. We do this by comparing to the global
450// __argv/__argc (MS extension). Deep comparison is required since
451// argv/argc is rebuilt by our WinMain entrypoint.
452static inline bool isArgvModified(int argc, char **argv)
453{
454 if (__argc != argc || !__argv /* wmain() */)
455 return true;
456 if (__argv == argv)
457 return false;
458 for (int a = 0; a < argc; ++a) {
459 if (argv[a] != __argv[a] && strcmp(argv[a], __argv[a]))
460 return true;
461 }
462 return false;
463}
464
465static inline bool contains(int argc, char **argv, const char *needle)
466{
467 for (int a = 0; a < argc; ++a) {
468 if (!strcmp(argv[a], needle))
469 return true;
470 }
471 return false;
472}
473#endif // Q_OS_WIN
474
475QCoreApplicationPrivate::QCoreApplicationPrivate(int &aargc, char **aargv)
476 : argc(aargc), argv(aargv)
477{
478 static const char *const empty = "";
479 if (argc == 0 || argv == nullptr) {
480 argc = 0;
481 argv = const_cast<char **>(&empty);
482 }
483#if defined(Q_OS_WIN)
484 if (!isArgvModified(argc, argv)) {
485 origArgc = argc;
486 origArgv = q20::make_unique_for_overwrite<char *[]>(argc);
487 std::copy(argv, argv + argc, origArgv.get());
488 }
489#endif // Q_OS_WIN
490
491#ifndef QT_NO_QOBJECT
492 QCoreApplicationPrivate::is_app_closing = false;
493
494# if defined(Q_OS_UNIX)
495 if (Q_UNLIKELY(!setuidAllowed && (geteuid() != getuid())))
496 qFatal("FATAL: The application binary appears to be running setuid, this is a security hole.");
497# endif // Q_OS_UNIX
498
499 QThread *cur = QThread::currentThread(); // note: this may end up setting theMainThread!
500 if (cur != theMainThread.loadAcquire())
501 qWarning("WARNING: QApplication was not created in the main() thread.");
502#endif
503}
504
505QCoreApplicationPrivate::~QCoreApplicationPrivate()
506{
507#ifndef QT_NO_QOBJECT
508 cleanupThreadData();
509#endif
510#if defined(Q_OS_WIN) && !defined(QT_BOOTSTRAPPED)
511 cleanupDebuggingConsole();
512#endif
513}
514
515#ifndef QT_NO_QOBJECT
516
517void QCoreApplicationPrivate::cleanupThreadData()
518{
519 auto thisThreadData = threadData.loadRelaxed();
520
521 if (thisThreadData && !threadData_clean) {
522#if QT_CONFIG(thread)
523 QThreadStoragePrivate::finish(&thisThreadData->tls);
524#endif
525
526 // need to clear the state of the mainData, just in case a new QCoreApplication comes along.
527 thisThreadData->clearEvents();
528 thisThreadData->quitNow = false;
529 threadData_clean = true;
530 }
531}
532
533void QCoreApplicationPrivate::createEventDispatcher()
534{
535 Q_Q(QCoreApplication);
536 QThreadData *data = QThreadData::current();
537 Q_ASSERT(!data->hasEventDispatcher());
538 eventDispatcher = data->createEventDispatcher();
539 eventDispatcher->setParent(q);
540}
541
542void QCoreApplicationPrivate::eventDispatcherReady()
543{
544}
545
546Q_CONSTINIT QBasicAtomicPointer<QThread> QCoreApplicationPrivate::theMainThread = Q_BASIC_ATOMIC_INITIALIZER(nullptr);
547Q_CONSTINIT QBasicAtomicPointer<void> QCoreApplicationPrivate::theMainThreadId = Q_BASIC_ATOMIC_INITIALIZER(nullptr);
548QThread *QCoreApplicationPrivate::mainThread()
549{
550 Q_ASSERT(theMainThread.loadRelaxed() != nullptr);
551 return theMainThread.loadRelaxed();
552}
553
554#endif // QT_NO_QOBJECT
555
556QString qAppName()
557{
558 if (!QCoreApplicationPrivate::checkInstance("qAppName"))
559 return QString();
560 return QCoreApplication::instance()->d_func()->appName();
561}
562
563void QCoreApplicationPrivate::initLocale()
564{
565#if defined(QT_BOOTSTRAPPED)
566 // Don't try to control bootstrap library locale or encoding.
567#elif defined(Q_OS_UNIX)
568 Q_CONSTINIT static bool qt_locale_initialized = false;
569 if (qt_locale_initialized)
570 return;
571 qt_locale_initialized = true;
572
573 // By default the portable "C"/POSIX locale is selected and active.
574 // Apply the locale from the environment, via setlocale(), which will
575 // read LC_ALL, LC_<category>, and LANG, in order (for each category).
576 setlocale(LC_ALL, "");
577
578 // Next, let's ensure that LC_CTYPE is UTF-8, since QStringConverter's
579 // QLocal8Bit hard-codes this, and we need to be consistent.
580# if defined(Q_OS_INTEGRITY)
581 setlocale(LC_CTYPE, "UTF-8");
582# elif defined(Q_OS_QNX)
583 // QNX has no nl_langinfo, so we can't check.
584 // FIXME: Shouldn't we still setlocale("UTF-8")?
585# elif defined(Q_OS_ANDROID) && __ANDROID_API__ < __ANDROID_API_O__
586 // Android 6 still lacks nl_langinfo(), so we can't check.
587 // FIXME: Shouldn't we still setlocale("UTF-8")?
588# elif defined(Q_OS_VXWORKS)
589 // VxWorks has no nl_langinfo, so we can't check.
590# else
591 // std::string's SSO usually saves this the need to allocate:
592 const std::string oldEncoding = nl_langinfo(CODESET);
593 if (!Q_LIKELY(qstricmp(oldEncoding.data(), "UTF-8") == 0
594 || qstricmp(oldEncoding.data(), "utf8") == 0)) {
595 const QByteArray oldLocale = setlocale(LC_ALL, nullptr);
596 QByteArray newLocale;
597 bool warnOnOverride = true;
598# if defined(Q_OS_DARWIN)
599 // Don't warn unless the char encoding has been changed from the
600 // default "C" encoding, or the user touched any of the locale
601 // environment variables to force the "C" char encoding.
602 warnOnOverride = qstrcmp(setlocale(LC_CTYPE, nullptr), "C") != 0
603 || getenv("LC_ALL") || getenv("LC_CTYPE") || getenv("LANG");
604
605 // No need to try language or region specific CTYPEs, as they
606 // all point back to the same generic UTF-8 CTYPE.
607 newLocale = setlocale(LC_CTYPE, "UTF-8");
608# else
609 newLocale = setlocale(LC_CTYPE, nullptr);
610 if (qsizetype dot = newLocale.indexOf('.'); dot != -1)
611 newLocale.truncate(dot); // remove encoding, if any
612 if (qsizetype at = newLocale.indexOf('@'); at != -1)
613 newLocale.truncate(at); // remove variant, as the old de_DE@euro
614 newLocale += ".UTF-8";
615 newLocale = setlocale(LC_CTYPE, newLocale);
616
617 // If that locale doesn't exist, try some fallbacks:
618 if (newLocale.isEmpty())
619 newLocale = setlocale(LC_CTYPE, "C.UTF-8");
620 if (newLocale.isEmpty())
621 newLocale = setlocale(LC_CTYPE, "C.utf8");
622# endif
623
624 if (newLocale.isEmpty()) {
625 // Failed to set a UTF-8 locale.
626 qWarning("Detected locale \"%s\" with character encoding \"%s\", which is not UTF-8.\n"
627 "Qt depends on a UTF-8 locale, but has failed to switch to one.\n"
628 "If this causes problems, reconfigure your locale. See the locale(1) manual\n"
629 "for more information.", oldLocale.constData(), oldEncoding.data());
630 } else if (warnOnOverride) {
631 // Let the user know we over-rode their configuration.
632 qWarning("Detected locale \"%s\" with character encoding \"%s\", which is not UTF-8.\n"
633 "Qt depends on a UTF-8 locale, and has switched to \"%s\" instead.\n"
634 "If this causes problems, reconfigure your locale. See the locale(1) manual\n"
635 "for more information.",
636 oldLocale.constData(), oldEncoding.data(), newLocale.constData());
637 }
638 }
639# endif // Platform choice
640#endif // Unix
641}
642
643
644/*!
645 \class QCoreApplication
646 \inmodule QtCore
647 \brief The QCoreApplication class provides an event loop for Qt
648 applications without UI.
649
650 This class is used by non-GUI applications to provide their event
651 loop. For non-GUI application that uses Qt, there should be exactly
652 one QCoreApplication object. For GUI applications, see
653 QGuiApplication. For applications that use the Qt Widgets module,
654 see QApplication.
655
656 QCoreApplication contains the main event loop, where all events
657 from the operating system (e.g., timer and network events) and
658 other sources are processed and dispatched. It also handles the
659 application's initialization and finalization, as well as
660 system-wide and application-wide settings.
661
662 \section1 The Event Loop and Event Handling
663
664 The event loop is started with a call to exec(). Long-running
665 operations can call processEvents() to keep the application
666 responsive.
667
668 In general, we recommend that you create a QCoreApplication,
669 QGuiApplication or a QApplication object in your \c main()
670 function as early as possible. exec() will not return until
671 the event loop exits; e.g., when quit() is called.
672
673 Several static convenience functions are also provided. The
674 QCoreApplication object is available from instance(). Events can
675 be sent with sendEvent() or posted to an event queue with postEvent().
676 Pending events can be removed with removePostedEvents() or dispatched
677 with sendPostedEvents().
678
679 The class provides a quit() slot and an aboutToQuit() signal.
680
681 \section1 Application and Library Paths
682
683 An application has an applicationDirPath() and an
684 applicationFilePath(). Library paths (see QLibrary) can be retrieved
685 with libraryPaths() and manipulated by setLibraryPaths(), addLibraryPath(),
686 and removeLibraryPath().
687
688 \section1 Internationalization and Translations
689
690 Translation files can be added or removed
691 using installTranslator() and removeTranslator(). Application
692 strings can be translated using translate(). The QObject::tr()
693 function is implemented in terms of translate().
694
695 \section1 Accessing Command Line Arguments
696
697 The command line arguments which are passed to QCoreApplication's
698 constructor should be accessed using the arguments() function.
699
700 \note QCoreApplication removes option \c -qmljsdebugger="...". It parses the
701 argument of \c qmljsdebugger, and then removes this option plus its argument.
702
703 For more advanced command line option handling, create a QCommandLineParser.
704
705 \section1 Locale Settings
706
707 On Unix/Linux Qt is configured to use the system locale settings by
708 default. This can cause a conflict when using POSIX functions, for
709 instance, when converting between data types such as floats and
710 strings, since the notation may differ between locales. To get
711 around this problem, call the POSIX function \c{setlocale(LC_NUMERIC,"C")}
712 right after initializing QApplication, QGuiApplication or QCoreApplication
713 to reset the locale that is used for number formatting to "C"-locale.
714
715 \sa QGuiApplication, QAbstractEventDispatcher, QEventLoop,
716 {Producer and Consumer using Semaphores},
717 {Producer and Consumer using Wait Conditions}
718*/
719
720/*!
721 \fn static QCoreApplication *QCoreApplication::instance()
722
723 Returns a pointer to the application's QCoreApplication (or
724 QGuiApplication/QApplication) instance.
725
726 If no instance has been allocated, \nullptr is returned.
727
728 \b{Data race notice}: this function should not be used to test for the
729 existence of the QCoreApplication instance from auxiliary threads, unless
730 the caller code is compiled as C++20.
731*/
732
733/*!
734 \internal
735 */
736QCoreApplication::QCoreApplication(QCoreApplicationPrivate &p)
737#ifdef QT_NO_QOBJECT
738 : d_ptr(&p)
739#else
740 : QObject(p, nullptr)
741#endif
742{
743 d_func()->q_ptr = this;
744 // note: it is the subclasses' job to call
745 // QCoreApplicationPrivate::eventDispatcher->startingUp();
746}
747
748/*!
749 Constructs a Qt core application. Core applications are applications without
750 a graphical user interface. Such applications are used at the console or as
751 server processes.
752
753 The \a argc and \a argv arguments are processed by the application,
754 and made available in a more convenient form by the arguments()
755 function.
756
757 \warning The data referred to by \a argc and \a argv must stay valid
758 for the entire lifetime of the QCoreApplication object. In addition,
759 \a argc must be greater than zero and \a argv must contain at least
760 one valid character string.
761*/
762QCoreApplication::QCoreApplication(int &argc, char **argv
763#ifndef Q_QDOC
764 , int
765#endif
766 )
767#ifdef QT_NO_QOBJECT
768 : d_ptr(new QCoreApplicationPrivate(argc, argv))
769#else
770 : QObject(*new QCoreApplicationPrivate(argc, argv))
771#endif
772{
773 d_func()->q_ptr = this;
774 d_func()->init();
775#ifndef QT_NO_QOBJECT
776 QCoreApplicationPrivate::eventDispatcher->startingUp();
777#endif
778}
779
780/*!
781 \enum QCoreApplication::anonymous
782 \internal
783
784 \value ApplicationFlags QT_VERSION
785*/
786
787void Q_TRACE_INSTRUMENT(qtcore) QCoreApplicationPrivate::init()
788{
789 Q_TRACE_SCOPE(QCoreApplicationPrivate_init);
790
791#if defined(Q_OS_MACOS)
792 QMacAutoReleasePool pool;
793#endif
794
795 Q_Q(QCoreApplication);
796
797#if defined(Q_OS_WIN) && !defined(QT_BOOTSTRAPPED)
798 initDebuggingConsole();
799#endif
800
801 initLocale();
802
803 Q_ASSERT_X(!QCoreApplication::self, "QCoreApplication", "there should be only one application object");
804#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
805# ifdef __cpp_lib_atomic_ref
806 std::atomic_ref(QCoreApplication::self).store(q, std::memory_order_relaxed);
807# else
808 QCoreApplication::self = q;
809# endif
810 g_self.storeRelaxed(q);
811#else
812 QCoreApplication::self.storeRelaxed(q);
813#endif
814
815#if QT_CONFIG(thread)
816#ifdef Q_OS_WASM
817 emscripten::val hardwareConcurrency = emscripten::val::global("navigator")["hardwareConcurrency"];
818 if (hardwareConcurrency.isUndefined())
819 QThreadPrivate::idealThreadCount = 2;
820 else
821 QThreadPrivate::idealThreadCount = hardwareConcurrency.as<int>();
822#endif
823#endif
824
825 // Store app name/version (so they're still available after QCoreApplication is destroyed)
826 if (!coreappdata()->applicationNameSet)
827 coreappdata()->application = appName();
828
829 if (!coreappdata()->applicationVersionSet)
830 coreappdata()->applicationVersion = appVersion();
831
832#if (defined(Q_OS_ANDROID) || defined(Q_OS_HARMONY)) && !defined(QT_BOOTSTRAPPED)
833 // We've deferred initializing the logging registry due to not being
834 // able to guarantee that logging happened on the same thread as the
835 // Qt main thread, but now that the Qt main thread is set up, we can
836 // enable categorized logging.
837 QLoggingRegistry::instance()->initializeRules();
838#endif
839
840#if QT_CONFIG(library)
841 // Reset the lib paths, so that they will be recomputed, taking the availability of argv[0]
842 // into account. If necessary, recompute right away and replay the manual changes on top of the
843 // new lib paths.
844 if (coreappdata->libPathsInitialized()) {
845 const QStringList appPaths = std::exchange(coreappdata->app_libpaths, {});
846 Q_ASSERT(!coreappdata->libPathsInitialized());
847
848 if (coreappdata->libPathsManuallySet()) {
849 const QStringList manualPaths = std::exchange(coreappdata->manual_libpaths, {});
850 Q_ASSERT(!coreappdata->libPathsManuallySet());
851
852 // Replay the delta. As paths can only be prepended to the front or removed from
853 // anywhere in the list, we can just linearly scan the lists and find the items that
854 // have been removed. Once the original list is exhausted we know all the remaining
855 // items have been added.
856 QStringList newPaths(q->libraryPaths());
857 for (qsizetype i = manualPaths.size(), j = appPaths.size(); i > 0 || j > 0; qt_noop()) {
858 if (--j < 0) {
859 newPaths.prepend(manualPaths[--i]);
860 } else if (--i < 0) {
861 newPaths.removeAll(appPaths[j]);
862 } else if (manualPaths[i] != appPaths[j]) {
863 newPaths.removeAll(appPaths[j]);
864 ++i; // try again with next item.
865 }
866 }
867 coreappdata->manual_libpaths.swap(newPaths);
868 }
869 }
870#endif
871
872#ifndef QT_NO_QOBJECT
873 // use the event dispatcher created by the app programmer (if any)
874 Q_ASSERT(!eventDispatcher);
875 auto thisThreadData = threadData.loadRelaxed();
876 eventDispatcher = thisThreadData->eventDispatcher.loadRelaxed();
877
878 // otherwise we create one
879 if (!eventDispatcher)
880 createEventDispatcher();
881 Q_ASSERT(eventDispatcher);
882
883 if (!eventDispatcher->parent()) {
884 eventDispatcher->moveToThread(thisThreadData->thread.loadAcquire());
885 eventDispatcher->setParent(q);
886 }
887
888 thisThreadData->eventDispatcher = eventDispatcher;
889 eventDispatcherReady();
890#endif
891
892 processCommandLineArguments();
893
894 qt_call_pre_routines();
895 QT_MANGLE_NAMESPACE(qt_startup_hook)();
896#ifndef QT_BOOTSTRAPPED
897 QtPrivate::initBindingStatusThreadId();
898 if (Q_UNLIKELY(qtHookData[QHooks::Startup]))
899 reinterpret_cast<QHooks::StartupCallback>(qtHookData[QHooks::Startup])();
900#endif
901
902#ifndef QT_NO_QOBJECT
903 is_app_running = true; // No longer starting up.
904#endif
905}
906
907/*!
908 Destroys the QCoreApplication object.
909*/
910QCoreApplication::~QCoreApplication()
911{
912 preRoutinesCalled = false;
913
914 qt_call_post_routines();
915
916#ifndef QT_NO_QOBJECT
917 QCoreApplicationPrivate::is_app_closing = true;
918 QCoreApplicationPrivate::is_app_running = false;
919#endif
920
921#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
922# ifdef __cpp_lib_atomic_ref
923 std::atomic_ref(self).store(nullptr, std::memory_order_relaxed);
924# else
925 self = nullptr;
926# endif
927 g_self.storeRelaxed(nullptr);
928#else
929 self.storeRelaxed(nullptr);
930#endif
931
932#if QT_CONFIG(thread)
933 // Synchronize and stop the global thread pool threads.
934 QThreadPoolPrivate::destroyGlobalThreadPool();
935#endif
936
937#ifndef QT_NO_QOBJECT
938 QCoreApplicationPrivate::destroyEventDispatcher();
939#endif
940
941#if QT_CONFIG(library)
942 if (coreappdata.exists()) {
943 // neither .clear(), .resize(), nor = {} will make isNull() == true
944 coreappdata->app_libpaths = QStringList();
945 coreappdata->manual_libpaths = QStringList();
946 Q_ASSERT(!coreappdata->libPathsManuallySet());
947 Q_ASSERT(!coreappdata->libPathsInitialized());
948 }
949#endif
950}
951
952/*!
953 \since 5.3
954
955 Allows the application to run setuid on UNIX platforms if \a allow
956 is true.
957
958 If \a allow is false (the default) and Qt detects the application is
959 running with an effective user id different than the real user id,
960 the application will be aborted when a QCoreApplication instance is
961 created.
962
963 Qt is not an appropriate solution for setuid programs due to its
964 large attack surface. However some applications may be required
965 to run in this manner for historical reasons. This flag will
966 prevent Qt from aborting the application when this is detected,
967 and must be set before a QCoreApplication instance is created.
968
969 \note It is strongly recommended not to enable this option since
970 it introduces security risks. If this application does enable the flag and
971 starts child processes, it should drop the privileges as early as possible
972 by calling \c{setuid(2)} for itself, or at the latest by using the
973 QProcess::UnixProcessParameters::ResetIds flag.
974*/
975void QCoreApplication::setSetuidAllowed(bool allow)
976{
977 QCoreApplicationPrivate::setuidAllowed = allow;
978}
979
980/*!
981 \since 5.3
982
983 Returns true if the application is allowed to run setuid on UNIX
984 platforms.
985
986 \sa QCoreApplication::setSetuidAllowed()
987*/
988bool QCoreApplication::isSetuidAllowed()
989{
990 return QCoreApplicationPrivate::setuidAllowed;
991}
992
993/*!
994 Sets the attribute \a attribute if \a on is true;
995 otherwise clears the attribute.
996
997 \note Some application attributes must be set \b before creating a
998 QCoreApplication instance. Refer to the Qt::ApplicationAttribute
999 documentation for more information.
1000
1001 \sa testAttribute()
1002*/
1003void QCoreApplication::setAttribute(Qt::ApplicationAttribute attribute, bool on)
1004{
1005 // Since we bit-shift these values, we can't go higher than 32 on 32 bit operating systems
1006 // without changing the storage type of QCoreApplicationPrivate::attribs to quint64.
1007 static_assert(Qt::AA_AttributeCount <= sizeof(QCoreApplicationPrivate::attribs) * CHAR_BIT);
1008
1009 if (on)
1010 QCoreApplicationPrivate::attribs |= 1 << attribute;
1011 else
1012 QCoreApplicationPrivate::attribs &= ~(1 << attribute);
1013#if defined(QT_NO_QOBJECT)
1014 if (Q_UNLIKELY(qApp)) {
1015#else
1016 if (Q_UNLIKELY(QCoreApplicationPrivate::is_app_running)) {
1017#endif
1018 switch (attribute) {
1019 case Qt::AA_PluginApplication:
1020 case Qt::AA_UseDesktopOpenGL:
1021 case Qt::AA_UseOpenGLES:
1022 case Qt::AA_UseSoftwareOpenGL:
1023#ifdef QT_BOOTSTRAPPED
1024 qWarning("Attribute %d must be set before QCoreApplication is created.",
1025 attribute);
1026#else
1027 qWarning("Attribute Qt::%s must be set before QCoreApplication is created.",
1028 QMetaEnum::fromType<Qt::ApplicationAttribute>().valueToKey(attribute));
1029#endif
1030 break;
1031 default:
1032 break;
1033 }
1034 }
1035}
1036
1037/*!
1038 Returns \c true if attribute \a attribute is set;
1039 otherwise returns \c false.
1040
1041 \sa setAttribute()
1042 */
1043bool QCoreApplication::testAttribute(Qt::ApplicationAttribute attribute)
1044{
1045 return QCoreApplicationPrivate::testAttribute(attribute);
1046}
1047
1048#ifndef QT_NO_QOBJECT
1049
1050/*!
1051 \property QCoreApplication::quitLockEnabled
1052
1053 \brief Whether the use of the QEventLoopLocker feature can cause the
1054 application to quit.
1055
1056 When this property is \c true the release of the last remaining
1057 QEventLoopLocker operating on the application will attempt to
1058 quit the application.
1059
1060 Note that attempting a quit may not necessarily result in the
1061 application quitting, for example if there still are open windows,
1062 or the QEvent::Quit event is ignored.
1063
1064 The default is \c true.
1065
1066 \sa QEventLoopLocker
1067*/
1068
1069bool QCoreApplication::isQuitLockEnabled()
1070{
1071 return quitLockEnabled;
1072}
1073
1074static bool doNotify(QObject *, QEvent *);
1075
1076void QCoreApplication::setQuitLockEnabled(bool enabled)
1077{
1078 quitLockEnabled = enabled;
1079}
1080
1081/*!
1082 \internal
1083 \since 5.6
1084
1085 This function is here to make it possible for Qt extensions to
1086 hook into event notification without subclassing QApplication.
1087*/
1088bool QCoreApplication::notifyInternal2(QObject *receiver, QEvent *event)
1089{
1090 // Qt enforces the rule that events can only be sent to objects in
1091 // the current thread, so receiver->d_func()->threadData is
1092 // equivalent to QThreadData::current(), just without the function
1093 // call overhead.
1094 QObjectPrivate *d = receiver->d_func();
1095 QThreadData *threadData = d->threadData.loadAcquire();
1096 bool selfRequired = threadData->requiresCoreApplication;
1097 if (selfRequired && !qApp)
1098 return false;
1099
1100 // Make it possible for Qt Script to hook into events even
1101 // though QApplication is subclassed...
1102 bool result = false;
1103 void *cbdata[] = { receiver, event, &result };
1104 if (QInternal::activateCallbacks(QInternal::EventNotifyCallback, cbdata)) {
1105 return result;
1106 }
1107
1108 QScopedScopeLevelCounter scopeLevelCounter(threadData);
1109 if (!selfRequired)
1110 return doNotify(receiver, event);
1111
1112 if (QCoreApplicationPrivate::is_app_closing)
1113 return false; // no event delivery while the application is closing
1114
1115#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0)
1116 if (!QThread::isMainThread())
1117 return false;
1118#endif
1119 return qApp->notify(receiver, event);
1120}
1121
1122/*!
1123 \internal
1124 \since 5.10
1125
1126 Forwards the \a event to the \a receiver, using the spontaneous
1127 state of the \a originatingEvent if specified.
1128*/
1129bool QCoreApplication::forwardEvent(QObject *receiver, QEvent *event, QEvent *originatingEvent)
1130{
1131 if (event && originatingEvent)
1132 event->m_spont = originatingEvent->m_spont;
1133
1134 return notifyInternal2(receiver, event);
1135}
1136
1137/*!
1138 Sends \a event to \a receiver: \a {receiver}->event(\a event).
1139 Returns the value that is returned from the receiver's event
1140 handler. Note that this function is called for all events sent to
1141 any object in any thread.
1142
1143 For certain types of events (e.g. mouse and key events),
1144 the event will be propagated to the receiver's parent and so on up to
1145 the top-level object if the receiver is not interested in the event
1146 (i.e., it returns \c false).
1147
1148 There are five different ways that events can be processed;
1149 reimplementing this virtual function is just one of them. All five
1150 approaches are listed below:
1151 \list 1
1152 \li Reimplementing \l {QWidget::}{paintEvent()}, \l {QWidget::}{mousePressEvent()} and so
1153 on. This is the most common, easiest, and least powerful way.
1154
1155 \li Reimplementing this function. This is very powerful, providing
1156 complete control; but only one subclass can be active at a time.
1157
1158 \li Installing an event filter on QCoreApplication::instance(). Such
1159 an event filter is able to process all events for all widgets, so
1160 it's just as powerful as reimplementing notify(); furthermore, it's
1161 possible to have more than one application-global event filter.
1162 Global event filters even see mouse events for
1163 \l{QWidget::isEnabled()}{disabled widgets}. Note that application
1164 event filters are only called for objects that live in the main
1165 thread.
1166
1167 \li Reimplementing QObject::event() (as QWidget does). If you do
1168 this you get Tab key presses, and you get to see the events before
1169 any widget-specific event filters.
1170
1171 \li Installing an event filter on the object. Such an event filter gets all
1172 the events, including Tab and Shift+Tab key press events, as long as they
1173 do not change the focus widget.
1174 \endlist
1175
1176 \b{Future direction:} This function will not be called for objects that live
1177 outside the main thread in Qt 7. Applications that need that functionality
1178 should find other solutions for their event inspection needs in the meantime.
1179 The change may be extended to the main thread, causing this function to be
1180 deprecated.
1181
1182 \warning If you override this function, you must ensure all threads that
1183 process events stop doing so before your application object begins
1184 destruction. This includes threads started by other libraries that you may be
1185 using, but does not apply to Qt's own threads.
1186
1187 \sa QObject::event(), installNativeEventFilter()
1188*/
1189
1190bool QCoreApplication::notify(QObject *receiver, QEvent *event)
1191{
1192 Q_ASSERT(receiver);
1193 Q_ASSERT(event);
1194
1195#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0)
1196 Q_ASSERT(receiver->d_func()->threadData.loadAcquire()->thread.loadRelaxed()
1197 == QCoreApplicationPrivate::mainThread());
1198#endif
1199
1200 // no events are delivered after ~QCoreApplication() has started
1201 if (QCoreApplicationPrivate::is_app_closing)
1202 return true;
1203 return doNotify(receiver, event);
1204}
1205
1206static bool doNotify(QObject *receiver, QEvent *event)
1207{
1208 Q_ASSERT(event);
1209
1210 // ### Qt 7: turn into an assert
1211 if (receiver == nullptr) { // serious error
1212 qWarning("QCoreApplication::notify: Unexpected null receiver");
1213 return true;
1214 }
1215
1216 QCoreApplicationPrivate::checkReceiverThread(receiver, "QCoreApplication::notify");
1217
1218 return receiver->isWidgetType() ? false : QCoreApplicationPrivate::notify_helper(receiver, event);
1219}
1220
1221bool QCoreApplicationPrivate::sendThroughApplicationEventFilters(QObject *receiver, QEvent *event)
1222{
1223 // We can't access the application event filters outside of the main thread (race conditions)
1224 Q_ASSERT(QThread::isMainThread());
1225
1226 if (extraData) {
1227 // application event filters are only called for objects in the GUI thread
1228 for (qsizetype i = 0; i < extraData->eventFilters.size(); ++i) {
1229 QObject *obj = extraData->eventFilters.at(i);
1230 if (!obj)
1231 continue;
1232 if (obj->d_func()->threadData.loadRelaxed() != threadData.loadRelaxed()) {
1233 qWarning("QCoreApplication: Application event filter cannot be in a different thread.");
1234 continue;
1235 }
1236 if (obj->eventFilter(receiver, event))
1237 return true;
1238 }
1239 }
1240 return false;
1241}
1242
1243bool QCoreApplicationPrivate::sendThroughObjectEventFilters(QObject *receiver, QEvent *event)
1244{
1245 if (receiver != qApp && receiver->d_func()->extraData) {
1246 for (qsizetype i = 0; i < receiver->d_func()->extraData->eventFilters.size(); ++i) {
1247 QObject *obj = receiver->d_func()->extraData->eventFilters.at(i);
1248 if (!obj)
1249 continue;
1250 if (obj->d_func()->threadData.loadRelaxed() != receiver->d_func()->threadData.loadRelaxed()) {
1251 qWarning("QCoreApplication: Object event filter cannot be in a different thread.");
1252 continue;
1253 }
1254 if (obj->eventFilter(receiver, event))
1255 return true;
1256 }
1257 }
1258 return false;
1259}
1260
1261/*!
1262 \internal
1263
1264 Helper function called by QCoreApplicationPrivate::notify() and qapplication.cpp
1265 */
1266bool QCoreApplicationPrivate::notify_helper(QObject *receiver, QEvent * event)
1267{
1268 // Note: when adjusting the tracepoints in here
1269 // consider adjusting QApplicationPrivate::notify_helper too.
1270 Q_TRACE(QCoreApplication_notify_entry, receiver, event, event->type());
1271 bool consumed = false;
1272 bool filtered = false;
1273 Q_TRACE_EXIT(QCoreApplication_notify_exit, consumed, filtered);
1274
1275 // send to all application event filters (only does anything in the main thread)
1276 if (QThread::isMainThread()
1277 && QCoreApplication::self
1278 && QCoreApplication::self->d_func()->sendThroughApplicationEventFilters(receiver, event)) {
1279 filtered = true;
1280 return filtered;
1281 }
1282 // send to all receiver event filters
1283 if (sendThroughObjectEventFilters(receiver, event)) {
1284 filtered = true;
1285 return filtered;
1286 }
1287
1288 // deliver the event
1289 consumed = receiver->event(event);
1290 return consumed;
1291}
1292
1293/*!
1294 Returns \c true if an application object has not been created yet;
1295 otherwise returns \c false.
1296
1297 \sa closingDown()
1298*/
1299
1300bool QCoreApplication::startingUp()
1301{
1302 return !QCoreApplicationPrivate::is_app_running;
1303}
1304
1305/*!
1306 Returns \c true if the application objects are being destroyed;
1307 otherwise returns \c false.
1308
1309 \sa startingUp()
1310*/
1311
1312bool QCoreApplication::closingDown()
1313{
1314 return QCoreApplicationPrivate::is_app_closing;
1315}
1316
1317
1318/*!
1319 Processes some pending events for the calling thread according to
1320 the specified \a flags.
1321
1322 Use of this function is discouraged. Instead, prefer to move long
1323 operations out of the GUI thread into an auxiliary one and to completely
1324 avoid nested event loop processing. If event processing is really
1325 necessary, consider using \l QEventLoop instead.
1326
1327 In the event that you are running a local loop which calls this function
1328 continuously, without an event loop, the
1329 \l{QEvent::DeferredDelete}{DeferredDelete} events will
1330 not be processed. This can affect the behaviour of widgets,
1331 e.g. QToolTip, that rely on \l{QEvent::DeferredDelete}{DeferredDelete}
1332 events to function properly. An alternative would be to call
1333 \l{QCoreApplication::sendPostedEvents()}{sendPostedEvents()} from
1334 within that local loop.
1335
1336 Calling this function processes events only for the calling thread,
1337 and returns after all available events have been processed. Available
1338 events are events queued before the function call. This means that
1339 events that are posted while the function runs will be queued until
1340 a later round of event processing.
1341
1342 \threadsafe
1343
1344 \sa exec(), QTimer, QChronoTimer, QEventLoop::processEvents(),
1345 sendPostedEvents()
1346*/
1347void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags)
1348{
1349 QThreadData *data = QThreadData::current();
1350 if (!data->hasEventDispatcher())
1351 return;
1352 data->eventDispatcher.loadRelaxed()->processEvents(flags);
1353}
1354
1355/*!
1356 \overload
1357
1358 Processes pending events for the calling thread for \a ms
1359 milliseconds or until there are no more events to process,
1360 whichever is shorter.
1361
1362 This is equivalent to calling:
1363 \code
1364 QCoreApplication::processEvents(flags, QDeadlineTimer(ms));
1365 \endcode
1366*/
1367void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags, int ms)
1368{
1369 QCoreApplication::processEvents(flags, QDeadlineTimer(ms));
1370}
1371
1372/*!
1373 \since 6.7
1374 \overload
1375
1376 Processes pending events for the calling thread untile \a deadline has expired,
1377 or until there are no more events to process, whichever happens first.
1378
1379 Use of this function is discouraged. Instead, prefer to move long
1380 operations out of the GUI thread into an auxiliary one and to completely
1381 avoid nested event loop processing. If event processing is really
1382 necessary, consider using \l QEventLoop instead.
1383
1384 Calling this function processes events only for the calling thread.
1385
1386 \note Unlike the \l{QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags)}{processEvents()}
1387 overload, this function also processes events that are posted while the function runs.
1388
1389 \note All events that were queued before the timeout will be processed,
1390 however long it takes.
1391
1392 \threadsafe
1393
1394 \sa exec(), QTimer, QChronoTimer, QEventLoop::processEvents()
1395*/
1396void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags, QDeadlineTimer deadline)
1397{
1398 // ### TODO: consider splitting this method into a public and a private
1399 // one, so that a user-invoked processEvents can be detected
1400 // and handled properly.
1401 QThreadData *data = QThreadData::current();
1402 if (!data->hasEventDispatcher())
1403 return;
1404
1405 while (data->eventDispatcher.loadRelaxed()->processEvents(flags & ~QEventLoop::WaitForMoreEvents)) {
1406 if (deadline.hasExpired())
1407 break;
1408 }
1409}
1410
1411/*****************************************************************************
1412 Main event loop wrappers
1413 *****************************************************************************/
1414
1415/*!
1416 Enters the main event loop and waits until exit() is called. Returns
1417 the value that was passed to exit() (which is 0 if exit() is called via
1418 quit()).
1419
1420 It is necessary to call this function to start event handling. The
1421 main event loop receives events from the window system and
1422 dispatches these to the application widgets.
1423
1424 To make your application perform idle processing (by executing a special
1425 function whenever there are no pending events), use a QChronoTimer
1426 with 0ns timeout. More advanced idle processing schemes can be achieved
1427 using processEvents().
1428
1429 We recommend that you connect clean-up code to the
1430 \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in
1431 your application's \c{main()} function because on some platforms the
1432 exec() call may not return. For example, on Windows
1433 when the user logs off, the system terminates the process after Qt
1434 closes all top-level windows. Hence, there is no guarantee that the
1435 application will have time to exit its event loop and execute code at
1436 the end of the \c{main()} function after the exec()
1437 call.
1438
1439 \sa quit(), exit(), processEvents(), QApplication::exec()
1440*/
1441int QCoreApplication::exec()
1442{
1443 if (!QCoreApplicationPrivate::checkInstance("exec"))
1444 return -1;
1445
1446 QThreadData *threadData = self->d_func()->threadData.loadAcquire();
1447 if (threadData != QThreadData::current()) {
1448 qWarning("%s::exec: Must be called from the main thread", self->metaObject()->className());
1449 return -1;
1450 }
1451 if (!threadData->eventLoops.isEmpty()) {
1452 qWarning("QCoreApplication::exec: The event loop is already running");
1453 return -1;
1454 }
1455
1456 threadData->quitNow = false;
1457 QEventLoop eventLoop;
1458 self->d_func()->in_exec = true;
1459 self->d_func()->aboutToQuitEmitted = false;
1460 int returnCode = eventLoop.exec(QEventLoop::ApplicationExec);
1461 threadData->quitNow = false;
1462
1463 if (self)
1464 self->d_func()->execCleanup();
1465
1466 return returnCode;
1467}
1468
1469
1470// Cleanup after eventLoop is done executing in QCoreApplication::exec().
1471// This is for use cases in which QCoreApplication is instantiated by a
1472// library and not by an application executable, for example, Active X
1473// servers.
1474
1475void QCoreApplicationPrivate::execCleanup()
1476{
1477 threadData.loadRelaxed()->quitNow = false;
1478 in_exec = false;
1479 QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
1480}
1481
1482
1483/*!
1484 Tells the application to exit with a return code.
1485
1486 After this function has been called, the application leaves the
1487 main event loop and returns from the call to exec(). The exec()
1488 function returns \a returnCode. If the event loop is not running,
1489 this function does nothing.
1490
1491 By convention, a \a returnCode of 0 means success, and any non-zero
1492 value indicates an error.
1493
1494 It's good practice to always connect signals to this slot using a
1495 \l{Qt::}{QueuedConnection}. If a signal connected (non-queued) to this slot
1496 is emitted before control enters the main event loop (such as before
1497 "int main" calls \l{QCoreApplication::}{exec()}), the slot has no effect
1498 and the application never exits. Using a queued connection ensures that the
1499 slot will not be invoked until after control enters the main event loop.
1500
1501 Note that unlike the C library function of the same name, this
1502 function \e does return to the caller -- it is event processing that
1503 stops.
1504
1505 Note also that this function is not thread-safe. It should be called only
1506 from the main thread (the thread that the QCoreApplication object is
1507 processing events on). To ask the application to exit from another thread,
1508 either use QCoreApplication::quit() or instead call this function from the
1509 main thread with QMetaMethod::invokeMethod().
1510
1511 \sa quit(), exec()
1512*/
1513void QCoreApplication::exit(int returnCode)
1514{
1515 if (!self)
1516 return;
1517
1518#ifdef Q_OS_WASM
1519 if (!qstdweb::haveAsyncify())
1520 qFatal("Terminating since we don't have asyncify");
1521#endif
1522 QCoreApplicationPrivate *d = self->d_func();
1523 if (!d->aboutToQuitEmitted) {
1524 emit self->aboutToQuit(QCoreApplication::QPrivateSignal());
1525 d->aboutToQuitEmitted = true;
1526 }
1527 QThreadData *data = d->threadData.loadRelaxed();
1528 data->quitNow = true;
1529 for (qsizetype i = 0; i < data->eventLoops.size(); ++i) {
1530 QEventLoop *eventLoop = data->eventLoops.at(i);
1531 eventLoop->exit(returnCode);
1532 }
1533}
1534
1535/*****************************************************************************
1536 QCoreApplication management of posted events
1537 *****************************************************************************/
1538
1539#ifndef QT_NO_QOBJECT
1540/*!
1541 \fn bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
1542
1543 Sends event \a event directly to receiver \a receiver, using the
1544 notify() function. Returns the value that was returned from the
1545 event handler.
1546
1547 The event is \e not deleted when the event has been sent. The normal
1548 approach is to create the event on the stack, for example:
1549
1550 \snippet code/src_corelib_kernel_qcoreapplication.cpp 0
1551
1552 \sa postEvent(), notify()
1553*/
1554bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
1555{
1556 Q_ASSERT_X(receiver, "QCoreApplication::sendEvent", "Unexpected null receiver");
1557 Q_ASSERT_X(event, "QCoreApplication::sendEvent", "Unexpected null event");
1558
1559 Q_TRACE(QCoreApplication_sendEvent, receiver, event, event->type());
1560
1561 event->m_spont = false;
1562 return notifyInternal2(receiver, event);
1563}
1564
1565/*!
1566 \internal
1567*/
1568bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
1569{
1570 Q_ASSERT_X(receiver, "QCoreApplication::sendSpontaneousEvent", "Unexpected null receiver");
1571 Q_ASSERT_X(event, "QCoreApplication::sendSpontaneousEvent", "Unexpected null event");
1572
1573 Q_TRACE(QCoreApplication_sendSpontaneousEvent, receiver, event, event->type());
1574
1575 event->m_spont = true;
1576 return notifyInternal2(receiver, event);
1577}
1578
1579#endif // QT_NO_QOBJECT
1580
1581QCoreApplicationPrivate::QPostEventListLocker QCoreApplicationPrivate::lockThreadPostEventList(QObject *object)
1582{
1583 QPostEventListLocker locker;
1584
1585 if (!object) {
1586 locker.threadData = QThreadData::current();
1587 locker.locker = qt_unique_lock(locker.threadData->postEventList.mutex);
1588 return locker;
1589 }
1590
1591 auto &threadData = QObjectPrivate::get(object)->threadData;
1592
1593 // if object has moved to another thread, follow it
1594 for (;;) {
1595 // synchronizes with the storeRelease in QObject::moveToThread
1596 locker.threadData = threadData.loadAcquire();
1597 if (!locker.threadData) {
1598 // destruction in progress
1599 return locker;
1600 }
1601
1602 auto temporaryLocker = qt_unique_lock(locker.threadData->postEventList.mutex);
1603 if (locker.threadData == threadData.loadAcquire()) {
1604 locker.locker = std::move(temporaryLocker);
1605 break;
1606 }
1607 }
1608
1609 Q_ASSERT(locker.threadData);
1610 return locker;
1611}
1612
1613/*!
1614 \since 4.3
1615
1616 Adds the event \a event, with the object \a receiver as the
1617 receiver of the event, to an event queue and returns immediately.
1618
1619 The event must be allocated on the heap since the post event queue
1620 will take ownership of the event and delete it once it has been
1621 posted. It is \e {not safe} to access the event after
1622 it has been posted.
1623
1624 When control returns to the main event loop, all events that are
1625 stored in the queue will be sent using the notify() function.
1626
1627 Events are sorted in descending \a priority order, i.e. events
1628 with a high \a priority are queued before events with a lower \a
1629 priority. The \a priority can be any integer value, i.e. between
1630 INT_MAX and INT_MIN, inclusive; see Qt::EventPriority for more
1631 details. Events with equal \a priority will be processed in the
1632 order posted.
1633
1634 \note QObject::deleteLater() schedules the object for deferred
1635 deletion, which is typically handled by the receiver's event
1636 loop. If no event loop is running in the thread, the deletion
1637 will be performed when the thread finishes. A common and safe
1638 pattern is to connect the thread's finished() signal to the
1639 object's deleteLater() slot:
1640
1641 \code
1642 QObject::connect(thread, &QThread::finished, worker, &QObject::deleteLater);
1643 \endcode
1644
1645 \threadsafe
1646
1647 \sa sendEvent(), notify(), sendPostedEvents(), Qt::EventPriority
1648*/
1649void QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority)
1650{
1651 Q_ASSERT_X(event, "QCoreApplication::postEvent", "Unexpected null event");
1652
1653 Q_TRACE_SCOPE(QCoreApplication_postEvent, receiver, event, event->type());
1654
1655 // ### Qt 7: turn into an assert
1656 if (receiver == nullptr) {
1657 qWarning("QCoreApplication::postEvent: Unexpected null receiver");
1658 delete event;
1659 return;
1660 }
1661
1662 auto locker = QCoreApplicationPrivate::lockThreadPostEventList(receiver);
1663 if (!locker.threadData) {
1664 // posting during destruction? just delete the event to prevent a leak
1665 delete event;
1666 return;
1667 }
1668
1669 QThreadData *data = locker.threadData;
1670
1671 QT_WARNING_PUSH
1672 QT_WARNING_DISABLE_DEPRECATED // compressEvent()
1673 // if this is one of the compressible events, do compression
1674 if (receiver->d_func()->postedEvents.loadAcquire()
1675 && self && self->compressEvent(event, receiver, &data->postEventList)) {
1676 Q_TRACE(QCoreApplication_postEvent_event_compressed, receiver, event);
1677 return;
1678 }
1679 QT_WARNING_POP
1680
1681 // delete the event on exceptions to protect against memory leaks till the event is
1682 // properly owned in the postEventList
1683 std::unique_ptr<QEvent> eventDeleter(event);
1684 Q_TRACE(QCoreApplication_postEvent_event_posted, receiver, event, event->type());
1685 data->postEventList.addEvent(QPostEvent(receiver, event, priority));
1686 Q_UNUSED(eventDeleter.release());
1687 event->m_posted = true;
1688 receiver->d_func()->postedEvents.fetchAndAddRelease(1);
1689 data->canWait = false;
1690 locker.unlock();
1691
1692 QAbstractEventDispatcher* dispatcher = data->eventDispatcher.loadAcquire();
1693 if (dispatcher)
1694 dispatcher->wakeUp();
1695}
1696
1697/*!
1698 \internal
1699 Returns \c true if \a event was compressed away (possibly deleted) and should not be added to the list.
1700*/
1701#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
1702bool QCoreApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
1703{
1704 return d_func()->compressEvent(event, receiver, postedEvents);
1705}
1706#endif
1707
1708bool QCoreApplicationPrivate::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
1709{
1710 Q_ASSERT(event);
1711 Q_ASSERT(receiver);
1712 Q_ASSERT(postedEvents);
1713
1714 // Events before startOffset have already been delivered by
1715 // sendPostedEvents() and have a null event pointer, so there is no
1716 // need to look at them.
1717 const auto pending = QSpan(std::as_const(*postedEvents)).subspan(postedEvents->startOffset);
1718
1719 // compress posted timers to this object.
1720 if (event->type() == QEvent::Timer) {
1721 const int timerId = static_cast<QTimerEvent *>(event)->timerId();
1722 auto it = pending.begin();
1723 const auto end = pending.end();
1724 while (it != end) {
1725 if (it->event && it->event->type() == QEvent::Timer && it->receiver == receiver) {
1726 if (static_cast<QTimerEvent *>(it->event)->timerId() == timerId) {
1727 delete event;
1728 return true;
1729 }
1730 }
1731 ++it;
1732 }
1733 return false;
1734 }
1735
1736 if (event->type() == QEvent::Quit) {
1737 for (const QPostEvent &cur : pending) {
1738 if (cur.receiver != receiver
1739 || cur.event == nullptr
1740 || cur.event->type() != event->type())
1741 continue;
1742 // found an event for this receiver
1743 delete event;
1744 return true;
1745 }
1746 }
1747
1748 return false;
1749}
1750
1751/*!
1752 Immediately dispatches all events which have been previously queued
1753 with QCoreApplication::postEvent() and which are for the object \a
1754 receiver and have the event type \a event_type.
1755
1756 Events from the window system are \e not dispatched by this
1757 function, but by processEvents().
1758
1759 If \a receiver is \nullptr, the events of \a event_type are sent for
1760 all objects. If \a event_type is 0, all the events are sent for
1761 \a receiver.
1762
1763 \note This method must be called from the thread in which its QObject
1764 parameter, \a receiver, lives.
1765
1766 \sa postEvent()
1767*/
1768void QCoreApplication::sendPostedEvents(QObject *receiver, int event_type)
1769{
1770 // ### TODO: consider splitting this method into a public and a private
1771 // one, so that a user-invoked sendPostedEvents can be detected
1772 // and handled properly.
1773 QThreadData *data = QThreadData::current();
1774
1775 QCoreApplicationPrivate::sendPostedEvents(receiver, event_type, data);
1776}
1777
1778void QCoreApplicationPrivate::sendPostedEvents(QObject *receiver, int event_type,
1779 QThreadData *data)
1780{
1781 if (event_type == -1) {
1782 // we were called by an obsolete event dispatcher.
1783 event_type = 0;
1784 }
1785
1786 if (receiver && receiver->d_func()->threadData.loadRelaxed() != data) {
1787 qWarning("QCoreApplication::sendPostedEvents: Cannot send "
1788 "posted events for objects in another thread");
1789 return;
1790 }
1791
1792 ++data->postEventList.recursion;
1793
1794 auto locker = qt_unique_lock(data->postEventList.mutex);
1795
1796 // by default, we assume that the event dispatcher can go to sleep after
1797 // processing all events. if any new events are posted while we send
1798 // events, canWait will be set to false.
1799 data->canWait = (data->postEventList.size() == 0);
1800
1801 if (data->postEventList.size() == 0
1802 || (receiver && !receiver->d_func()->postedEvents.loadAcquire())) {
1803 --data->postEventList.recursion;
1804 return;
1805 }
1806
1807 data->canWait = true;
1808
1809 // okay. here is the tricky loop. be careful about optimizing
1810 // this, it looks the way it does for good reasons.
1811 qsizetype startOffset = data->postEventList.startOffset;
1812 qsizetype &i = (!event_type && !receiver) ? data->postEventList.startOffset : startOffset;
1813 data->postEventList.insertionOffset = data->postEventList.size();
1814
1815 // Exception-safe cleaning up without the need for a try/catch block
1816 struct CleanUp {
1817 Q_DISABLE_COPY_MOVE(CleanUp)
1818
1819 QObject *receiver;
1820 int event_type;
1821 QThreadData *data;
1822 bool exceptionCaught;
1823
1824 inline CleanUp(QObject *receiver, int event_type, QThreadData *data) :
1825 receiver(receiver), event_type(event_type), data(data), exceptionCaught(true)
1826 {}
1827 inline ~CleanUp()
1828 {
1829 if (exceptionCaught) {
1830 // since we were interrupted, we need another pass to make sure we clean everything up
1831 data->canWait = false;
1832 }
1833
1834 --data->postEventList.recursion;
1835 if (!data->postEventList.recursion && !data->canWait && data->hasEventDispatcher())
1836 data->eventDispatcher.loadRelaxed()->wakeUp();
1837
1838 // clear the global list, i.e. remove everything that was
1839 // delivered.
1840 if (!event_type && !receiver && data->postEventList.startOffset >= 0) {
1841 const QPostEventList::iterator it = data->postEventList.begin();
1842 data->postEventList.erase(it, it + data->postEventList.startOffset);
1843 data->postEventList.insertionOffset -= data->postEventList.startOffset;
1844 Q_ASSERT(data->postEventList.insertionOffset >= 0);
1845 data->postEventList.startOffset = 0;
1846 }
1847 }
1848 };
1849 CleanUp cleanup(receiver, event_type, data);
1850
1851 while (i < data->postEventList.size()) {
1852 // avoid live-lock
1853 if (i >= data->postEventList.insertionOffset)
1854 break;
1855
1856 const QPostEvent &pe = data->postEventList.at(i);
1857 ++i;
1858
1859 if (!pe.event)
1860 continue;
1861 if ((receiver && receiver != pe.receiver) || (event_type && event_type != pe.event->type())) {
1862 data->canWait = false;
1863 continue;
1864 }
1865
1866 if (pe.event->type() == QEvent::DeferredDelete) {
1867 // DeferredDelete events are sent either
1868 // 1) when the event loop that posted the event has returned; or
1869 // 2) if explicitly requested (with QEvent::DeferredDelete) for
1870 // events posted by the current event loop; or
1871 // 3) if the event was posted before the outermost event loop.
1872
1873 const int eventLoopLevel = static_cast<QDeferredDeleteEvent *>(pe.event)->loopLevel();
1874 const int eventScopeLevel = static_cast<QDeferredDeleteEvent *>(pe.event)->scopeLevel();
1875
1876 const bool postedBeforeOutermostLoop = eventLoopLevel == 0;
1877 const bool allowDeferredDelete =
1878 (eventLoopLevel + eventScopeLevel > data->loopLevel + data->scopeLevel
1879 || (postedBeforeOutermostLoop && data->loopLevel > 0)
1880 || (event_type == QEvent::DeferredDelete
1881 && eventLoopLevel + eventScopeLevel == data->loopLevel + data->scopeLevel));
1882 if (!allowDeferredDelete) {
1883 // cannot send deferred delete
1884 if (!event_type && !receiver) {
1885 // we must copy it first; we want to re-post the event
1886 // with the event pointer intact, but we can't delay
1887 // nulling the event ptr until after re-posting, as
1888 // addEvent may invalidate pe.
1889 QPostEvent pe_copy = pe;
1890
1891 // null out the event so if sendPostedEvents recurses, it
1892 // will ignore this one, as it's been re-posted.
1893 const_cast<QPostEvent &>(pe).event = nullptr;
1894
1895 // re-post the copied event so it isn't lost
1896 data->postEventList.addEvent(pe_copy);
1897 }
1898 continue;
1899 }
1900 }
1901
1902 // first, we diddle the event so that we can deliver
1903 // it, and that no one will try to touch it later.
1904 pe.event->m_posted = false;
1905 QEvent *e = pe.event;
1906 QObject * r = pe.receiver;
1907
1908 [[maybe_unused]]
1909 const auto previous = r->d_func()->postedEvents.fetchAndSubAcquire(1);
1910 Q_ASSERT(previous > 0);
1911
1912 // next, update the data structure so that we're ready
1913 // for the next event.
1914 const_cast<QPostEvent &>(pe).event = nullptr;
1915
1916 locker.unlock();
1917 const auto relocker = qScopeGuard([&locker] { locker.lock(); });
1918
1919 const std::unique_ptr<QEvent> event_deleter(e); // will delete the event (with the mutex unlocked)
1920
1921 // after all that work, it's time to deliver the event.
1922 QCoreApplication::sendEvent(r, e);
1923
1924 // careful when adding anything below this point - the
1925 // sendEvent() call might invalidate any invariants this
1926 // function depends on.
1927 }
1928
1929 cleanup.exceptionCaught = false;
1930}
1931
1932/*!
1933 \since 4.3
1934
1935 Removes all events of the given \a eventType that were posted
1936 using postEvent() for \a receiver.
1937
1938 The events are \e not dispatched, instead they are removed from
1939 the queue. You should never need to call this function. If you do
1940 call it, be aware that killing events may cause \a receiver to
1941 break one or more invariants.
1942
1943 If \a receiver is \nullptr, the events of \a eventType are removed
1944 for all objects. If \a eventType is 0, all the events are removed
1945 for \a receiver. You should never call this function with \a
1946 eventType of 0.
1947
1948 \threadsafe
1949*/
1950
1951void QCoreApplication::removePostedEvents(QObject *receiver, int eventType)
1952{
1953 auto locker = QCoreApplicationPrivate::lockThreadPostEventList(receiver);
1954 QThreadData *data = locker.threadData;
1955
1956 // the QObject destructor calls this function directly. this can
1957 // happen while the event loop is in the middle of posting events,
1958 // and when we get here, we may not have any more posted events
1959 // for this object.
1960 if (receiver && !receiver->d_func()->postedEvents.loadAcquire())
1961 return;
1962
1963 //we will collect all the posted events for the QObject
1964 //and we'll delete after the mutex was unlocked
1965 QVarLengthArray<QEvent*> events;
1966 qsizetype n = data->postEventList.size();
1967 qsizetype j = 0;
1968
1969 for (qsizetype i = 0; i < n; ++i) {
1970 const QPostEvent &pe = data->postEventList.at(i);
1971
1972 if ((!receiver || pe.receiver == receiver)
1973 && (pe.event && (eventType == 0 || pe.event->type() == eventType))) {
1974 pe.receiver->d_func()->postedEvents.fetchAndSubAcquire(1);
1975 pe.event->m_posted = false;
1976 events.append(pe.event);
1977 const_cast<QPostEvent &>(pe).event = nullptr;
1978 } else if (!data->postEventList.recursion) {
1979 if (i != j)
1980 qSwap(data->postEventList[i], data->postEventList[j]);
1981 ++j;
1982 }
1983 }
1984
1985#ifdef QT_DEBUG
1986 if (receiver && eventType == 0) {
1987 Q_ASSERT(!receiver->d_func()->postedEvents.loadRelaxed());
1988 }
1989#endif
1990
1991 if (!data->postEventList.recursion) {
1992 // truncate list
1993 data->postEventList.erase(data->postEventList.begin() + j, data->postEventList.end());
1994 }
1995
1996 locker.unlock();
1997 qDeleteAll(events);
1998}
1999
2000/*!
2001 Removes \a event from the queue of posted events, and emits a
2002 warning message if appropriate.
2003
2004 \warning This function can be \e really slow. Avoid using it, if
2005 possible.
2006
2007 \threadsafe
2008 \internal
2009*/
2010
2011void QCoreApplicationPrivate::removePostedEvent(QEvent * event)
2012{
2013 if (!event || !event->m_posted)
2014 return;
2015
2016 QThreadData *data = QThreadData::current();
2017
2018 const auto locker = qt_scoped_lock(data->postEventList.mutex);
2019
2020 if (data->postEventList.size() == 0) {
2021#if defined(QT_DEBUG)
2022 qDebug("QCoreApplication::removePostedEvent: Internal error: %p %d is posted",
2023 (void*)event, event->type());
2024 return;
2025#endif
2026 }
2027
2028 for (const QPostEvent &pe : std::as_const(data->postEventList)) {
2029 if (pe.event == event) {
2030#ifndef QT_NO_DEBUG
2031 qWarning("QCoreApplication::removePostedEvent: Event of type %d deleted while posted to %s %s",
2032 event->type(),
2033 pe.receiver->metaObject()->className(),
2034 pe.receiver->objectName().toLocal8Bit().data());
2035#endif
2036 pe.receiver->d_func()->postedEvents.fetchAndSubAcquire(1);
2037 pe.event->m_posted = false;
2038 delete pe.event;
2039 const_cast<QPostEvent &>(pe).event = nullptr;
2040 return;
2041 }
2042 }
2043}
2044
2045/*!\reimp
2046
2047*/
2048bool QCoreApplication::event(QEvent *e)
2049{
2050 Q_D(QCoreApplication);
2051 if (e->type() == QEvent::Quit) {
2052 if (d->handlingQuitEvent) {
2053 e->ignore();
2054 return true;
2055 }
2056
2057 QScopedValueRollback rollback(d->handlingQuitEvent, true);
2058 e->setAccepted(d->handleQuitEvent());
2059 return true;
2060 }
2061 return QObject::event(e);
2062}
2063
2064void QCoreApplicationPrivate::ref()
2065{
2066 quitLockRef.ref();
2067}
2068
2069void QCoreApplicationPrivate::deref()
2070{
2071 quitLockRef.deref();
2072
2073 if (quitLockEnabled && canQuitAutomatically())
2074 quitAutomatically();
2075}
2076
2077bool QCoreApplicationPrivate::canQuitAutomatically()
2078{
2079 if (!in_exec)
2080 return false;
2081
2082 // The automatic quit functionality is triggered by
2083 // both QEventLoopLocker and maybeLastWindowClosed.
2084 // In either case, we don't want to quit if there
2085 // are active QEventLoopLockers, even if quitLockEnabled
2086 // is not enabled, as the property signals whether to
2087 // trigger the automatic quit, not whether to block it.
2088 if (quitLockRef.loadRelaxed())
2089 return false;
2090
2091 return true;
2092}
2093
2094void QCoreApplicationPrivate::quitAutomatically()
2095{
2096 Q_Q(QCoreApplication);
2097
2098 // Explicit requests by the user to quit() is plumbed via the platform
2099 // if possible, and delivers the quit event synchronously. For automatic
2100 // quits we implicitly support cancelling the quit by showing another
2101 // window, which currently relies on removing any posted quit events
2102 // from the event queue. As a result, we can't use the normal quit()
2103 // code path, and need to post manually.
2104 QCoreApplication::postEvent(q, new QEvent(QEvent::Quit));
2105}
2106
2107/*!
2108 \threadsafe
2109
2110 Asks the application to quit.
2111
2112 The request may be ignored if the application prevents the quit,
2113 for example if one of its windows can't be closed. The application
2114 can affect this by handling the QEvent::Quit event on the application
2115 level, or QEvent::Close events for the individual windows.
2116
2117 If the quit is not interrupted the application will exit with return
2118 code 0 (success).
2119
2120 To exit the application without a chance of being interrupted, call
2121 exit() directly. Note that method is not thread-safe.
2122
2123 It's good practice to always connect signals to this slot using a
2124 \l{Qt::}{QueuedConnection}. If a signal connected (non-queued) to this slot
2125 is emitted before control enters the main event loop (such as before
2126 "int main" calls \l{QCoreApplication::}{exec()}), the slot has no effect
2127 and the application never exits. Using a queued connection ensures that the
2128 slot will not be invoked until after control enters the main event loop.
2129
2130 Example:
2131
2132 \snippet code/src_corelib_kernel_qcoreapplication.cpp 1
2133
2134 \b{Thread-safety note}: this function may be called from any thread to
2135 thread-safely cause the currently-running main application loop to exit.
2136 However, thread-safety is not guaranteed if the QCoreApplication object is
2137 being destroyed at the same time.
2138
2139 \sa exit(), aboutToQuit()
2140*/
2141void QCoreApplication::quit()
2142{
2143 if (!self)
2144 return;
2145
2146 if (!self->d_func()->in_exec)
2147 return;
2148
2149 if (QThread::isMainThread() && self->d_func()->handlingQuitEvent)
2150 return;
2151
2152 self->d_func()->quit();
2153}
2154
2155void QCoreApplicationPrivate::quit()
2156{
2157 Q_Q(QCoreApplication);
2158
2159 if (QThread::isMainThread()) {
2160 QEvent quitEvent(QEvent::Quit);
2161 QCoreApplication::sendEvent(q, &quitEvent);
2162 } else {
2163 QCoreApplication::postEvent(q, new QEvent(QEvent::Quit));
2164 }
2165}
2166
2167/*!
2168 \internal
2169
2170 Handles a QEvent::Quit sent to the application.
2171
2172 Subclasses can override this to perform additional work, such
2173 as closing windows, before calling the base implementation,
2174 which exits the event loop.
2175
2176 Returns \c true if the quit was accepted, or \c false to
2177 reject it, in which case the event will be ignored.
2178*/
2179bool QCoreApplicationPrivate::handleQuitEvent()
2180{
2181 QCoreApplication::exit(0);
2182 return true;
2183}
2184
2185/*!
2186 \fn void QCoreApplication::aboutToQuit()
2187
2188 This signal is emitted when the application is about to quit the
2189 main event loop, e.g. when the event loop level drops to zero.
2190 This may happen either after a call to quit() from inside the
2191 application or when the user shuts down the entire desktop session.
2192
2193 The signal is particularly useful if your application has to do some
2194 last-second cleanup. Note that no user interaction is possible in
2195 this state.
2196
2197 \note At this point the main event loop is still running, but will
2198 not process further events on return except QEvent::DeferredDelete
2199 events for objects deleted via deleteLater(). If event processing is
2200 needed, use a nested event loop or call QCoreApplication::processEvents()
2201 manually.
2202
2203 \sa quit()
2204*/
2205
2206#endif // QT_NO_QOBJECT
2207
2208#ifndef QT_NO_TRANSLATION
2209/*!
2210 Adds the translation file \a translationFile to the list of
2211 translation files to be used for translations.
2212
2213 Multiple translation files can be installed. Translations are
2214 searched for in the reverse order in which they were installed,
2215 so the most recently installed translation file is searched first
2216 and the first translation file installed is searched last.
2217 The search stops as soon as a translation containing a matching
2218 string is found.
2219
2220 Installing or removing a QTranslator, or changing an installed QTranslator
2221 generates a \l{QEvent::LanguageChange}{LanguageChange} event for the
2222 QCoreApplication instance. A QApplication instance will propagate the event
2223 to all toplevel widgets, where a reimplementation of changeEvent can
2224 re-translate the user interface by passing user-visible strings via the
2225 tr() function to the respective property setters. User-interface classes
2226 generated by \QD provide a \c retranslateUi() function that can be
2227 called.
2228
2229 The function returns \c true on success and \c false on failure.
2230
2231 \note QCoreApplication does \e not take ownership of \a translationFile.
2232 It is the responsibility of the application to ensure that, if the
2233 function returned \c true, the \a translationFile object is alive until
2234 either \l removeTranslator() is called for it, or the application exits.
2235
2236 \sa removeTranslator(), translate(), QTranslator::load(),
2237 {Writing Source Code for Translation#Prepare for Dynamic Language Changes}{Prepare for Dynamic Language Changes}
2238*/
2239
2240bool QCoreApplication::installTranslator(QTranslator *translationFile)
2241{
2242 if (!translationFile)
2243 return false;
2244
2245 if (!QCoreApplicationPrivate::checkInstance("installTranslator"))
2246 return false;
2247
2248 QCoreApplicationPrivate *d = self->d_func();
2249 {
2250 QWriteLocker locker(&d->translateMutex);
2251 d->translators.prepend(translationFile);
2252 }
2253
2254 if (translationFile->isEmpty())
2255 return true;
2256
2257#ifndef QT_NO_QOBJECT
2258 QEvent ev(QEvent::LanguageChange);
2259 QCoreApplication::sendEvent(self, &ev);
2260#endif
2261
2262 return true;
2263}
2264
2265/*!
2266 Removes the translation file \a translationFile from the list of
2267 translation files used by this application. (It does not delete the
2268 translation file from the file system.)
2269
2270 The function returns \c true on success and false on failure.
2271
2272 \sa installTranslator(), translate(), QObject::tr()
2273*/
2274
2275bool QCoreApplication::removeTranslator(QTranslator *translationFile)
2276{
2277 if (!translationFile)
2278 return false;
2279 if (!QCoreApplicationPrivate::checkInstance("removeTranslator"))
2280 return false;
2281 QCoreApplicationPrivate *d = self->d_func();
2282 QWriteLocker locker(&d->translateMutex);
2283 if (d->translators.removeAll(translationFile)) {
2284#ifndef QT_NO_QOBJECT
2285 locker.unlock();
2286 if (!self->closingDown()) {
2287 QEvent ev(QEvent::LanguageChange);
2288 QCoreApplication::sendEvent(self, &ev);
2289 }
2290#endif
2291 return true;
2292 }
2293 return false;
2294}
2295
2296static void replacePercentN(QString *result, int n)
2297{
2298 if (n >= 0) {
2299 qsizetype percentPos = 0;
2300 qsizetype len = 0;
2301 while ((percentPos = result->indexOf(u'%', percentPos + len)) != -1) {
2302 len = 1;
2303 if (percentPos + len == result->size())
2304 break;
2305 QString fmt;
2306 if (result->at(percentPos + len) == u'L') {
2307 ++len;
2308 if (percentPos + len == result->size())
2309 break;
2310 fmt = "%L1"_L1;
2311 } else {
2312 fmt = "%1"_L1;
2313 }
2314 if (result->at(percentPos + len) == u'n') {
2315 fmt = fmt.arg(n);
2316 ++len;
2317 result->replace(percentPos, len, fmt);
2318 len = fmt.size();
2319 }
2320 }
2321 }
2322}
2323
2324/*!
2325 \threadsafe
2326
2327 Returns the translation text for \a sourceText, by querying the
2328 installed translation files. The translation files are searched
2329 from the most recently installed file back to the first
2330 installed file.
2331
2332 QObject::tr() provides this functionality more conveniently.
2333
2334 \a context is typically a class name (e.g., "MyDialog") and \a
2335 sourceText is either English text or a short identifying text.
2336
2337 \a disambiguation is an identifying string, for when the same \a
2338 sourceText is used in different roles within the same context. By
2339 default, it is \nullptr.
2340
2341 See the \l QTranslator and \l QObject::tr() documentation for
2342 more information about contexts, disambiguations and comments.
2343
2344 \a n is used in conjunction with \c %n to support plural forms.
2345 See QObject::tr() for details.
2346
2347 If none of the translation files contain a translation for \a
2348 sourceText in \a context, this function returns a QString
2349 equivalent of \a sourceText.
2350
2351 This function is not virtual. You can use alternative translation
2352 techniques by subclassing \l QTranslator.
2353
2354 \sa QObject::tr(), installTranslator(), removeTranslator(),
2355 {Internationalization and Translations}
2356*/
2357QString QCoreApplication::translate(const char *context, const char *sourceText,
2358 const char *disambiguation, int n)
2359{
2360 QString result;
2361
2362 if (!sourceText)
2363 return result;
2364
2365 if (self) {
2366 QCoreApplicationPrivate *d = self->d_func();
2367 QReadLocker locker(&d->translateMutex);
2368 if (!d->translators.isEmpty()) {
2369 QList<QTranslator*>::ConstIterator it;
2370 QTranslator *translationFile;
2371 for (it = d->translators.constBegin(); it != d->translators.constEnd(); ++it) {
2372 translationFile = *it;
2373 result = translationFile->translate(context, sourceText, disambiguation, n);
2374 if (!result.isNull())
2375 break;
2376 }
2377 }
2378 }
2379
2380 if (result.isNull())
2381 result = QString::fromUtf8(sourceText);
2382
2383 replacePercentN(&result, n);
2384 return result;
2385}
2386
2387// Declared in qglobal.h
2388QString qtTrId(const char *id, int n)
2389{
2390 return QCoreApplication::translate(nullptr, id, nullptr, n);
2391}
2392
2393bool QCoreApplicationPrivate::isTranslatorInstalled(QTranslator *translator)
2394{
2395 if (!QCoreApplication::self)
2396 return false;
2397 QCoreApplicationPrivate *d = QCoreApplication::self->d_func();
2398 QReadLocker locker(&d->translateMutex);
2399 return d->translators.contains(translator);
2400}
2401
2402#else
2403
2404QString QCoreApplication::translate(const char *context, const char *sourceText,
2405 const char *disambiguation, int n)
2406{
2407 Q_UNUSED(context);
2408 Q_UNUSED(disambiguation);
2409 QString ret = QString::fromUtf8(sourceText);
2410 if (n >= 0)
2411 ret.replace("%n"_L1, QString::number(n));
2412 return ret;
2413}
2414
2415#endif //QT_NO_TRANSLATION
2416
2417#ifndef QT_BOOTSTRAPPED
2418/*!
2419 Returns the directory that contains the application executable.
2420
2421 For example, if you have installed Qt in the \c{C:\Qt}
2422 directory, and you run the \c{regexp} example, this function will
2423 return "C:/Qt/examples/tools/regexp".
2424
2425 On \macos and iOS this will point to the directory actually containing
2426 the executable, which may be inside an application bundle (if the
2427 application is bundled).
2428
2429 On Android this will point to the directory actually containing the
2430 executable, which may be inside the application APK (if it was built
2431 with uncompressed libraries support).
2432
2433 \warning On Linux, this function will try to get the path from the
2434 \c {/proc} file system. If that fails, it assumes that \c
2435 {argv[0]} contains the absolute file name of the executable. The
2436 function also assumes that the current directory has not been
2437 changed by the application.
2438
2439 \sa applicationFilePath()
2440*/
2441QString QCoreApplication::applicationDirPath()
2442{
2443 if (!self) {
2444 qWarning("QCoreApplication::applicationDirPath: Please instantiate the QApplication object first");
2445 return QString();
2446 }
2447
2448 QFileSystemEntry appFilePath(applicationFilePath(), QFileSystemEntry::FromInternalPath{});
2449 return appFilePath.isEmpty() ? QString() : appFilePath.path();
2450}
2451
2452#if !defined(Q_OS_WIN) && !defined(Q_OS_DARWIN)
2453// qcoreapplication_win.cpp or qcoreapplication_mac.cpp for those
2454static QString qAppFileName()
2455{
2456# if defined(Q_OS_ANDROID) || defined(Q_OS_HARMONY)
2457 // the actual process on Android is the Java VM, so this doesn't help us
2458 return QString();
2459# elif defined(Q_OS_LINUX)
2460 // this includes the Embedded Android builds
2461 return QFile::decodeName(qt_readlink("/proc/self/exe"));
2462# elif defined(AT_EXECPATH)
2463 // seen on FreeBSD, but I suppose the other BSDs could adopt this API
2464 char execfn[PATH_MAX];
2465 if (elf_aux_info(AT_EXECPATH, execfn, sizeof(execfn)) != 0)
2466 execfn[0] = '\0';
2467
2468 qsizetype len = qstrlen(execfn);
2469 return QFile::decodeName(QByteArray::fromRawData(execfn, len));
2470# else
2471 // other OS or something
2472 return QString();
2473# endif
2474}
2475#endif // !Q_OS_WIN && !Q_OS_DARWIN
2476
2477/*!
2478 Returns the file path of the application executable.
2479
2480 For example, if you have installed Qt in the \c{/usr/local/qt}
2481 directory, and you run the \c{regexp} example, this function will
2482 return "/usr/local/qt/examples/tools/regexp/regexp".
2483
2484 \warning On Linux, this function will try to get the path from the
2485 \c {/proc} file system. If that fails, it assumes that \c
2486 {argv[0]} contains the absolute file name of the executable. The
2487 function also assumes that the current directory has not been
2488 changed by the application.
2489
2490 \sa applicationDirPath()
2491*/
2492QString QCoreApplication::applicationFilePath()
2493{
2494 if (!self) {
2495 qWarning("QCoreApplication::applicationFilePath: Please instantiate the QApplication object first");
2496 return QString();
2497 }
2498
2499 QCoreApplicationPrivate *d = self->d_func();
2500
2501 if (d->argc) {
2502 static QByteArray procName = QByteArray(d->argv[0]);
2503 if (procName != QByteArrayView(d->argv[0])) {
2504 // clear the cache if the procname changes, so we reprocess it.
2505 d->cachedApplicationFilePath = QString();
2506 procName.assign(d->argv[0]);
2507 }
2508 }
2509
2510 if (!d->cachedApplicationFilePath.isNull())
2511 return d->cachedApplicationFilePath;
2512
2513 QString absPath = qAppFileName();
2514 if (Q_LIKELY(!absPath.isEmpty())) { // Darwin, FreeBSD, Linux, Windows
2515 // the OS has canonicalized for us
2516 return d->cachedApplicationFilePath = std::move(absPath);
2517 }
2518
2519 if (const QStringList args = arguments(); !args.isEmpty()) {
2520 const QString &argv0 = args[0];
2521
2522 if (!argv0.isEmpty() && argv0.at(0) == u'/') {
2523 /*
2524 If argv0 starts with a slash, it is already an absolute
2525 file path.
2526 */
2527 absPath = argv0;
2528 } else if (argv0.contains(u'/')) {
2529 /*
2530 If argv0 contains one or more slashes, it is a file path
2531 relative to the current directory.
2532 */
2533 absPath = QDir::current().absoluteFilePath(argv0);
2534 } else {
2535 /*
2536 Otherwise, the file path has to be determined using the
2537 PATH environment variable.
2538 */
2539 absPath = QStandardPaths::findExecutable(argv0);
2540 }
2541 }
2542
2543 absPath = QFileInfo(absPath).canonicalFilePath();
2544 if (!absPath.isEmpty()) {
2545 return d->cachedApplicationFilePath = std::move(absPath);
2546 }
2547 return QString();
2548}
2549#endif // !QT_BOOTSTRAPPED
2550
2551/*!
2552 \since 4.4
2553
2554 Returns the current process ID for the application.
2555*/
2556qint64 QCoreApplication::applicationPid() noexcept
2557{
2558#if defined(Q_OS_WIN)
2559 return GetCurrentProcessId();
2560#elif defined(Q_OS_VXWORKS)
2561 return (pid_t) taskIdCurrent;
2562#else
2563 return getpid();
2564#endif
2565}
2566
2567#ifdef Q_OS_WIN
2568static QStringList winCmdArgs()
2569{
2570 // On Windows, it is possible to pass Unicode arguments on
2571 // the command line, but we don't implement any of the wide
2572 // entry-points (wmain/wWinMain), so get the arguments from
2573 // the Windows API instead of using argv. Note that we only
2574 // do this when argv were not modified by the user in main().
2575 QStringList result;
2576 int size;
2577 if (wchar_t **argv = CommandLineToArgvW(GetCommandLine(), &size)) {
2578 result.reserve(size);
2579 wchar_t **argvEnd = argv + size;
2580 for (wchar_t **a = argv; a < argvEnd; ++a)
2581 result.append(QString::fromWCharArray(*a));
2582 LocalFree(argv);
2583 }
2584 return result;
2585}
2586#endif // Q_OS_WIN
2587
2588/*!
2589 \since 4.1
2590
2591 Returns the list of command-line arguments.
2592
2593 Usually arguments().at(0) is the program name, arguments().at(1)
2594 is the first argument, and arguments().last() is the last
2595 argument. See the note below about Windows.
2596
2597 Calling this function is slow - you should store the result in a variable
2598 when parsing the command line.
2599
2600 \warning On Unix, this list is built from the argc and argv parameters passed
2601 to the constructor in the main() function. The string-data in argv is
2602 interpreted using QString::fromLocal8Bit(); hence it is not possible to
2603 pass, for example, Japanese command line arguments on a system that runs in a
2604 Latin1 locale. Most modern Unix systems do not have this limitation, as they are
2605 Unicode-based.
2606
2607 On Windows, the list is built from the argc and argv parameters only if
2608 modified argv/argc parameters are passed to the constructor. In that case,
2609 encoding problems might occur.
2610
2611 Otherwise, the arguments() are constructed from the return value of
2612 \l{https://docs.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getcommandlinea}{GetCommandLine()}.
2613 As a result of this, the string given by arguments().at(0)
2614 might not be the exact program used to start the application
2615 on Windows.
2616
2617 \sa applicationFilePath(), QCommandLineParser
2618*/
2619
2620QStringList QCoreApplication::arguments()
2621{
2622 QStringList list;
2623
2624 if (!self) {
2625 qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first");
2626 return list;
2627 }
2628
2629 const QCoreApplicationPrivate *d = self->d_func();
2630
2631 const int argc = d->argc;
2632 char ** const argv = d->argv;
2633 list.reserve(argc);
2634
2635#if defined(Q_OS_WIN)
2636 const bool argsModifiedByUser = d->origArgv == nullptr;
2637 if (!argsModifiedByUser) {
2638 QStringList commandLineArguments = winCmdArgs();
2639
2640 // Even if the user didn't modify argv before passing them
2641 // on to QCoreApplication, derived QApplications might have.
2642 // If that's the case argc will differ from origArgc.
2643 if (argc != d->origArgc) {
2644 // Note: On MingGW the arguments from GetCommandLine are
2645 // not wildcard expanded (if wildcard expansion is enabled),
2646 // as opposed to the arguments in argv. This means we can't
2647 // compare commandLineArguments to argv/origArgc, but
2648 // must remove elements by value, based on whether they
2649 // were filtered out from argc.
2650 for (int i = 0; i < d->origArgc; ++i) {
2651 if (!contains(argc, argv, d->origArgv[i]))
2652 commandLineArguments.removeAll(QString::fromLocal8Bit(d->origArgv[i]));
2653 }
2654 }
2655
2656 return commandLineArguments;
2657 } // Fall back to rebuilding from argv/argc when a modified argv was passed.
2658#endif // defined(Q_OS_WIN)
2659
2660 for (int a = 0; a < argc; ++a)
2661 list << QString::fromLocal8Bit(argv[a]);
2662
2663 return list;
2664}
2665
2666/*!
2667 \property QCoreApplication::organizationName
2668 \brief the name of the organization that wrote this application
2669
2670 The value is used by the QSettings class when it is constructed
2671 using the default constructor. This saves having to repeat this
2672 information each time a QSettings object is created.
2673
2674 On Mac, QSettings uses \l {QCoreApplication::}{organizationDomain()} as the organization
2675 if it's not an empty string; otherwise it uses
2676 organizationName(). On all other platforms, QSettings uses
2677 organizationName() as the organization.
2678
2679 \sa organizationDomain, applicationName
2680*/
2681
2682/*!
2683 \fn void QCoreApplication::organizationNameChanged()
2684 \internal
2685
2686 While not useful from C++ due to how organizationName is normally set once on
2687 startup, this is still needed for QML so that bindings are reevaluated after
2688 that initial change.
2689*/
2690void QCoreApplication::setOrganizationName(const QString &orgName)
2691{
2692 if (coreappdata()->orgName == orgName)
2693 return;
2694 coreappdata()->orgName = orgName;
2695#ifndef QT_NO_QOBJECT
2696 if (QCoreApplication::self)
2697 emit QCoreApplication::self->organizationNameChanged();
2698#endif
2699}
2700
2701QString QCoreApplication::organizationName()
2702{
2703 return coreappdata()->orgName;
2704}
2705
2706/*!
2707 \property QCoreApplication::organizationDomain
2708 \brief the Internet domain of the organization that wrote this application
2709
2710 The value is used by the QSettings class when it is constructed
2711 using the default constructor. This saves having to repeat this
2712 information each time a QSettings object is created.
2713
2714 On Mac, QSettings uses organizationDomain() as the organization
2715 if it's not an empty string; otherwise it uses organizationName().
2716 On all other platforms, QSettings uses organizationName() as the
2717 organization.
2718
2719 \sa organizationName, applicationName, applicationVersion
2720*/
2721/*!
2722 \fn void QCoreApplication::organizationDomainChanged()
2723 \internal
2724
2725 Primarily for QML, see organizationNameChanged.
2726*/
2727void QCoreApplication::setOrganizationDomain(const QString &orgDomain)
2728{
2729 if (coreappdata()->orgDomain == orgDomain)
2730 return;
2731 coreappdata()->orgDomain = orgDomain;
2732#ifndef QT_NO_QOBJECT
2733 if (QCoreApplication::self)
2734 emit QCoreApplication::self->organizationDomainChanged();
2735#endif
2736}
2737
2738QString QCoreApplication::organizationDomain()
2739{
2740 return coreappdata()->orgDomain;
2741}
2742
2743/*!
2744 \property QCoreApplication::applicationName
2745 \brief the name of this application
2746
2747 The application name is used in various Qt classes and modules,
2748 most prominently in \l{QSettings} when it is constructed using the default constructor.
2749 Other uses are in formatted logging output (see \l{qSetMessagePattern()}),
2750 in output by \l{QCommandLineParser}, in \l{QTemporaryDir} and \l{QTemporaryFile}
2751 default paths, and in some file locations of \l{QStandardPaths}.
2752 \l{Qt D-Bus}, \l{Accessibility}, and the XCB platform integration make use
2753 of the application name, too.
2754
2755 If not set, the application name defaults to the executable name.
2756
2757 \sa organizationName, organizationDomain, applicationVersion, applicationFilePath()
2758*/
2759/*!
2760 \fn void QCoreApplication::applicationNameChanged()
2761 \internal
2762
2763 Primarily for QML, see organizationNameChanged.
2764*/
2765void QCoreApplication::setApplicationName(const QString &application)
2766{
2767 coreappdata()->applicationNameSet = !application.isEmpty();
2768 QString newAppName = application;
2769 if (newAppName.isEmpty() && QCoreApplication::self)
2770 newAppName = QCoreApplication::self->d_func()->appName();
2771 if (coreappdata()->application == newAppName)
2772 return;
2773 coreappdata()->application = newAppName;
2774#ifndef QT_NO_QOBJECT
2775 if (QCoreApplication::self)
2776 emit QCoreApplication::self->applicationNameChanged();
2777#endif
2778}
2779
2780QString QCoreApplication::applicationName()
2781{
2782 return coreappdata() ? coreappdata()->application : QString();
2783}
2784
2785/*!
2786 \property QCoreApplication::applicationVersion
2787 \since 4.4
2788 \brief the version of this application
2789
2790 If not set, the application version defaults to a platform-specific value
2791 determined from the main application executable or package (since Qt 5.9):
2792
2793 \table
2794 \header
2795 \li Platform
2796 \li Source
2797 \row
2798 \li Windows (classic desktop)
2799 \li PRODUCTVERSION parameter of the VERSIONINFO resource
2800 \row
2801 \li macOS, iOS, tvOS, watchOS
2802 \li CFBundleVersion property of the information property list
2803 \row
2804 \li Android
2805 \li android:versionName property of the AndroidManifest.xml manifest element
2806 \row
2807 \li HarmonyOS
2808 \li versionName field of the app.json5 configuration file
2809 \endtable
2810
2811 On other platforms, the default is the empty string.
2812
2813 \sa applicationName, organizationName, organizationDomain
2814*/
2815/*!
2816 \fn void QCoreApplication::applicationVersionChanged()
2817 \internal
2818
2819 Primarily for QML, see organizationNameChanged.
2820*/
2821void QCoreApplication::setApplicationVersion(const QString &version)
2822{
2823 coreappdata()->applicationVersionSet = !version.isEmpty();
2824 QString newVersion = version;
2825 if (newVersion.isEmpty() && QCoreApplication::self)
2826 newVersion = QCoreApplication::self->d_func()->appVersion();
2827 if (coreappdata()->applicationVersion == newVersion)
2828 return;
2829 coreappdata()->applicationVersion = newVersion;
2830#ifndef QT_NO_QOBJECT
2831 if (QCoreApplication::self)
2832 emit QCoreApplication::self->applicationVersionChanged();
2833#endif
2834}
2835
2836QString QCoreApplication::applicationVersion()
2837{
2838 return coreappdata() ? coreappdata()->applicationVersion : QString();
2839}
2840
2841#if QT_CONFIG(permissions) || defined(Q_QDOC)
2842
2843/*!
2844 Checks the status of the given \a permission
2845
2846 If the result is Qt::PermissionStatus::Undetermined then permission should be
2847 requested via requestPermission() to determine the user's intent.
2848
2849 \since 6.5
2850 \sa requestPermission(), {Application Permissions}
2851*/
2852Qt::PermissionStatus QCoreApplication::checkPermission(const QPermission &permission)
2853{
2854 return QPermissions::Private::checkPermission(permission);
2855}
2856
2857/*!
2858 \fn template <typename Functor> void QCoreApplication::requestPermission(
2859 const QPermission &permission, Functor &&functor)
2860
2861 Requests the given \a permission.
2862
2863 \include permissions.qdocinc requestPermission-functor
2864
2865 The \a functor can be a free-standing or static member function:
2866
2867 \code
2868 qApp->requestPermission(QCameraPermission{}, &permissionUpdated);
2869 \endcode
2870
2871 or a lambda:
2872
2873 \code
2874 qApp->requestPermission(QCameraPermission{}, [](const QPermission &permission) {
2875 });
2876 \endcode
2877
2878 \include permissions.qdocinc requestPermission-postamble
2879
2880 \since 6.5
2881 \sa checkPermission(), {Application Permissions}
2882*/
2883
2884/*!
2885 \fn template<typename Functor> void QCoreApplication::requestPermission(
2886 const QPermission &permission, const QObject *context,
2887 Functor functor)
2888
2889 Requests the given \a permission, in the context of \a context.
2890
2891 \include permissions.qdocinc requestPermission-functor
2892
2893 The \a functor can be a free-standing or static member function:
2894
2895 \code
2896 qApp->requestPermission(QCameraPermission{}, context, &permissionUpdated);
2897 \endcode
2898
2899 a lambda:
2900
2901 \code
2902 qApp->requestPermission(QCameraPermission{}, context, [](const QPermission &permission) {
2903 });
2904 \endcode
2905
2906 or a slot in the \a context object:
2907
2908 \code
2909 qApp->requestPermission(QCameraPermission{}, this, &CamerWidget::permissionUpdated);
2910 \endcode
2911
2912 The \a functor will be called in the thread of the \a context object. If
2913 \a context is destroyed before the request completes, the \a functor will
2914 not be called.
2915
2916 \include permissions.qdocinc requestPermission-postamble
2917
2918 \since 6.5
2919 \overload
2920 \sa checkPermission(), {Application Permissions}
2921*/
2922
2923/*!
2924 \internal
2925
2926 Called by the various requestPermission overloads to perform the request.
2927
2928 Calls the functor encapsulated in the \a slotObjRaw in the given \a context
2929 (which may be \c nullptr).
2930*/
2931void QCoreApplication::requestPermissionImpl(const QPermission &requestedPermission,
2932 QtPrivate::QSlotObjectBase *slotObjRaw, const QObject *context)
2933{
2934 QtPrivate::SlotObjUniquePtr slotObj{slotObjRaw}; // adopts
2935 Q_ASSERT(slotObj);
2936
2937 if (!QThread::isMainThread()) {
2938 qCWarning(lcPermissions, "Permissions can only be requested from the GUI (main) thread");
2939 return;
2940 }
2941
2942 class PermissionReceiver : public QObject
2943 {
2944 public:
2945 explicit PermissionReceiver(QtPrivate::SlotObjUniquePtr &&slotObject, const QObject *context)
2946 : slotObject(std::move(slotObject)), context(context ? context : this)
2947 {
2948 Q_ASSERT(this->context);
2949 moveToThread(this->context->thread());
2950 }
2951
2952 void finalizePermissionRequest(const QPermission &permission)
2953 {
2954 Q_ASSERT(slotObject);
2955 // only execute if context object is still alive
2956 if (context) {
2957 void *args[] = { nullptr, const_cast<QPermission *>(&permission) };
2958 slotObject->call(const_cast<QObject *>(context.data()), args);
2959 }
2960 }
2961
2962 private:
2963 QtPrivate::SlotObjUniquePtr slotObject;
2964 QPointer<const QObject> context;
2965 };
2966
2967 // ### use unique_ptr once PermissionCallback is a move_only function
2968 auto receiver = std::make_shared<PermissionReceiver>(std::move(slotObj), context);
2969
2970 QPermissions::Private::requestPermission(requestedPermission,
2971 [=, receiver = std::move(receiver)](Qt::PermissionStatus status) mutable {
2972 if (status == Qt::PermissionStatus::Undetermined) {
2973 Q_ASSERT_X(false, "QPermission",
2974 "Internal error: requestPermission() should never return Undetermined");
2975 status = Qt::PermissionStatus::Denied;
2976 }
2977
2978 if (QCoreApplication::self) {
2979 QPermission permission = requestedPermission;
2980 permission.m_status = status;
2981 auto receiverObject = receiver.get();
2982 QMetaObject::invokeMethod(receiverObject,
2983 [receiver = std::move(receiver), permission] {
2984 receiver->finalizePermissionRequest(permission);
2985 }, Qt::QueuedConnection);
2986 }
2987 });
2988}
2989
2990#endif // QT_CONFIG(permissions)
2991
2992#if QT_CONFIG(library)
2993static QStringList libraryPathsLocked();
2994
2995/*!
2996 Returns a list of paths that the application will search when
2997 dynamically loading libraries.
2998
2999 The return value of this function may change when a QCoreApplication
3000 is created. It is not recommended to call it before creating a
3001 QCoreApplication. The directory of the application executable (\b not
3002 the working directory) is part of the list if it is known. In order
3003 to make it known a QCoreApplication has to be constructed as it will
3004 use \c {argv[0]} to find it.
3005
3006 Qt provides default library paths, but they can also be set using
3007 a \l{Using qt.conf}{qt.conf} file. Paths specified in this file
3008 will override default values. Note that if the qt.conf file is in
3009 the directory of the application executable, it may not be found
3010 until a QCoreApplication is created. If it is not found when calling
3011 this function, the default library paths will be used.
3012
3013 The list will include the installation directories for plugins if
3014 they exist (the default installation directory for plugins is \c
3015 INSTALL/plugins, where \c INSTALL is the directory where Qt was
3016 installed). The colon separated entries of the \c QT_PLUGIN_PATH
3017 environment variable are always added. The plugin installation
3018 directory (and its existence) may change when the directory of
3019 the application executable becomes known.
3020
3021 \warning This function does not currently include QLibraryInfo::LibrariesPath
3022 in its default paths, and QLibrary does not currently use this function to look
3023 up non-absolute library paths.
3024
3025 \sa setLibraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary,
3026 {How to Create Qt Plugins}
3027*/
3028QStringList QCoreApplication::libraryPaths()
3029{
3030 QMutexLocker locker(&coreappdata->libraryPathMutex);
3031 return libraryPathsLocked();
3032}
3033
3034/*!
3035 \internal
3036*/
3037static QStringList libraryPathsLocked()
3038{
3039 QCoreApplicationData *d = coreappdata;
3040 if (d->libPathsManuallySet())
3041 return d->manual_libpaths;
3042
3043 QStringList *app_libpaths = &d->app_libpaths;
3044 if (!d->libPathsInitialized()) {
3045
3046 auto setPathsFromEnv = [&](QString libPathEnv) {
3047 if (!libPathEnv.isEmpty()) {
3048 QStringList paths = libPathEnv.split(QDir::listSeparator(), Qt::SkipEmptyParts);
3049 for (QStringList::const_iterator it = paths.constBegin(); it != paths.constEnd(); ++it) {
3050 QString canonicalPath = QDir(*it).canonicalPath();
3051 if (!canonicalPath.isEmpty()
3052 && !app_libpaths->contains(canonicalPath)) {
3053 app_libpaths->append(canonicalPath);
3054 }
3055 }
3056 }
3057 };
3058 setPathsFromEnv(qEnvironmentVariable("QT_PLUGIN_PATH"));
3059
3060 const auto pluginPaths = QLibraryInfo::paths(QLibraryInfo::PluginsPath);
3061 for (auto path : pluginPaths) {
3062 if (QFile::exists(path)) {
3063 // Make sure we convert from backslashes to slashes.
3064 path = QDir(path).canonicalPath();
3065 if (!app_libpaths->contains(path))
3066 app_libpaths->append(path);
3067 }
3068 }
3069
3070 // If QCoreApplication is not yet instantiated,
3071 // make sure we add the application path when we construct the QCoreApplication
3072 if (qApp) {
3073 QString app_location = QCoreApplication::applicationFilePath();
3074 app_location.truncate(app_location.lastIndexOf(u'/'));
3075 app_location = QDir(app_location).canonicalPath();
3076 if (QFile::exists(app_location) && !app_libpaths->contains(app_location))
3077 app_libpaths->append(app_location);
3078 }
3079 if (app_libpaths->isEmpty())
3080 app_libpaths->reserve(1); // detach from null
3081 Q_ASSERT(d->libPathsInitialized());
3082 }
3083 return *app_libpaths;
3084}
3085
3086
3087
3088/*!
3089
3090 Sets the list of directories to search when loading plugins with
3091 QLibrary to \a paths. All existing paths will be deleted and the
3092 path list will consist of the paths given in \a paths and the path
3093 to the application.
3094
3095 The library paths are reset to the default when an instance of
3096 QCoreApplication is destructed.
3097
3098 \warning QLibrary does not currently use the given paths to look
3099 up non-absolute library paths.
3100
3101 \sa libraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary
3102 */
3103void QCoreApplication::setLibraryPaths(const QStringList &paths)
3104{
3105 QCoreApplicationData *d = coreappdata;
3106 QMutexLocker locker(&d->libraryPathMutex);
3107
3108 // setLibraryPaths() is considered a "remove everything and then add some new ones" operation.
3109 // When the application is constructed it should still amend the paths. So we keep the originals
3110 // around, and even create them if they don't exist, yet.
3111 if (!d->libPathsInitialized())
3112 libraryPathsLocked();
3113
3114 d->manual_libpaths = paths;
3115 if (d->manual_libpaths.isEmpty())
3116 d->manual_libpaths.reserve(1); // detach from null
3117 Q_ASSERT(d->libPathsManuallySet());
3118
3119 locker.unlock();
3120 QFactoryLoader::refreshAll();
3121}
3122
3123/*!
3124 Prepends \a path to the beginning of the library path list, ensuring that
3125 it is searched for libraries first. If \a path is empty or already in the
3126 path list, the path list is not changed.
3127
3128 The default path list consists of one or two entries. The first is the
3129 installation directory for plugins, which is \c INSTALL/plugins, where \c
3130 INSTALL is the directory where Qt was installed. The second is the
3131 application's own directory (\b not the current directory), but only after
3132 the QCoreApplication object is instantiated.
3133
3134 The library paths are reset to the default when an instance of
3135 QCoreApplication is destructed.
3136
3137 \warning QLibrary does not currently use the given path to look
3138 up non-absolute library paths.
3139
3140 \sa removeLibraryPath(), libraryPaths(), setLibraryPaths()
3141 */
3142void QCoreApplication::addLibraryPath(const QString &path)
3143{
3144 if (path.isEmpty())
3145 return;
3146
3147 QString canonicalPath = QDir(path).canonicalPath();
3148 if (canonicalPath.isEmpty())
3149 return;
3150
3151 QCoreApplicationData *d = coreappdata;
3152 QMutexLocker locker(&d->libraryPathMutex);
3153
3154 QStringList *libpaths = &d->manual_libpaths;
3155 if (d->libPathsManuallySet()) {
3156 if (d->manual_libpaths.contains(canonicalPath))
3157 return;
3158 } else {
3159 // make sure that library paths are initialized
3160 libraryPathsLocked();
3161 QStringList *app_libpaths = &d->app_libpaths;
3162 if (app_libpaths->contains(canonicalPath))
3163 return;
3164
3165 *libpaths = *app_libpaths;
3166 }
3167
3168 libpaths->prepend(canonicalPath);
3169 Q_ASSERT(d->libPathsManuallySet());
3170 locker.unlock();
3171 QFactoryLoader::refreshAll();
3172}
3173
3174/*!
3175 Removes \a path from the library path list. If \a path is empty or not
3176 in the path list, the list is not changed.
3177
3178 The library paths are reset to the default when an instance of
3179 QCoreApplication is destructed.
3180
3181 \warning QLibrary does not currently use libraryPaths()
3182 to look up non-absolute library paths.
3183
3184 \sa addLibraryPath(), libraryPaths(), setLibraryPaths()
3185*/
3186void QCoreApplication::removeLibraryPath(const QString &path)
3187{
3188 if (path.isEmpty())
3189 return;
3190
3191 QString canonicalPath = QDir(path).canonicalPath();
3192 if (canonicalPath.isEmpty())
3193 return;
3194
3195 QCoreApplicationData *d = coreappdata;
3196 QMutexLocker locker(&d->libraryPathMutex);
3197
3198 QStringList *libpaths = &d->manual_libpaths;
3199 if (d->libPathsManuallySet()) {
3200 if (libpaths->removeAll(canonicalPath) == 0)
3201 return;
3202 } else {
3203 // make sure that library paths is initialized
3204 libraryPathsLocked();
3205 QStringList *app_libpaths = &d->app_libpaths;
3206 if (!app_libpaths->contains(canonicalPath))
3207 return;
3208
3209 *libpaths = *app_libpaths;
3210 libpaths->removeAll(canonicalPath);
3211 Q_ASSERT(d->libPathsManuallySet());
3212 }
3213
3214 locker.unlock();
3215 QFactoryLoader::refreshAll();
3216}
3217
3218#endif // QT_CONFIG(library)
3219
3220#ifndef QT_NO_QOBJECT
3221
3222/*!
3223 Installs an event filter \a filterObj for all native events
3224 received by the application in the main thread.
3225
3226 The event filter \a filterObj receives events via its \l {QAbstractNativeEventFilter::}{nativeEventFilter()}
3227 function, which is called for all native events received in the main thread.
3228
3229 The QAbstractNativeEventFilter::nativeEventFilter() function should
3230 return true if the event should be filtered, i.e. stopped. It should
3231 return false to allow normal Qt processing to continue: the native
3232 event can then be translated into a QEvent and handled by the standard
3233 Qt \l{QEvent} {event} filtering, e.g. QObject::installEventFilter().
3234
3235 If multiple event filters are installed, the filter that was
3236 installed last is activated first.
3237
3238 \note The filter function set here receives native messages,
3239 i.e. MSG or XCB event structs.
3240
3241 \note Native event filters will be disabled in the application when the
3242 Qt::AA_PluginApplication attribute is set.
3243
3244 For maximum portability, you should always try to use QEvent
3245 and QObject::installEventFilter() whenever possible.
3246
3247 \sa QObject::installEventFilter()
3248
3249 \since 5.0
3250*/
3251void QCoreApplication::installNativeEventFilter(QAbstractNativeEventFilter *filterObj)
3252{
3253 if (QCoreApplication::testAttribute(Qt::AA_PluginApplication)) {
3254 qWarning("Native event filters are not applied when the Qt::AA_PluginApplication attribute is set");
3255 return;
3256 }
3257
3258 QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance(QCoreApplicationPrivate::theMainThread.loadAcquire());
3259 if (!filterObj || !eventDispatcher)
3260 return;
3261 eventDispatcher->installNativeEventFilter(filterObj);
3262}
3263
3264/*!
3265 Removes an event \a filterObject from this object. The
3266 request is ignored if such an event filter has not been installed.
3267
3268 All event filters for this object are automatically removed when
3269 this object is destroyed.
3270
3271 It is always safe to remove an event filter, even during event
3272 filter activation (i.e. from the nativeEventFilter() function).
3273
3274 \sa installNativeEventFilter()
3275 \since 5.0
3276*/
3277void QCoreApplication::removeNativeEventFilter(QAbstractNativeEventFilter *filterObject)
3278{
3279 QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance(QCoreApplicationPrivate::theMainThread.loadAcquire());
3280 if (!filterObject || !eventDispatcher)
3281 return;
3282 eventDispatcher->removeNativeEventFilter(filterObject);
3283}
3284
3285/*!
3286 Returns a pointer to the event dispatcher object for the main thread. If no
3287 event dispatcher exists for the thread, this function returns \nullptr.
3288*/
3289QAbstractEventDispatcher *QCoreApplication::eventDispatcher()
3290{
3291 if (QCoreApplicationPrivate::theMainThread.loadAcquire())
3292 return QCoreApplicationPrivate::theMainThread.loadRelaxed()->eventDispatcher();
3293 return nullptr;
3294}
3295
3296/*!
3297 Sets the event dispatcher for the main thread to \a eventDispatcher. This
3298 is only possible as long as there is no event dispatcher installed yet. That
3299 is, before QCoreApplication has been instantiated. This method takes
3300 ownership of the object.
3301*/
3302void QCoreApplication::setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
3303{
3304 QThread *mainThread = QCoreApplicationPrivate::theMainThread.loadAcquire();
3305 if (!mainThread)
3306 mainThread = QThread::currentThread(); // will also setup theMainThread
3307 mainThread->setEventDispatcher(eventDispatcher);
3308}
3309
3310void QCoreApplicationPrivate::destroyEventDispatcher()
3311{
3312 // This function is called by either ~QCoreApplication or ~QGuiApplication
3313 QThreadData *data = QThreadData::current();
3314 Q_ASSERT(data->eventDispatcher.loadAcquire() == eventDispatcher);
3315
3316 // same sequence as QThread::finish() or cleanup(): first we set the
3317 // global(s) to nullptr, then we emit the signal, then we delete.
3318 QAbstractEventDispatcher *dispatcher = eventDispatcher;
3319 eventDispatcher = nullptr;
3320 data->eventDispatcher.storeRelaxed(nullptr);
3321 if (dispatcher) {
3322 dispatcher->closingDown();
3323 delete dispatcher;
3324 }
3325}
3326#endif // QT_NO_QOBJECT
3327
3328/*!
3329 \macro Q_COREAPP_STARTUP_FUNCTION(QtStartUpFunction ptr)
3330 \since 5.1
3331 \relates QCoreApplication
3332 \reentrant
3333
3334 Adds a global function that will be called from the QCoreApplication
3335 constructor. This macro is normally used to initialize libraries
3336 for program-wide functionality, without requiring the application to
3337 call into the library for initialization.
3338
3339 The function specified by \a ptr should take no arguments and should
3340 return nothing. For example:
3341
3342 \snippet code/src_corelib_kernel_qcoreapplication.cpp 3
3343
3344 Note that the startup function will run at the end of the QCoreApplication constructor,
3345 before any GUI initialization. If GUI code is required in the function,
3346 use a timer (or a queued invocation) to perform the initialization later on,
3347 from the event loop.
3348
3349 If QCoreApplication is deleted and another QCoreApplication is created,
3350 the startup function will be invoked again.
3351
3352 \note This macro is not suitable for use in library code that is then
3353 statically linked into an application since the function may not be called
3354 at all due to being eliminated by the linker.
3355*/
3356
3357/*!
3358 \fn void qAddPostRoutine(QtCleanUpFunction ptr)
3359 \threadsafe
3360 \relates QCoreApplication
3361
3362 Adds a global routine that will be called from the QCoreApplication
3363 destructor. This function is normally used to add cleanup routines
3364 for program-wide functionality.
3365
3366 The cleanup routines are called in the reverse order of their addition.
3367
3368 The function specified by \a ptr should take no arguments and should
3369 return nothing. For example:
3370
3371 \snippet code/src_corelib_kernel_qcoreapplication.cpp 4
3372
3373 Note that for an application- or module-wide cleanup, qAddPostRoutine()
3374 is often not suitable. For example, if the program is split into dynamically
3375 loaded modules, the relevant module may be unloaded long before the
3376 QCoreApplication destructor is called. In such cases, if using qAddPostRoutine()
3377 is still desirable, qRemovePostRoutine() can be used to prevent a routine
3378 from being called by the QCoreApplication destructor. For example, if that
3379 routine was called before the module was unloaded.
3380
3381 For modules and libraries, using a reference-counted
3382 initialization manager or Qt's parent-child deletion mechanism may
3383 be better. Here is an example of a private class that uses the
3384 parent-child mechanism to call a cleanup function at the right
3385 time:
3386
3387 \snippet code/src_corelib_kernel_qcoreapplication.cpp 5
3388
3389 By selecting the right parent object, this can often be made to
3390 clean up the module's data at the right moment.
3391
3392 \note This function has been thread-safe since Qt 5.10.
3393
3394 \sa qRemovePostRoutine()
3395*/
3396
3397/*!
3398 \fn void qRemovePostRoutine(QtCleanUpFunction ptr)
3399 \threadsafe
3400 \relates QCoreApplication
3401 \since 5.3
3402
3403 Removes the cleanup routine specified by \a ptr from the list of
3404 routines called by the QCoreApplication destructor. The routine
3405 must have been previously added to the list by a call to
3406 qAddPostRoutine(), otherwise this function has no effect.
3407
3408 \note This function has been thread-safe since Qt 5.10.
3409
3410 \sa qAddPostRoutine()
3411*/
3412
3413/*!
3414 \macro Q_DECLARE_TR_FUNCTIONS(context)
3415 \relates QCoreApplication
3416
3417 The Q_DECLARE_TR_FUNCTIONS() macro declares and implements the
3418 translation function \c tr() with this signature:
3419
3420 \snippet code/src_corelib_kernel_qcoreapplication.cpp 6
3421
3422 This macro is useful if you want to use QObject::tr() in classes
3423 that don't inherit from QObject.
3424
3425 Q_DECLARE_TR_FUNCTIONS() must appear at the very top of the
3426 class definition (before the first \c{public:} or \c{protected:}).
3427 For example:
3428
3429 \snippet code/src_corelib_kernel_qcoreapplication.cpp 7
3430
3431 The \a context parameter is normally the class name, but it can
3432 be any text.
3433
3434 \sa Q_OBJECT, QObject::tr()
3435*/
3436
3437void *QCoreApplication::resolveInterface(const char *name, int revision) const
3438{
3439#if defined(Q_OS_ANDROID)
3440 // The QAndroidApplication is wrongly using static methods for
3441 // its native interface (QTBUG-128796). Until we fix that we at
3442 // least want the preferred way of resolving a native interface
3443 // to work, so provide a minimal subclass of the interface.
3444 using namespace QNativeInterface;
3445 struct AndroidApplication : public QAndroidApplication {};
3446 static AndroidApplication androidApplication;
3447 QT_NATIVE_INTERFACE_RETURN_IF(QAndroidApplication, &androidApplication);
3448#endif
3449#if defined(Q_OS_HARMONY) && !defined(QT_BOOTSTRAPPED)
3450 using namespace QNativeInterface;
3451 struct HarmonyApplication : public QHarmonyApplication {};
3452 static HarmonyApplication harmonyApplication;
3453 QT_NATIVE_INTERFACE_RETURN_IF(QHarmonyApplication, &harmonyApplication);
3454#endif
3455 Q_UNUSED(name); Q_UNUSED(revision);
3456 return nullptr;
3457}
3458
3459QT_END_NAMESPACE
3460
3461#ifndef QT_NO_QOBJECT
3462#include "moc_qcoreapplication.cpp"
3463#endif
\inmodule QtCore
#define __has_include(x)
QString qAppName()
Q_TRACE_POINT(qtcore, QCoreApplication_notify_exit, bool consumed, bool filtered)
void QT_MANGLE_NAMESPACE qt_startup_hook()
static QString qAppFileName()
QList< QtStartUpFunction > QStartUpFuncList
Q_TRACE_METADATA(qtcore, "ENUM { AUTO, RANGE User ... MaxUser } QEvent::Type;")
QString qtTrId(const char *id, int n)
Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_exit)
static void qt_call_pre_routines()
qsizetype qGlobalPostedEventsCount()
static Q_CONSTINIT bool preRoutinesCalled
QList< QtCleanUpFunction > QVFuncList
static void replacePercentN(QString *result, int n)
Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_event_compressed, QObject *receiver, QEvent *event)
Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_entry, QObject *receiver, QEvent *event, QEvent::Type type)
Q_TRACE_PREFIX(qtcore, "#include <qcoreevent.h>")
Q_CORE_EXPORT void qAddPostRoutine(QtCleanUpFunction)
void(*) QtStartUpFunction()
void(*) QtCleanUpFunction()
Q_CORE_EXPORT void qAddPreRoutine(QtStartUpFunction)
Q_CORE_EXPORT void qRemovePostRoutine(QtCleanUpFunction)
#define qApp
Q_GLOBAL_STATIC(QReadWriteLock, g_updateMutex)