1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qcoreapplication.h"
43 #include "qcoreapplication_p.h"
45 #include "qabstracteventdispatcher.h"
46 #include "qcoreevent.h"
47 #include "qeventloop.h"
48 #include "qcorecmdlineargs_p.h"
49 #include <qdatastream.h>
53 #include <qfileinfo.h>
55 #include <private/qprocess_p.h>
56 #include <qstandardpaths.h>
57 #include <qtextcodec.h>
59 #include <qthreadpool.h>
60 #include <qthreadstorage.h>
61 #include <private/qthread_p.h>
62 #include <qelapsedtimer.h>
63 #include <qlibraryinfo.h>
64 #include <qvarlengtharray.h>
65 #include <private/qfactoryloader_p.h>
66 #include <private/qfunctions_p.h>
67 #include <private/qlocale_p.h>
69 #if defined(Q_OS_UNIX)
70 # if !defined(QT_NO_GLIB)
71 # include "qeventdispatcher_glib_p.h"
73 # include "qeventdispatcher_unix_p.h"
77 # include "qeventdispatcher_win_p.h"
81 # include "qcore_mac_p.h"
99 inline explicit QMutexUnlocker(QMutex *m)
102 inline ~QMutexUnlocker() { unlock(); }
103 inline void unlock() { if (mtx) mtx->unlock(); mtx = 0; }
106 Q_DISABLE_COPY(QMutexUnlocker)
111 #if defined(Q_OS_WIN) || defined(Q_OS_MAC)
112 extern QString qAppFileName();
115 #if QT_VERSION >= 0x060000
116 # error "Bump QCoreApplicatoinPrivate::app_compile_version to 0x060000"
118 int QCoreApplicationPrivate::app_compile_version = 0x050000; //we don't know exactly, but it's at least 5.0.0
120 #if !defined(Q_OS_WIN)
122 QString QCoreApplicationPrivate::macMenuBarName()
125 CFTypeRef string = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("CFBundleName"));
127 bundleName = QCFString::toQString(static_cast<CFStringRef>(string));
131 QString QCoreApplicationPrivate::appName() const
133 static QString applName;
135 applName = macMenuBarName();
137 if (applName.isEmpty() && argv[0]) {
138 char *p = strrchr(argv[0], '/');
139 applName = QString::fromLocal8Bit(p ? p + 1 : argv[0]);
145 bool QCoreApplicationPrivate::checkInstance(const char *function)
147 bool b = (QCoreApplication::self != 0);
149 qWarning("QApplication::%s: Please instantiate the QApplication object first", function);
153 void QCoreApplicationPrivate::processCommandLineArguments()
155 int j = argc ? 1 : 0;
156 for (int i = 1; i < argc; ++i) {
157 if (argv[i] && *argv[i] != '-') {
161 QByteArray arg = argv[i];
162 if (arg.startsWith("-qmljsdebugger=")) {
163 qmljs_debug_arguments = QString::fromLocal8Bit(arg.right(arg.length() - 15));
175 // Support for introspection
177 QSignalSpyCallbackSet Q_CORE_EXPORT qt_signal_spy_callback_set = { 0, 0, 0, 0 };
179 void qt_register_signal_spy_callbacks(const QSignalSpyCallbackSet &callback_set)
181 qt_signal_spy_callback_set = callback_set;
184 extern "C" void Q_CORE_EXPORT qt_startup_hook()
188 typedef QList<QtCleanUpFunction> QVFuncList;
189 Q_GLOBAL_STATIC(QVFuncList, postRList)
191 void qAddPostRoutine(QtCleanUpFunction p)
193 QVFuncList *list = postRList();
199 void qRemovePostRoutine(QtCleanUpFunction p)
201 QVFuncList *list = postRList();
207 void Q_CORE_EXPORT qt_call_post_routines()
209 QVFuncList *list = 0;
212 } QT_CATCH(const std::bad_alloc &) {
213 // ignore - if we can't allocate a post routine list,
214 // there's a high probability that there's no post
215 // routine to be executed :)
219 while (!list->isEmpty())
220 (list->takeFirst())();
224 // app starting up if false
225 bool QCoreApplicationPrivate::is_app_running = false;
226 // app closing down if true
227 bool QCoreApplicationPrivate::is_app_closing = false;
228 // initialized in qcoreapplication and in qtextstream autotest when setlocale is called.
229 Q_CORE_EXPORT bool qt_locale_initialized = false;
231 Q_CORE_EXPORT uint qGlobalPostedEventsCount()
233 QThreadData *currentThreadData = QThreadData::current();
234 return currentThreadData->postEventList.size() - currentThreadData->postEventList.startOffset;
237 QCoreApplication *QCoreApplication::self = 0;
238 QAbstractEventDispatcher *QCoreApplicationPrivate::eventDispatcher = 0;
239 uint QCoreApplicationPrivate::attribs = (1 << Qt::AA_SynthesizeMouseForUnhandledTouchEvents);
242 Qt::HANDLE qt_application_thread_id = 0;
245 struct QCoreApplicationData {
246 QCoreApplicationData() {
247 #ifndef QT_NO_LIBRARY
251 ~QCoreApplicationData() {
252 #ifndef QT_NO_LIBRARY
256 // cleanup the QAdoptedThread created for the main() thread
257 if (QCoreApplicationPrivate::theMainThread) {
258 QThreadData *data = QThreadData::get2(QCoreApplicationPrivate::theMainThread);
259 QCoreApplicationPrivate::theMainThread = 0;
260 data->deref(); // deletes the data and the adopted thread
263 QString orgName, orgDomain, application;
264 QString applicationVersion;
266 #ifndef QT_NO_LIBRARY
267 QStringList *app_libpaths;
272 Q_GLOBAL_STATIC(QCoreApplicationData, coreappdata)
274 static bool quitLockRefEnabled = true;
276 QCoreApplicationPrivate::QCoreApplicationPrivate(int &aargc, char **aargv, uint flags)
277 : QObjectPrivate(), argc(aargc), argv(aargv), application_type(0), eventFilter(0),
278 in_exec(false), aboutToQuitEmitted(false), threadData_clean(false)
280 app_compile_version = flags & 0xffffff;
281 static const char *const empty = "";
282 if (argc == 0 || argv == 0) {
284 argv = (char **)∅ // ouch! careful with QCoreApplication::argv()!
286 QCoreApplicationPrivate::is_app_closing = false;
289 qt_application_thread_id = QThread::currentThreadId();
292 // note: this call to QThread::currentThread() may end up setting theMainThread!
293 if (QThread::currentThread() != theMainThread)
294 qWarning("WARNING: QApplication was not created in the main() thread.");
297 QCoreApplicationPrivate::~QCoreApplicationPrivate()
302 void QCoreApplicationPrivate::cleanupThreadData()
304 if (threadData && !threadData_clean) {
306 void *data = &threadData->tls;
307 QThreadStorageData::finish((void **)data);
310 // need to clear the state of the mainData, just in case a new QCoreApplication comes along.
311 QMutexLocker locker(&threadData->postEventList.mutex);
312 for (int i = 0; i < threadData->postEventList.size(); ++i) {
313 const QPostEvent &pe = threadData->postEventList.at(i);
315 --pe.receiver->d_func()->postedEvents;
316 pe.event->posted = false;
320 threadData->postEventList.clear();
321 threadData->postEventList.recursion = 0;
322 threadData->quitNow = false;
323 threadData_clean = true;
327 void QCoreApplicationPrivate::createEventDispatcher()
329 Q_Q(QCoreApplication);
330 #if defined(Q_OS_UNIX)
331 # if !defined(QT_NO_GLIB)
332 if (qgetenv("QT_NO_GLIB").isEmpty() && QEventDispatcherGlib::versionSupported())
333 eventDispatcher = new QEventDispatcherGlib(q);
336 eventDispatcher = new QEventDispatcherUNIX(q);
337 #elif defined(Q_OS_WIN)
338 eventDispatcher = new QEventDispatcherWin32(q);
340 # error "QEventDispatcher not yet ported to this platform"
344 void QCoreApplicationPrivate::_q_initializeProcessManager()
346 #ifndef QT_NO_PROCESS
348 QProcessPrivate::initializeProcessManager();
354 QThread *QCoreApplicationPrivate::theMainThread = 0;
355 QThread *QCoreApplicationPrivate::mainThread()
357 Q_ASSERT(theMainThread != 0);
358 return theMainThread;
361 #if !defined (QT_NO_DEBUG) || defined (QT_MAC_FRAMEWORK_BUILD)
362 void QCoreApplicationPrivate::checkReceiverThread(QObject *receiver)
364 QThread *currentThread = QThread::currentThread();
365 QThread *thr = receiver->thread();
366 Q_ASSERT_X(currentThread == thr || !thr,
367 "QCoreApplication::sendEvent",
368 QString::fromLatin1("Cannot send events to objects owned by a different thread. "
369 "Current thread %1. Receiver '%2' (of type '%3') was created in thread %4")
370 .arg(QString::number((quintptr) currentThread, 16))
371 .arg(receiver->objectName())
372 .arg(QLatin1String(receiver->metaObject()->className()))
373 .arg(QString::number((quintptr) thr, 16))
374 .toLocal8Bit().data());
375 Q_UNUSED(currentThread);
380 void QCoreApplicationPrivate::appendApplicationPathToLibraryPaths()
382 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
383 QStringList *app_libpaths = coreappdata()->app_libpaths;
384 Q_ASSERT(app_libpaths);
385 QString app_location( QCoreApplication::applicationFilePath() );
386 app_location.truncate(app_location.lastIndexOf(QLatin1Char('/')));
387 app_location = QDir(app_location).canonicalPath();
388 if (QFile::exists(app_location) && !app_libpaths->contains(app_location))
389 app_libpaths->append(app_location);
395 if (!QCoreApplicationPrivate::checkInstance("qAppName"))
397 return QCoreApplication::instance()->d_func()->appName();
401 \class QCoreApplication
402 \brief The QCoreApplication class provides an event loop for console Qt
405 This class is used by non-GUI applications to provide their event
406 loop. For non-GUI application that uses Qt, there should be exactly
407 one QCoreApplication object. For GUI applications, see
410 QCoreApplication contains the main event loop, where all events
411 from the operating system (e.g., timer and network events) and
412 other sources are processed and dispatched. It also handles the
413 application's initialization and finalization, as well as
414 system-wide and application-wide settings.
416 \section1 The Event Loop and Event Handling
418 The event loop is started with a call to exec(). Long running
419 operations can call processEvents() to keep the application
422 In general, we recommend that you create a QCoreApplication or a
423 QApplication object in your \c main() function as early as
424 possible. exec() will not return until the event loop exits; e.g.,
425 when quit() is called.
427 Several static convenience functions are also provided. The
428 QCoreApplication object is available from instance(). Events can
429 be sent or posted using sendEvent(), postEvent(), and
430 sendPostedEvents(). Pending events can be removed with
431 removePostedEvents() or flushed with flush().
433 The class provides a quit() slot and an aboutToQuit() signal.
435 \section1 Application and Library Paths
437 An application has an applicationDirPath() and an
438 applicationFilePath(). Library paths (see QLibrary) can be retrieved
439 with libraryPaths() and manipulated by setLibraryPaths(), addLibraryPath(),
440 and removeLibraryPath().
442 \section1 Internationalization and Translations
444 Translation files can be added or removed
445 using installTranslator() and removeTranslator(). Application
446 strings can be translated using translate(). The QObject::tr()
447 and QObject::trUtf8() functions are implemented in terms of
450 \section1 Accessing Command Line Arguments
452 The command line arguments which are passed to QCoreApplication's
453 constructor should be accessed using the arguments() function.
454 Note that some arguments supplied by the user may have been
455 processed and removed by QCoreApplication.
457 In cases where command line arguments need to be obtained using the
458 argv() function, you must convert them from the local string encoding
459 using QString::fromLocal8Bit().
461 \section1 Locale Settings
463 On Unix/Linux Qt is configured to use the system locale settings by
464 default. This can cause a conflict when using POSIX functions, for
465 instance, when converting between data types such as floats and
466 strings, since the notation may differ between locales. To get
467 around this problem, call the POSIX function \c{setlocale(LC_NUMERIC,"C")}
468 right after initializing QApplication or QCoreApplication to reset
469 the locale that is used for number formatting to "C"-locale.
471 \sa QApplication, QAbstractEventDispatcher, QEventLoop,
472 {Semaphores Example}, {Wait Conditions Example}
476 \fn static QCoreApplication *QCoreApplication::instance()
478 Returns a pointer to the application's QCoreApplication (or
479 QApplication) instance.
481 If no instance has been allocated, \c null is returned.
486 QCoreApplication::QCoreApplication(QCoreApplicationPrivate &p)
490 // note: it is the subclasses' job to call
491 // QCoreApplicationPrivate::eventDispatcher->startingUp();
495 Flushes the platform specific event queues.
497 If you are doing graphical changes inside a loop that does not
498 return to the event loop on asynchronous window systems like X11
499 or double buffered window systems like Mac OS X, and you want to
500 visualize these changes immediately (e.g. Splash Screens), call
503 \sa sendPostedEvents()
505 void QCoreApplication::flush()
507 if (self && self->d_func()->eventDispatcher)
508 self->d_func()->eventDispatcher->flush();
512 Constructs a Qt kernel application. Kernel applications are
513 applications without a graphical user interface. These type of
514 applications are used at the console or as server processes.
516 The \a argc and \a argv arguments are processed by the application,
517 and made available in a more convenient form by the arguments()
520 \warning The data referred to by \a argc and \a argv must stay valid
521 for the entire lifetime of the QCoreApplication object. In addition,
522 \a argc must be greater than zero and \a argv must contain at least
523 one valid character string.
525 QCoreApplication::QCoreApplication(int &argc, char **argv, int _internal)
526 : QObject(*new QCoreApplicationPrivate(argc, argv, _internal))
529 QCoreApplicationPrivate::eventDispatcher->startingUp();
533 // ### move to QCoreApplicationPrivate constructor?
534 void QCoreApplication::init()
536 Q_D(QCoreApplication);
539 setlocale(LC_ALL, ""); // use correct char set mapping
540 qt_locale_initialized = true;
543 Q_ASSERT_X(!self, "QCoreApplication", "there should be only one application object");
544 QCoreApplication::self = this;
546 // use the event dispatcher created by the app programmer (if any)
547 if (!QCoreApplicationPrivate::eventDispatcher)
548 QCoreApplicationPrivate::eventDispatcher = d->threadData->eventDispatcher;
549 // otherwise we create one
550 if (!QCoreApplicationPrivate::eventDispatcher)
551 d->createEventDispatcher();
552 Q_ASSERT(QCoreApplicationPrivate::eventDispatcher != 0);
554 if (!QCoreApplicationPrivate::eventDispatcher->parent()) {
555 QCoreApplicationPrivate::eventDispatcher->moveToThread(d->threadData->thread);
556 QCoreApplicationPrivate::eventDispatcher->setParent(this);
559 d->threadData->eventDispatcher = QCoreApplicationPrivate::eventDispatcher;
561 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
562 if (!coreappdata()->app_libpaths) {
563 // make sure that library paths is initialized
566 d->appendApplicationPathToLibraryPaths();
571 extern void qt_core_eval_init(uint);
572 qt_core_eval_init(d->application_type);
575 d->processCommandLineArguments();
581 Destroys the QCoreApplication object.
583 QCoreApplication::~QCoreApplication()
585 qt_call_post_routines();
588 QCoreApplicationPrivate::is_app_closing = true;
589 QCoreApplicationPrivate::is_app_running = false;
591 #if !defined(QT_NO_THREAD)
592 // Synchronize and stop the global thread pool threads.
593 QThreadPool *globalThreadPool = 0;
595 globalThreadPool = QThreadPool::globalInstance();
597 // swallow the exception, since destructors shouldn't throw
599 if (globalThreadPool)
600 globalThreadPool->waitForDone();
603 d_func()->threadData->eventDispatcher = 0;
604 if (QCoreApplicationPrivate::eventDispatcher)
605 QCoreApplicationPrivate::eventDispatcher->closingDown();
606 QCoreApplicationPrivate::eventDispatcher = 0;
608 #ifndef QT_NO_LIBRARY
609 delete coreappdata()->app_libpaths;
610 coreappdata()->app_libpaths = 0;
616 Sets the attribute \a attribute if \a on is true;
617 otherwise clears the attribute.
619 One of the attributes that can be set with this method is
620 Qt::AA_ImmediateWidgetCreation. It tells Qt to create toplevel
621 windows immediately. Normally, resources for widgets are allocated
622 on demand to improve efficiency and minimize resource usage.
623 Therefore, if it is important to minimize resource consumption, do
624 not set this attribute.
628 void QCoreApplication::setAttribute(Qt::ApplicationAttribute attribute, bool on)
631 QCoreApplicationPrivate::attribs |= 1 << attribute;
633 QCoreApplicationPrivate::attribs &= ~(1 << attribute);
637 Returns true if attribute \a attribute is set;
638 otherwise returns false.
642 bool QCoreApplication::testAttribute(Qt::ApplicationAttribute attribute)
644 return QCoreApplicationPrivate::testAttribute(attribute);
648 Returns true if the use of the QEventLoopLocker feature can cause the
649 application to quit, otherwise returns false.
653 bool QCoreApplication::isQuitLockEnabled()
655 return quitLockRefEnabled;
659 Enables the ability of the QEventLoopLocker feature to quit
662 If disabled, the use of QEventLoopLocker will not quit the application.
666 void QCoreApplication::setQuitLockEnabled(bool enabled)
668 quitLockRefEnabled = enabled;
674 This function is here to make it possible for Qt extensions to
675 hook into event notification without subclassing QApplication
677 bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
679 // Make it possible for QtScript to hook into events even
680 // though QApplication is subclassed...
682 void *cbdata[] = { receiver, event, &result };
683 if (QInternal::activateCallbacks(QInternal::EventNotifyCallback, cbdata)) {
687 // Qt enforces the rule that events can only be sent to objects in
688 // the current thread, so receiver->d_func()->threadData is
689 // equivalent to QThreadData::current(), just without the function
691 QObjectPrivate *d = receiver->d_func();
692 QThreadData *threadData = d->threadData;
693 QScopedLoopLevelCounter loopLevelCounter(threadData);
694 return notify(receiver, event);
699 Sends \a event to \a receiver: \a {receiver}->event(\a event).
700 Returns the value that is returned from the receiver's event
701 handler. Note that this function is called for all events sent to
702 any object in any thread.
704 For certain types of events (e.g. mouse and key events),
705 the event will be propagated to the receiver's parent and so on up to
706 the top-level object if the receiver is not interested in the event
707 (i.e., it returns false).
709 There are five different ways that events can be processed;
710 reimplementing this virtual function is just one of them. All five
711 approaches are listed below:
713 \li Reimplementing paintEvent(), mousePressEvent() and so
714 on. This is the commonest, easiest and least powerful way.
716 \li Reimplementing this function. This is very powerful, providing
717 complete control; but only one subclass can be active at a time.
719 \li Installing an event filter on QCoreApplication::instance(). Such
720 an event filter is able to process all events for all widgets, so
721 it's just as powerful as reimplementing notify(); furthermore, it's
722 possible to have more than one application-global event filter.
723 Global event filters even see mouse events for
724 \l{QWidget::isEnabled()}{disabled widgets}. Note that application
725 event filters are only called for objects that live in the main
728 \li Reimplementing QObject::event() (as QWidget does). If you do
729 this you get Tab key presses, and you get to see the events before
730 any widget-specific event filters.
732 \li Installing an event filter on the object. Such an event filter gets all
733 the events, including Tab and Shift+Tab key press events, as long as they
734 do not change the focus widget.
737 \sa QObject::event(), installEventFilter()
740 bool QCoreApplication::notify(QObject *receiver, QEvent *event)
742 Q_D(QCoreApplication);
743 // no events are delivered after ~QCoreApplication() has started
744 if (QCoreApplicationPrivate::is_app_closing)
747 if (receiver == 0) { // serious error
748 qWarning("QCoreApplication::notify: Unexpected null receiver");
753 d->checkReceiverThread(receiver);
756 return receiver->isWidgetType() ? false : d->notify_helper(receiver, event);
759 bool QCoreApplicationPrivate::sendThroughApplicationEventFilters(QObject *receiver, QEvent *event)
761 if (receiver->d_func()->threadData == this->threadData) {
762 // application event filters are only called for objects in the GUI thread
763 for (int i = 0; i < eventFilters.size(); ++i) {
764 register QObject *obj = eventFilters.at(i);
767 if (obj->d_func()->threadData != threadData) {
768 qWarning("QCoreApplication: Application event filter cannot be in a different thread.");
771 if (obj->eventFilter(receiver, event))
778 bool QCoreApplicationPrivate::sendThroughObjectEventFilters(QObject *receiver, QEvent *event)
780 Q_Q(QCoreApplication);
782 for (int i = 0; i < receiver->d_func()->eventFilters.size(); ++i) {
783 register QObject *obj = receiver->d_func()->eventFilters.at(i);
786 if (obj->d_func()->threadData != receiver->d_func()->threadData) {
787 qWarning("QCoreApplication: Object event filter cannot be in a different thread.");
790 if (obj->eventFilter(receiver, event))
799 Helper function called by notify()
801 bool QCoreApplicationPrivate::notify_helper(QObject *receiver, QEvent * event)
803 // send to all application event filters
804 if (sendThroughApplicationEventFilters(receiver, event))
806 // send to all receiver event filters
807 if (sendThroughObjectEventFilters(receiver, event))
810 return receiver->event(event);
814 Returns true if an application object has not been created yet;
815 otherwise returns false.
820 bool QCoreApplication::startingUp()
822 return !QCoreApplicationPrivate::is_app_running;
826 Returns true if the application objects are being destroyed;
827 otherwise returns false.
832 bool QCoreApplication::closingDown()
834 return QCoreApplicationPrivate::is_app_closing;
839 Processes all pending events for the calling thread according to
840 the specified \a flags until there are no more events to process.
842 You can call this function occasionally when your program is busy
843 performing a long operation (e.g. copying a file).
845 In event you are running a local loop which calls this function
846 continuously, without an event loop, the
847 \l{QEvent::DeferredDelete}{DeferredDelete} events will
848 not be processed. This can affect the behaviour of widgets,
849 e.g. QToolTip, that rely on \l{QEvent::DeferredDelete}{DeferredDelete}
850 events to function properly. An alternative would be to call
851 \l{QCoreApplication::sendPostedEvents()}{sendPostedEvents()} from
852 within that local loop.
854 Calling this function processes events only for the calling thread.
858 \sa exec(), QTimer, QEventLoop::processEvents(), flush(), sendPostedEvents()
860 void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags)
862 QThreadData *data = QThreadData::current();
863 if (!data->eventDispatcher)
865 data->eventDispatcher->processEvents(flags);
869 \overload processEvents()
871 Processes pending events for the calling thread for \a maxtime
872 milliseconds or until there are no more events to process,
873 whichever is shorter.
875 You can call this function occasionally when you program is busy
876 doing a long operation (e.g. copying a file).
878 Calling this function processes events only for the calling thread.
882 \sa exec(), QTimer, QEventLoop::processEvents()
884 void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags, int maxtime)
886 QThreadData *data = QThreadData::current();
887 if (!data->eventDispatcher)
891 while (data->eventDispatcher->processEvents(flags & ~QEventLoop::WaitForMoreEvents)) {
892 if (start.elapsed() > maxtime)
897 /*****************************************************************************
898 Main event loop wrappers
899 *****************************************************************************/
902 Enters the main event loop and waits until exit() is called.
903 Returns the value that was set to exit() (which is 0 if exit() is
906 It is necessary to call this function to start event handling. The
907 main event loop receives events from the window system and
908 dispatches these to the application widgets.
910 To make your application perform idle processing (i.e. executing a
911 special function whenever there are no pending events), use a
912 QTimer with 0 timeout. More advanced idle processing schemes can
913 be achieved using processEvents().
915 We recommend that you connect clean-up code to the
916 \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in
917 your application's \c{main()} function because on some platforms the
918 QCoreApplication::exec() call may not return. For example, on Windows
919 when the user logs off, the system terminates the process after Qt
920 closes all top-level windows. Hence, there is no guarantee that the
921 application will have time to exit its event loop and execute code at
922 the end of the \c{main()} function after the QCoreApplication::exec()
925 \sa quit(), exit(), processEvents(), QApplication::exec()
927 int QCoreApplication::exec()
929 if (!QCoreApplicationPrivate::checkInstance("exec"))
932 QThreadData *threadData = self->d_func()->threadData;
933 if (threadData != QThreadData::current()) {
934 qWarning("%s::exec: Must be called from the main thread", self->metaObject()->className());
937 if (!threadData->eventLoops.isEmpty()) {
938 qWarning("QCoreApplication::exec: The event loop is already running");
942 threadData->quitNow = false;
943 QEventLoop eventLoop;
944 self->d_func()->in_exec = true;
945 self->d_func()->aboutToQuitEmitted = false;
946 int returnCode = eventLoop.exec();
947 threadData->quitNow = false;
949 self->d_func()->in_exec = false;
950 if (!self->d_func()->aboutToQuitEmitted)
951 emit self->aboutToQuit();
952 self->d_func()->aboutToQuitEmitted = true;
953 sendPostedEvents(0, QEvent::DeferredDelete);
961 Tells the application to exit with a return code.
963 After this function has been called, the application leaves the
964 main event loop and returns from the call to exec(). The exec()
965 function returns \a returnCode. If the event loop is not running,
966 this function does nothing.
968 By convention, a \a returnCode of 0 means success, and any non-zero
969 value indicates an error.
971 Note that unlike the C library function of the same name, this
972 function \e does return to the caller -- it is event processing that
977 void QCoreApplication::exit(int returnCode)
981 QThreadData *data = self->d_func()->threadData;
982 data->quitNow = true;
983 for (int i = 0; i < data->eventLoops.size(); ++i) {
984 QEventLoop *eventLoop = data->eventLoops.at(i);
985 eventLoop->exit(returnCode);
989 /*****************************************************************************
990 QCoreApplication management of posted events
991 *****************************************************************************/
994 \fn bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
996 Sends event \a event directly to receiver \a receiver, using the
997 notify() function. Returns the value that was returned from the
1000 The event is \e not deleted when the event has been sent. The normal
1001 approach is to create the event on the stack, for example:
1003 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 0
1005 \sa postEvent(), notify()
1011 Adds the event \a event, with the object \a receiver as the
1012 receiver of the event, to an event queue and returns immediately.
1014 The event must be allocated on the heap since the post event queue
1015 will take ownership of the event and delete it once it has been
1016 posted. It is \e {not safe} to access the event after
1019 When control returns to the main event loop, all events that are
1020 stored in the queue will be sent using the notify() function.
1022 Events are sorted in descending \a priority order, i.e. events
1023 with a high \a priority are queued before events with a lower \a
1024 priority. The \a priority can be any integer value, i.e. between
1025 INT_MAX and INT_MIN, inclusive; see Qt::EventPriority for more
1026 details. Events with equal \a priority will be processed in the
1031 \sa sendEvent(), notify(), sendPostedEvents(), Qt::EventPriority
1033 void QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority)
1035 if (receiver == 0) {
1036 qWarning("QCoreApplication::postEvent: Unexpected null receiver");
1041 QThreadData * volatile * pdata = &receiver->d_func()->threadData;
1042 QThreadData *data = *pdata;
1044 // posting during destruction? just delete the event to prevent a leak
1049 // lock the post event mutex
1050 data->postEventList.mutex.lock();
1052 // if object has moved to another thread, follow it
1053 while (data != *pdata) {
1054 data->postEventList.mutex.unlock();
1058 // posting during destruction? just delete the event to prevent a leak
1063 data->postEventList.mutex.lock();
1066 QMutexUnlocker locker(&data->postEventList.mutex);
1068 // if this is one of the compressible events, do compression
1069 if (receiver->d_func()->postedEvents
1070 && self && self->compressEvent(event, receiver, &data->postEventList)) {
1074 if (event->type() == QEvent::DeferredDelete && data == QThreadData::current()) {
1075 // remember the current running eventloop for DeferredDelete
1076 // events posted in the receiver's thread
1077 event->d = reinterpret_cast<QEventPrivate *>(quintptr(data->loopLevel));
1080 // delete the event on exceptions to protect against memory leaks till the event is
1081 // properly owned in the postEventList
1082 QScopedPointer<QEvent> eventDeleter(event);
1083 data->postEventList.addEvent(QPostEvent(receiver, event, priority));
1084 eventDeleter.take();
1085 event->posted = true;
1086 ++receiver->d_func()->postedEvents;
1087 data->canWait = false;
1090 if (data->eventDispatcher)
1091 data->eventDispatcher->wakeUp();
1096 Returns true if \a event was compressed away (possibly deleted) and should not be added to the list.
1098 bool QCoreApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
1103 Q_ASSERT(postedEvents);
1105 // compress posted timers to this object.
1106 if (event->type() == QEvent::Timer && receiver->d_func()->postedEvents > 0) {
1107 int timerId = ((QTimerEvent *) event)->timerId();
1108 for (int i=0; i<postedEvents->size(); ++i) {
1109 const QPostEvent &e = postedEvents->at(i);
1110 if (e.receiver == receiver && e.event && e.event->type() == QEvent::Timer
1111 && ((QTimerEvent *) e.event)->timerId() == timerId) {
1118 if ((event->type() == QEvent::DeferredDelete
1119 || event->type() == QEvent::Quit)
1120 && receiver->d_func()->postedEvents > 0) {
1121 for (int i = 0; i < postedEvents->size(); ++i) {
1122 const QPostEvent &cur = postedEvents->at(i);
1123 if (cur.receiver != receiver
1125 || cur.event->type() != event->type())
1127 // found an event for this receiver
1136 Immediately dispatches all events which have been previously queued
1137 with QCoreApplication::postEvent() and which are for the object \a receiver
1138 and have the event type \a event_type.
1140 Events from the window system are \e not dispatched by this
1141 function, but by processEvents().
1143 If \a receiver is null, the events of \a event_type are sent for all
1144 objects. If \a event_type is 0, all the events are sent for \a receiver.
1146 \note This method must be called from the same thread as its QObject parameter, \a receiver.
1148 \sa flush(), postEvent()
1150 void QCoreApplication::sendPostedEvents(QObject *receiver, int event_type)
1152 QThreadData *data = QThreadData::current();
1154 QCoreApplicationPrivate::sendPostedEvents(receiver, event_type, data);
1157 void QCoreApplicationPrivate::sendPostedEvents(QObject *receiver, int event_type,
1160 if (event_type == -1) {
1161 // we were called by an obsolete event dispatcher.
1165 if (receiver && receiver->d_func()->threadData != data) {
1166 qWarning("QCoreApplication::sendPostedEvents: Cannot send "
1167 "posted events for objects in another thread");
1171 ++data->postEventList.recursion;
1173 QMutexLocker locker(&data->postEventList.mutex);
1175 // by default, we assume that the event dispatcher can go to sleep after
1176 // processing all events. if any new events are posted while we send
1177 // events, canWait will be set to false.
1178 data->canWait = (data->postEventList.size() == 0);
1180 if (data->postEventList.size() == 0 || (receiver && !receiver->d_func()->postedEvents)) {
1181 --data->postEventList.recursion;
1185 data->canWait = true;
1187 // okay. here is the tricky loop. be careful about optimizing
1188 // this, it looks the way it does for good reasons.
1189 int startOffset = data->postEventList.startOffset;
1190 int &i = (!event_type && !receiver) ? data->postEventList.startOffset : startOffset;
1191 data->postEventList.insertionOffset = data->postEventList.size();
1193 // Exception-safe cleaning up without the need for a try/catch block
1198 bool exceptionCaught;
1200 inline CleanUp(QObject *receiver, int event_type, QThreadData *data) :
1201 receiver(receiver), event_type(event_type), data(data), exceptionCaught(true)
1205 if (exceptionCaught) {
1206 // since we were interrupted, we need another pass to make sure we clean everything up
1207 data->canWait = false;
1210 --data->postEventList.recursion;
1211 if (!data->postEventList.recursion && !data->canWait && data->eventDispatcher)
1212 data->eventDispatcher->wakeUp();
1214 // clear the global list, i.e. remove everything that was
1216 if (!event_type && !receiver && data->postEventList.startOffset >= 0) {
1217 const QPostEventList::iterator it = data->postEventList.begin();
1218 data->postEventList.erase(it, it + data->postEventList.startOffset);
1219 data->postEventList.insertionOffset -= data->postEventList.startOffset;
1220 Q_ASSERT(data->postEventList.insertionOffset >= 0);
1221 data->postEventList.startOffset = 0;
1225 CleanUp cleanup(receiver, event_type, data);
1227 while (i < data->postEventList.size()) {
1229 if (i >= data->postEventList.insertionOffset)
1232 const QPostEvent &pe = data->postEventList.at(i);
1237 if ((receiver && receiver != pe.receiver) || (event_type && event_type != pe.event->type())) {
1238 data->canWait = false;
1242 if (pe.event->type() == QEvent::DeferredDelete) {
1243 // DeferredDelete events are only sent when we are explicitly asked to
1244 // (s.a. QEvent::DeferredDelete), and then only if the event loop that
1245 // posted the event has returned.
1246 const bool allowDeferredDelete =
1247 (quintptr(pe.event->d) > unsigned(data->loopLevel)
1248 || (!quintptr(pe.event->d) && data->loopLevel > 0)
1249 || (event_type == QEvent::DeferredDelete
1250 && quintptr(pe.event->d) == unsigned(data->loopLevel)));
1251 if (!allowDeferredDelete) {
1252 // cannot send deferred delete
1253 if (!event_type && !receiver) {
1254 // we must copy it first; we want to re-post the event
1255 // with the event pointer intact, but we can't delay
1256 // nulling the event ptr until after re-posting, as
1257 // addEvent may invalidate pe.
1258 QPostEvent pe_copy = pe;
1260 // null out the event so if sendPostedEvents recurses, it
1261 // will ignore this one, as it's been re-posted.
1262 const_cast<QPostEvent &>(pe).event = 0;
1264 // re-post the copied event so it isn't lost
1265 data->postEventList.addEvent(pe_copy);
1271 // first, we diddle the event so that we can deliver
1272 // it, and that no one will try to touch it later.
1273 pe.event->posted = false;
1274 QScopedPointer<QEvent> e(pe.event);
1275 QObject * r = pe.receiver;
1277 --r->d_func()->postedEvents;
1278 Q_ASSERT(r->d_func()->postedEvents >= 0);
1280 // next, update the data structure so that we're ready
1281 // for the next event.
1282 const_cast<QPostEvent &>(pe).event = 0;
1284 struct MutexUnlocker
1287 MutexUnlocker(QMutexLocker &m) : m(m) { m.unlock(); }
1288 ~MutexUnlocker() { m.relock(); }
1290 MutexUnlocker unlocker(locker);
1292 // after all that work, it's time to deliver the event.
1293 QCoreApplication::sendEvent(r, e.data());
1295 // careful when adding anything below this point - the
1296 // sendEvent() call might invalidate any invariants this
1297 // function depends on.
1300 cleanup.exceptionCaught = false;
1306 Removes all events of the given \a eventType that were posted
1307 using postEvent() for \a receiver.
1309 The events are \e not dispatched, instead they are removed from
1310 the queue. You should never need to call this function. If you do
1311 call it, be aware that killing events may cause \a receiver to
1312 break one or more invariants.
1314 If \a receiver is null, the events of \a eventType are removed for
1315 all objects. If \a eventType is 0, all the events are removed for
1316 \a receiver. You should never call this function with \a eventType
1317 of 0. If you do call it in this way, be aware that killing events
1318 may cause \a receiver to break one or more invariants.
1323 void QCoreApplication::removePostedEvents(QObject *receiver, int eventType)
1325 QThreadData *data = receiver ? receiver->d_func()->threadData : QThreadData::current();
1326 QMutexLocker locker(&data->postEventList.mutex);
1328 // the QObject destructor calls this function directly. this can
1329 // happen while the event loop is in the middle of posting events,
1330 // and when we get here, we may not have any more posted events
1332 if (receiver && !receiver->d_func()->postedEvents)
1335 //we will collect all the posted events for the QObject
1336 //and we'll delete after the mutex was unlocked
1337 QVarLengthArray<QEvent*> events;
1338 int n = data->postEventList.size();
1341 for (int i = 0; i < n; ++i) {
1342 const QPostEvent &pe = data->postEventList.at(i);
1344 if ((!receiver || pe.receiver == receiver)
1345 && (pe.event && (eventType == 0 || pe.event->type() == eventType))) {
1346 --pe.receiver->d_func()->postedEvents;
1347 pe.event->posted = false;
1348 events.append(pe.event);
1349 const_cast<QPostEvent &>(pe).event = 0;
1350 } else if (!data->postEventList.recursion) {
1352 qSwap(data->postEventList[i], data->postEventList[j]);
1358 if (receiver && eventType == 0) {
1359 Q_ASSERT(!receiver->d_func()->postedEvents);
1363 if (!data->postEventList.recursion) {
1365 data->postEventList.erase(data->postEventList.begin() + j, data->postEventList.end());
1369 for (int i = 0; i < events.count(); ++i) {
1375 Removes \a event from the queue of posted events, and emits a
1376 warning message if appropriate.
1378 \warning This function can be \e really slow. Avoid using it, if
1384 void QCoreApplicationPrivate::removePostedEvent(QEvent * event)
1386 if (!event || !event->posted)
1389 QThreadData *data = QThreadData::current();
1391 QMutexLocker locker(&data->postEventList.mutex);
1393 if (data->postEventList.size() == 0) {
1394 #if defined(QT_DEBUG)
1395 qDebug("QCoreApplication::removePostedEvent: Internal error: %p %d is posted",
1396 (void*)event, event->type());
1401 for (int i = 0; i < data->postEventList.size(); ++i) {
1402 const QPostEvent & pe = data->postEventList.at(i);
1403 if (pe.event == event) {
1405 qWarning("QCoreApplication::removePostedEvent: Event of type %d deleted while posted to %s %s",
1407 pe.receiver->metaObject()->className(),
1408 pe.receiver->objectName().toLocal8Bit().data());
1410 --pe.receiver->d_func()->postedEvents;
1411 pe.event->posted = false;
1413 const_cast<QPostEvent &>(pe).event = 0;
1422 bool QCoreApplication::event(QEvent *e)
1424 if (e->type() == QEvent::Quit) {
1428 return QObject::event(e);
1431 /*! \enum QCoreApplication::Encoding
1433 This enum type defines the 8-bit encoding of character string
1434 arguments to translate():
1436 \value UnicodeUTF8 UTF-8.
1437 \value Latin1 Latin-1.
1438 \value DefaultCodec Latin-1.
1440 \sa QObject::tr(), QObject::trUtf8(), QString::fromUtf8()
1443 void QCoreApplicationPrivate::ref()
1448 void QCoreApplicationPrivate::deref()
1450 if (!quitLockRef.deref())
1454 void QCoreApplicationPrivate::maybeQuit()
1456 if (quitLockRef.load() == 0 && in_exec && quitLockRefEnabled && shouldQuit())
1457 QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(QEvent::Quit));
1461 Tells the application to exit with return code 0 (success).
1462 Equivalent to calling QCoreApplication::exit(0).
1464 It's common to connect the QApplication::lastWindowClosed() signal
1465 to quit(), and you also often connect e.g. QAbstractButton::clicked() or
1466 signals in QAction, QMenu, or QMenuBar to it.
1470 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 1
1472 \sa exit(), aboutToQuit(), QApplication::lastWindowClosed()
1475 void QCoreApplication::quit()
1481 \fn void QCoreApplication::aboutToQuit()
1483 This signal is emitted when the application is about to quit the
1484 main event loop, e.g. when the event loop level drops to zero.
1485 This may happen either after a call to quit() from inside the
1486 application or when the users shuts down the entire desktop session.
1488 The signal is particularly useful if your application has to do some
1489 last-second cleanup. Note that no user interaction is possible in
1495 #ifndef QT_NO_TRANSLATION
1497 Adds the translation file \a translationFile to the list of
1498 translation files to be used for translations.
1500 Multiple translation files can be installed. Translations are
1501 searched for in the reverse order in which they were installed,
1502 so the most recently installed translation file is searched first
1503 and the first translation file installed is searched last.
1504 The search stops as soon as a translation containing a matching
1507 Installing or removing a QTranslator, or changing an installed QTranslator
1508 generates a \l{QEvent::LanguageChange}{LanguageChange} event for the
1509 QCoreApplication instance. A QApplication instance will propagate the event
1510 to all toplevel windows, where a reimplementation of changeEvent can
1511 re-translate the user interface by passing user-visible strings via the
1512 tr() function to the respective property setters. User-interface classes
1513 generated by \l{Qt Designer} provide a \c retranslateUi() function that can be
1516 \sa removeTranslator() translate() QTranslator::load() {Dynamic Translation}
1519 void QCoreApplication::installTranslator(QTranslator *translationFile)
1521 if (!translationFile)
1524 if (!QCoreApplicationPrivate::checkInstance("installTranslator"))
1526 QCoreApplicationPrivate *d = self->d_func();
1527 d->translators.prepend(translationFile);
1529 #ifndef QT_NO_TRANSLATION_BUILDER
1530 if (translationFile->isEmpty())
1534 QEvent ev(QEvent::LanguageChange);
1535 QCoreApplication::sendEvent(self, &ev);
1539 Removes the translation file \a translationFile from the list of
1540 translation files used by this application. (It does not delete the
1541 translation file from the file system.)
1543 \sa installTranslator() translate(), QObject::tr()
1546 void QCoreApplication::removeTranslator(QTranslator *translationFile)
1548 if (!translationFile)
1550 if (!QCoreApplicationPrivate::checkInstance("removeTranslator"))
1552 QCoreApplicationPrivate *d = self->d_func();
1553 if (d->translators.removeAll(translationFile) && !self->closingDown()) {
1554 QEvent ev(QEvent::LanguageChange);
1555 QCoreApplication::sendEvent(self, &ev);
1559 static void replacePercentN(QString *result, int n)
1564 while ((percentPos = result->indexOf(QLatin1Char('%'), percentPos + len)) != -1) {
1567 if (result->at(percentPos + len) == QLatin1Char('L')) {
1569 fmt = QLatin1String("%L1");
1571 fmt = QLatin1String("%1");
1573 if (result->at(percentPos + len) == QLatin1Char('n')) {
1576 result->replace(percentPos, len, fmt);
1587 Returns the translation text for \a sourceText, by querying the
1588 installed translation files. The translation files are searched
1589 from the most recently installed file back to the first
1592 QObject::tr() and QObject::trUtf8() provide this functionality
1595 \a context is typically a class name (e.g., "MyDialog") and \a
1596 sourceText is either English text or a short identifying text.
1598 \a disambiguation is an identifying string, for when the same \a
1599 sourceText is used in different roles within the same context. By
1600 default, it is null.
1602 See the \l QTranslator and \l QObject::tr() documentation for
1603 more information about contexts, disambiguations and comments.
1605 \a encoding indicates the 8-bit encoding of character strings.
1607 \a n is used in conjunction with \c %n to support plural forms.
1608 See QObject::tr() for details.
1610 If none of the translation files contain a translation for \a
1611 sourceText in \a context, this function returns a QString
1612 equivalent of \a sourceText. The encoding of \a sourceText is
1613 specified by \e encoding; it defaults to DefaultCodec.
1615 This function is not virtual. You can use alternative translation
1616 techniques by subclassing \l QTranslator.
1618 \warning This method is reentrant only if all translators are
1619 installed \e before calling this method. Installing or removing
1620 translators while performing translations is not supported. Doing
1621 so will most likely result in crashes or other undesirable
1624 \sa QObject::tr() installTranslator()
1628 QString QCoreApplication::translate(const char *context, const char *sourceText,
1629 const char *disambiguation, Encoding encoding, int n)
1636 if (self && !self->d_func()->translators.isEmpty()) {
1637 QList<QTranslator*>::ConstIterator it;
1638 QTranslator *translationFile;
1639 for (it = self->d_func()->translators.constBegin(); it != self->d_func()->translators.constEnd(); ++it) {
1640 translationFile = *it;
1641 result = translationFile->translate(context, sourceText, disambiguation, n);
1642 if (!result.isNull())
1647 if (result.isNull()) {
1648 #ifdef QT_NO_TEXTCODEC
1651 if (encoding == UnicodeUTF8)
1652 result = QString::fromUtf8(sourceText);
1655 result = QString::fromLatin1(sourceText);
1658 replacePercentN(&result, n);
1662 // Declared in qglobal.h
1663 QString qtTrId(const char *id, int n)
1665 return QCoreApplication::translate(0, id, 0, QCoreApplication::UnicodeUTF8, n);
1668 bool QCoreApplicationPrivate::isTranslatorInstalled(QTranslator *translator)
1670 return QCoreApplication::self
1671 && QCoreApplication::self->d_func()->translators.contains(translator);
1674 #endif //QT_NO_TRANSLATE
1677 Returns the directory that contains the application executable.
1679 For example, if you have installed Qt in the \c{C:\Qt}
1680 directory, and you run the \c{regexp} example, this function will
1681 return "C:/Qt/examples/tools/regexp".
1683 On Mac OS X this will point to the directory actually containing the
1684 executable, which may be inside of an application bundle (if the
1685 application is bundled).
1687 \warning On Linux, this function will try to get the path from the
1688 \c {/proc} file system. If that fails, it assumes that \c
1689 {argv[0]} contains the absolute file name of the executable. The
1690 function also assumes that the current directory has not been
1691 changed by the application.
1693 \sa applicationFilePath()
1695 QString QCoreApplication::applicationDirPath()
1698 qWarning("QCoreApplication::applicationDirPath: Please instantiate the QApplication object first");
1702 QCoreApplicationPrivate *d = self->d_func();
1703 if (d->cachedApplicationDirPath.isNull())
1704 d->cachedApplicationDirPath = QFileInfo(applicationFilePath()).path();
1705 return d->cachedApplicationDirPath;
1709 Returns the file path of the application executable.
1711 For example, if you have installed Qt in the \c{/usr/local/qt}
1712 directory, and you run the \c{regexp} example, this function will
1713 return "/usr/local/qt/examples/tools/regexp/regexp".
1715 \warning On Linux, this function will try to get the path from the
1716 \c {/proc} file system. If that fails, it assumes that \c
1717 {argv[0]} contains the absolute file name of the executable. The
1718 function also assumes that the current directory has not been
1719 changed by the application.
1721 \sa applicationDirPath()
1723 QString QCoreApplication::applicationFilePath()
1726 qWarning("QCoreApplication::applicationFilePath: Please instantiate the QApplication object first");
1730 QCoreApplicationPrivate *d = self->d_func();
1731 if (!d->cachedApplicationFilePath.isNull())
1732 return d->cachedApplicationFilePath;
1734 #if defined(Q_OS_WIN)
1735 d->cachedApplicationFilePath = QFileInfo(qAppFileName()).filePath();
1736 return d->cachedApplicationFilePath;
1737 #elif defined(Q_OS_MAC)
1738 QString qAppFileName_str = qAppFileName();
1739 if(!qAppFileName_str.isEmpty()) {
1740 QFileInfo fi(qAppFileName_str);
1741 d->cachedApplicationFilePath = fi.exists() ? fi.canonicalFilePath() : QString();
1742 return d->cachedApplicationFilePath;
1745 #if defined( Q_OS_UNIX )
1747 // Try looking for a /proc/<pid>/exe symlink first which points to
1748 // the absolute path of the executable
1749 QFileInfo pfi(QString::fromLatin1("/proc/%1/exe").arg(getpid()));
1750 if (pfi.exists() && pfi.isSymLink()) {
1751 d->cachedApplicationFilePath = pfi.canonicalFilePath();
1752 return d->cachedApplicationFilePath;
1756 QString argv0 = QFile::decodeName(arguments().at(0).toLocal8Bit());
1759 if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/')) {
1761 If argv0 starts with a slash, it is already an absolute
1765 } else if (argv0.contains(QLatin1Char('/'))) {
1767 If argv0 contains one or more slashes, it is a file path
1768 relative to the current directory.
1770 absPath = QDir::current().absoluteFilePath(argv0);
1773 Otherwise, the file path has to be determined using the
1774 PATH environment variable.
1776 absPath = QStandardPaths::findExecutable(argv0);
1779 absPath = QDir::cleanPath(absPath);
1781 QFileInfo fi(absPath);
1782 d->cachedApplicationFilePath = fi.exists() ? fi.canonicalFilePath() : QString();
1783 return d->cachedApplicationFilePath;
1790 Returns the current process ID for the application.
1792 qint64 QCoreApplication::applicationPid()
1794 #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
1795 return GetCurrentProcessId();
1796 #elif defined(Q_OS_VXWORKS)
1797 return (pid_t) taskIdCurrent;
1806 Returns the list of command-line arguments.
1808 Usually arguments().at(0) is the program name, arguments().at(1)
1809 is the first argument, and arguments().last() is the last
1810 argument. See the note below about Windows.
1812 Calling this function is slow - you should store the result in a variable
1813 when parsing the command line.
1815 \warning On Unix, this list is built from the argc and argv parameters passed
1816 to the constructor in the main() function. The string-data in argv is
1817 interpreted using QString::fromLocal8Bit(); hence it is not possible to
1818 pass, for example, Japanese command line arguments on a system that runs in a
1819 Latin1 locale. Most modern Unix systems do not have this limitation, as they are
1822 On NT-based Windows, this limitation does not apply either.
1823 On Windows, the arguments() are not built from the contents of argv/argc, as
1824 the content does not support Unicode. Instead, the arguments() are constructed
1825 from the return value of
1826 \l{http://msdn2.microsoft.com/en-us/library/ms683156(VS.85).aspx}{GetCommandLine()}.
1827 As a result of this, the string given by arguments().at(0) might not be
1828 the program name on Windows, depending on how the application was started.
1830 \sa applicationFilePath()
1833 QStringList QCoreApplication::arguments()
1838 qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first");
1842 QString cmdline = QString::fromWCharArray(GetCommandLine());
1844 #if defined(Q_OS_WINCE)
1845 wchar_t tempFilename[MAX_PATH+1];
1846 if (GetModuleFileName(0, tempFilename, MAX_PATH)) {
1847 tempFilename[MAX_PATH] = 0;
1848 cmdline.prepend(QLatin1Char('\"') + QString::fromWCharArray(tempFilename) + QLatin1String("\" "));
1850 #endif // Q_OS_WINCE
1852 list = qWinCmdArgs(cmdline);
1853 if (self->d_func()->application_type) { // GUI app? Skip known - see qapplication.cpp
1854 QStringList stripped;
1855 for (int a = 0; a < list.count(); ++a) {
1856 QString arg = list.at(a);
1857 QByteArray l1arg = arg.toLatin1();
1858 if (l1arg == "-qdevel" ||
1859 l1arg == "-qdebug" ||
1860 l1arg == "-reverse" ||
1861 l1arg == "-stylesheet" ||
1862 l1arg == "-widgetcount")
1864 else if (l1arg.startsWith("-style=") ||
1865 l1arg.startsWith("-qmljsdebugger="))
1867 else if (l1arg == "-style" ||
1868 l1arg == "-session" ||
1869 l1arg == "-testability")
1877 const int ac = self->d_func()->argc;
1878 char ** const av = self->d_func()->argv;
1879 for (int a = 0; a < ac; ++a) {
1880 list << QString::fromLocal8Bit(av[a]);
1888 \property QCoreApplication::organizationName
1889 \brief the name of the organization that wrote this application
1891 The value is used by the QSettings class when it is constructed
1892 using the empty constructor. This saves having to repeat this
1893 information each time a QSettings object is created.
1895 On Mac, QSettings uses organizationDomain() as the organization
1896 if it's not an empty string; otherwise it uses
1897 organizationName(). On all other platforms, QSettings uses
1898 organizationName() as the organization.
1900 \sa organizationDomain applicationName
1903 void QCoreApplication::setOrganizationName(const QString &orgName)
1905 coreappdata()->orgName = orgName;
1908 QString QCoreApplication::organizationName()
1910 return coreappdata()->orgName;
1914 \property QCoreApplication::organizationDomain
1915 \brief the Internet domain of the organization that wrote this application
1917 The value is used by the QSettings class when it is constructed
1918 using the empty constructor. This saves having to repeat this
1919 information each time a QSettings object is created.
1921 On Mac, QSettings uses organizationDomain() as the organization
1922 if it's not an empty string; otherwise it uses organizationName().
1923 On all other platforms, QSettings uses organizationName() as the
1926 \sa organizationName applicationName applicationVersion
1928 void QCoreApplication::setOrganizationDomain(const QString &orgDomain)
1930 coreappdata()->orgDomain = orgDomain;
1933 QString QCoreApplication::organizationDomain()
1935 return coreappdata()->orgDomain;
1939 \property QCoreApplication::applicationName
1940 \brief the name of this application
1942 The value is used by the QSettings class when it is constructed
1943 using the empty constructor. This saves having to repeat this
1944 information each time a QSettings object is created.
1946 \sa organizationName organizationDomain applicationVersion
1948 void QCoreApplication::setApplicationName(const QString &application)
1950 coreappdata()->application = application;
1953 QString QCoreApplication::applicationName()
1955 return coreappdata()->application;
1959 \property QCoreApplication::applicationVersion
1961 \brief the version of this application
1963 \sa applicationName organizationName organizationDomain
1965 void QCoreApplication::setApplicationVersion(const QString &version)
1967 coreappdata()->applicationVersion = version;
1970 QString QCoreApplication::applicationVersion()
1972 return coreappdata()->applicationVersion;
1975 #ifndef QT_NO_LIBRARY
1977 Q_GLOBAL_STATIC_WITH_ARGS(QMutex, libraryPathMutex, (QMutex::Recursive))
1980 Returns a list of paths that the application will search when
1981 dynamically loading libraries.
1983 Qt provides default library paths, but they can also be set using
1984 a \l{Using qt.conf}{qt.conf} file. Paths specified in this file
1985 will override default values.
1987 This list will include the installation directory for plugins if
1988 it exists (the default installation directory for plugins is \c
1989 INSTALL/plugins, where \c INSTALL is the directory where Qt was
1990 installed). The directory of the application executable (NOT the
1991 working directory) is always added, as well as the colon separated
1992 entries of the QT_PLUGIN_PATH environment variable.
1994 If you want to iterate over the list, you can use the \l foreach
1997 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 2
1999 \sa setLibraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary,
2000 {How to Create Qt Plugins}
2002 QStringList QCoreApplication::libraryPaths()
2004 QMutexLocker locker(libraryPathMutex());
2005 if (!coreappdata()->app_libpaths) {
2006 QStringList *app_libpaths = coreappdata()->app_libpaths = new QStringList;
2007 QString installPathPlugins = QLibraryInfo::location(QLibraryInfo::PluginsPath);
2008 if (QFile::exists(installPathPlugins)) {
2009 // Make sure we convert from backslashes to slashes.
2010 installPathPlugins = QDir(installPathPlugins).canonicalPath();
2011 if (!app_libpaths->contains(installPathPlugins))
2012 app_libpaths->append(installPathPlugins);
2015 // If QCoreApplication is not yet instantiated,
2016 // make sure we add the application path when we construct the QCoreApplication
2017 if (self) self->d_func()->appendApplicationPathToLibraryPaths();
2019 const QByteArray libPathEnv = qgetenv("QT_PLUGIN_PATH");
2020 if (!libPathEnv.isEmpty()) {
2021 #if defined(Q_OS_WIN)
2022 QLatin1Char pathSep(';');
2024 QLatin1Char pathSep(':');
2026 QStringList paths = QString::fromLatin1(libPathEnv).split(pathSep, QString::SkipEmptyParts);
2027 for (QStringList::const_iterator it = paths.constBegin(); it != paths.constEnd(); ++it) {
2028 QString canonicalPath = QDir(*it).canonicalPath();
2029 if (!canonicalPath.isEmpty()
2030 && !app_libpaths->contains(canonicalPath)) {
2031 app_libpaths->append(canonicalPath);
2036 return *(coreappdata()->app_libpaths);
2043 Sets the list of directories to search when loading libraries to
2044 \a paths. All existing paths will be deleted and the path list
2045 will consist of the paths given in \a paths.
2047 \sa libraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary
2049 void QCoreApplication::setLibraryPaths(const QStringList &paths)
2051 QMutexLocker locker(libraryPathMutex());
2052 if (!coreappdata()->app_libpaths)
2053 coreappdata()->app_libpaths = new QStringList;
2054 *(coreappdata()->app_libpaths) = paths;
2056 QFactoryLoader::refreshAll();
2060 Prepends \a path to the beginning of the library path list, ensuring that
2061 it is searched for libraries first. If \a path is empty or already in the
2062 path list, the path list is not changed.
2064 The default path list consists of a single entry, the installation
2065 directory for plugins. The default installation directory for plugins
2066 is \c INSTALL/plugins, where \c INSTALL is the directory where Qt was
2069 \sa removeLibraryPath(), libraryPaths(), setLibraryPaths()
2071 void QCoreApplication::addLibraryPath(const QString &path)
2076 QMutexLocker locker(libraryPathMutex());
2078 // make sure that library paths is initialized
2081 QString canonicalPath = QDir(path).canonicalPath();
2082 if (!canonicalPath.isEmpty()
2083 && !coreappdata()->app_libpaths->contains(canonicalPath)) {
2084 coreappdata()->app_libpaths->prepend(canonicalPath);
2086 QFactoryLoader::refreshAll();
2091 Removes \a path from the library path list. If \a path is empty or not
2092 in the path list, the list is not changed.
2094 \sa addLibraryPath(), libraryPaths(), setLibraryPaths()
2096 void QCoreApplication::removeLibraryPath(const QString &path)
2101 QMutexLocker locker(libraryPathMutex());
2103 // make sure that library paths is initialized
2106 QString canonicalPath = QDir(path).canonicalPath();
2107 coreappdata()->app_libpaths->removeAll(canonicalPath);
2108 QFactoryLoader::refreshAll();
2111 #endif //QT_NO_LIBRARY
2114 \typedef QCoreApplication::EventFilter
2116 A function with the following signature that can be used as an
2119 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 3
2121 \sa setEventFilter()
2125 \fn EventFilter QCoreApplication::setEventFilter(EventFilter filter)
2127 Replaces the event filter function for the QCoreApplication with
2128 \a filter and returns the pointer to the replaced event filter
2129 function. Only the current event filter function is called. If you
2130 want to use both filter functions, save the replaced EventFilter
2131 in a place where yours can call it.
2133 The event filter function set here is called for all messages
2134 received by all threads meant for all Qt objects. It is \e not
2135 called for messages that are not meant for Qt objects.
2137 The event filter function should return true if the message should
2138 be filtered, (i.e. stopped). It should return false to allow
2139 processing the message to continue.
2141 By default, no event filter function is set (i.e., this function
2142 returns a null EventFilter the first time it is called).
2144 \note The filter function set here receives native messages,
2145 i.e. MSG or XEvent structs, that are going to Qt objects. It is
2146 called by QCoreApplication::filterEvent(). If the filter function
2147 returns false to indicate the message should be processed further,
2148 the native message can then be translated into a QEvent and
2149 handled by the standard Qt \l{QEvent} {event} filering, e.g.
2150 QObject::installEventFilter().
2152 \note The filter function set here is different form the filter
2153 function set via QAbstractEventDispatcher::setEventFilter(), which
2154 gets all messages received by its thread, even messages meant for
2155 objects that are not handled by Qt.
2157 \sa QObject::installEventFilter(), QAbstractEventDispatcher::setEventFilter()
2159 QCoreApplication::EventFilter
2160 QCoreApplication::setEventFilter(QCoreApplication::EventFilter filter)
2162 Q_D(QCoreApplication);
2163 EventFilter old = d->eventFilter;
2164 d->eventFilter = filter;
2169 Sends \a message through the event filter that was set by
2170 setEventFilter(). If no event filter has been set, this function
2171 returns false; otherwise, this function returns the result of the
2172 event filter function in the \a result parameter.
2174 \sa setEventFilter()
2176 bool QCoreApplication::filterEvent(void *message, long *result)
2178 Q_D(QCoreApplication);
2182 return d->eventFilter(message, result);
2184 return winEventFilter(reinterpret_cast<MSG *>(message), result);
2191 This function returns true if there are pending events; otherwise
2192 returns false. Pending events can be either from the window
2193 system or posted events using postEvent().
2195 \sa QAbstractEventDispatcher::hasPendingEvents()
2197 bool QCoreApplication::hasPendingEvents()
2199 QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance();
2200 if (eventDispatcher)
2201 return eventDispatcher->hasPendingEvents();
2206 Returns a pointer to the event dispatcher object for the main thread. If no
2207 event dispatcher exists for the thread, this function returns 0.
2209 QAbstractEventDispatcher *QCoreApplication::eventDispatcher()
2211 if (QCoreApplicationPrivate::theMainThread)
2212 return QCoreApplicationPrivate::theMainThread->eventDispatcher();
2217 Sets the event dispatcher for the main thread to \a eventDispatcher. This
2218 is only possible as long as there is no event dispatcher installed yet. That
2219 is, before QCoreApplication has been instantiated. This method takes
2220 ownership of the object.
2222 void QCoreApplication::setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
2224 QThread *mainThread = QCoreApplicationPrivate::theMainThread;
2226 mainThread = QThread::currentThread(); // will also setup theMainThread
2227 mainThread->setEventDispatcher(eventDispatcher);
2231 \fn void QCoreApplication::watchUnixSignal(int signal, bool watch)
2236 \fn void QCoreApplication::unixSignal(int number)
2239 This signal is emitted whenever a Unix signal is received by the
2240 application. The Unix signal received is specified by its \a number.
2244 \fn void qAddPostRoutine(QtCleanUpFunction ptr)
2245 \relates QCoreApplication
2247 Adds a global routine that will be called from the QApplication
2248 destructor. This function is normally used to add cleanup routines
2249 for program-wide functionality.
2251 The function specified by \a ptr should take no arguments and should
2252 return nothing. For example:
2254 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 4
2256 Note that for an application- or module-wide cleanup,
2257 qAddPostRoutine() is often not suitable. For example, if the
2258 program is split into dynamically loaded modules, the relevant
2259 module may be unloaded long before the QApplication destructor is
2262 For modules and libraries, using a reference-counted
2263 initialization manager or Qt's parent-child deletion mechanism may
2264 be better. Here is an example of a private class that uses the
2265 parent-child mechanism to call a cleanup function at the right
2268 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 5
2270 By selecting the right parent object, this can often be made to
2271 clean up the module's data at the right moment.
2275 \macro Q_DECLARE_TR_FUNCTIONS(context)
2276 \relates QCoreApplication
2278 The Q_DECLARE_TR_FUNCTIONS() macro declares and implements two
2279 translation functions, \c tr() and \c trUtf8(), with these
2282 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 6
2284 This macro is useful if you want to use QObject::tr() or
2285 QObject::trUtf8() in classes that don't inherit from QObject.
2287 Q_DECLARE_TR_FUNCTIONS() must appear at the very top of the
2288 class definition (before the first \c{public:} or \c{protected:}).
2291 \snippet doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp 7
2293 The \a context parameter is normally the class name, but it can
2296 \sa Q_OBJECT, QObject::tr(), QObject::trUtf8()
2300 \enum QCoreApplication::Type
2302 \value Tty a console application
2303 \value GuiClient a GUI application
2304 \value GuiServer \e{Deprecated.} this value is only left for compatibility.
2309 #include "moc_qcoreapplication.cpp"