e9003e8c14cafcaed336f2ac2ee7a75307175339
[profile/ivi/qtbase.git] / src / widgets / kernel / qapplication.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qplatformdefs.h"
43 #include "qabstracteventdispatcher.h"
44 #include "qaccessible.h"
45 #include "qapplication.h"
46 #include "qclipboard.h"
47 #include "qcursor.h"
48 #include "qdesktopwidget.h"
49 #include "qdir.h"
50 #include "qevent.h"
51 #include "qfile.h"
52 #include "qfileinfo.h"
53 #include "qgraphicsscene.h"
54 #include "qhash.h"
55 #include "qset.h"
56 #include "qlayout.h"
57 #include "qsessionmanager.h"
58 #include "qstyle.h"
59 #include "qstylefactory.h"
60 #include "qtextcodec.h"
61 #include "qtranslator.h"
62 #include "qvariant.h"
63 #include "qwidget.h"
64 #include "private/qdnd_p.h"
65 #include "private/qguiapplication_p.h"
66 #include "qcolormap.h"
67 #include "qdebug.h"
68 #include "private/qstylesheetstyle_p.h"
69 #include "private/qstyle_p.h"
70 #include "qmessagebox.h"
71 #include "qwidgetwindow_qpa_p.h"
72 #include <QtWidgets/qgraphicsproxywidget.h>
73 #include <QtGui/qstylehints.h>
74 #include <QtGui/qinputmethod.h>
75 #include <qpa/qplatformtheme.h>
76
77 #include "private/qkeymapper_p.h"
78
79 #include <qthread.h>
80 #include <private/qthread_p.h>
81
82 #include <private/qfont_p.h>
83
84 #include <stdlib.h>
85
86 #include "qapplication_p.h"
87 #include "private/qevent_p.h"
88 #include "qwidget_p.h"
89
90 #include "qapplication.h"
91
92 #include "qgesture.h"
93 #include "private/qgesturemanager_p.h"
94 #include "private/qguiapplication_p.h"
95 #include <qpa/qplatformfontdatabase.h>
96 #ifndef QT_NO_LIBRARY
97 #include "qlibrary.h"
98 #endif
99
100 #ifdef Q_OS_WINCE
101 #include "qdatetime.h"
102 extern bool qt_wince_is_smartphone(); //qguifunctions_wince.cpp
103 extern bool qt_wince_is_mobile();     //qguifunctions_wince.cpp
104 extern bool qt_wince_is_pocket_pc();  //qguifunctions_wince.cpp
105 #endif
106
107 #include "qdatetime.h"
108
109 //#define ALIEN_DEBUG
110
111 static void initResources()
112 {
113 #if defined(Q_OS_WINCE)
114     Q_INIT_RESOURCE_EXTERN(qstyle_wince)
115     Q_INIT_RESOURCE(qstyle_wince);
116 #else
117     Q_INIT_RESOURCE_EXTERN(qstyle)
118     Q_INIT_RESOURCE(qstyle);
119 #endif
120     Q_INIT_RESOURCE_EXTERN(qmessagebox)
121     Q_INIT_RESOURCE(qmessagebox);
122
123 }
124
125 QT_BEGIN_NAMESPACE
126
127 Q_CORE_EXPORT void qt_call_post_routines();
128
129 QApplicationPrivate *QApplicationPrivate::self = 0;
130
131 static void initSystemPalette()
132 {
133     if (!QApplicationPrivate::sys_pal) {
134         QPalette defaultPlatte;
135         if (QApplicationPrivate::app_style)
136             defaultPlatte = QApplicationPrivate::app_style->standardPalette();
137         if (const QPalette *themePalette = QGuiApplicationPrivate::platformTheme()->palette()) {
138             QApplicationPrivate::setSystemPalette(themePalette->resolve(defaultPlatte));
139             QApplicationPrivate::initializeWidgetPaletteHash();
140         } else {
141             QApplicationPrivate::setSystemPalette(defaultPlatte);
142         }
143     }
144 }
145
146 static void clearSystemPalette()
147 {
148     delete QApplicationPrivate::sys_pal;
149     QApplicationPrivate::sys_pal = 0;
150 }
151
152 #ifdef Q_OS_WINCE
153 int QApplicationPrivate::autoMaximizeThreshold = -1;
154 bool QApplicationPrivate::autoSipEnabled = false;
155 #else
156 bool QApplicationPrivate::autoSipEnabled = true;
157 #endif
158
159 QApplicationPrivate::QApplicationPrivate(int &argc, char **argv, QApplication::Type type, int flags)
160     : QApplicationPrivateBase(argc, argv, flags)
161 {
162     application_type = type;
163
164 #ifndef QT_NO_SESSIONMANAGER
165     is_session_restored = false;
166 #endif
167
168 #ifndef QT_NO_GESTURES
169     gestureManager = 0;
170     gestureWidget = 0;
171 #endif // QT_NO_GESTURES
172
173     if (!self)
174         self = this;
175 }
176
177 QApplicationPrivate::~QApplicationPrivate()
178 {
179     if (self == this)
180         self = 0;
181 }
182
183 /*!
184     \class QApplication
185     \brief The QApplication class manages the GUI application's control
186     flow and main settings.
187
188     \inmodule QtWidgets
189
190     QApplication specializes QGuiApplication with some functionality needed
191     for QWidget-based applications. It handles widget specific initialization,
192     finalization, and provides session management.
193
194     For any GUI application using Qt, there is precisely \b one QApplication
195     object, no matter whether the application has 0, 1, 2 or more windows at
196     any given time. For non-QWidget based Qt applications, use QGuiApplication instead,
197     as it does not depend on the \l QtWidgets library.
198
199     The QApplication object is accessible through the instance() function that
200     returns a pointer equivalent to the global qApp pointer.
201
202     QApplication's main areas of responsibility are:
203         \list
204             \li  It initializes the application with the user's desktop settings
205                 such as palette(), font() and doubleClickInterval(). It keeps
206                 track of these properties in case the user changes the desktop
207                 globally, for example through some kind of control panel.
208
209             \li  It performs event handling, meaning that it receives events
210                 from the underlying window system and dispatches them to the
211                 relevant widgets. By using sendEvent() and postEvent() you can
212                 send your own events to widgets.
213
214             \li  It parses common command line arguments and sets its internal
215                 state accordingly. See the \l{QApplication::QApplication()}
216                 {constructor documentation} below for more details.
217
218             \li  It defines the application's look and feel, which is
219                 encapsulated in a QStyle object. This can be changed at runtime
220                 with setStyle().
221
222             \li  It specifies how the application is to allocate colors. See
223                 setColorSpec() for details.
224
225             \li  It provides localization of strings that are visible to the
226                 user via translate().
227
228             \li  It provides some magical objects like the desktop() and the
229                 clipboard().
230
231             \li  It knows about the application's windows. You can ask which
232                 widget is at a certain position using widgetAt(), get a list of
233                 topLevelWidgets() and closeAllWindows(), etc.
234
235             \li  It manages the application's mouse cursor handling, see
236                 setOverrideCursor()
237
238             \li  It provides support for sophisticated \l{Session Management}
239                 {session management}. This makes it possible for applications
240                 to terminate gracefully when the user logs out, to cancel a
241                 shutdown process if termination isn't possible and even to
242                 preserve the entire application's state for a future session.
243                 See isSessionRestored(), sessionId() and commitData() and
244                 saveState() for details.
245         \endlist
246
247     Since the QApplication object does so much initialization, it \e{must} be
248     created before any other objects related to the user interface are created.
249     QApplication also deals with common command line arguments. Hence, it is
250     usually a good idea to create it \e before any interpretation or
251     modification of \c argv is done in the application itself.
252
253     \table
254     \header
255         \li{2,1} Groups of functions
256
257         \row
258         \li  System settings
259         \li  desktopSettingsAware(),
260             setDesktopSettingsAware(),
261             cursorFlashTime(),
262             setCursorFlashTime(),
263             doubleClickInterval(),
264             setDoubleClickInterval(),
265             setKeyboardInputInterval(),
266             wheelScrollLines(),
267             setWheelScrollLines(),
268             palette(),
269             setPalette(),
270             font(),
271             setFont(),
272             fontMetrics().
273
274         \row
275         \li  Event handling
276         \li  exec(),
277             processEvents(),
278             exit(),
279             quit().
280             sendEvent(),
281             postEvent(),
282             sendPostedEvents(),
283             removePostedEvents(),
284             hasPendingEvents(),
285             notify().
286
287         \row
288         \li  GUI Styles
289         \li  style(),
290             setStyle().
291
292         \row
293         \li  Color usage
294         \li  colorSpec(),
295             setColorSpec().
296
297         \row
298         \li  Text handling
299         \li  installTranslator(),
300             removeTranslator()
301             translate().
302
303         \row
304         \li  Widgets
305         \li  allWidgets(),
306             topLevelWidgets(),
307             desktop(),
308             activePopupWidget(),
309             activeModalWidget(),
310             clipboard(),
311             focusWidget(),
312             activeWindow(),
313             widgetAt().
314
315         \row
316         \li  Advanced cursor handling
317         \li  overrideCursor(),
318             setOverrideCursor(),
319             restoreOverrideCursor().
320
321         \row
322         \li  Session management
323         \li  isSessionRestored(),
324             sessionId(),
325             commitData(),
326             saveState().
327
328         \row
329         \li  Miscellaneous
330         \li  closeAllWindows(),
331             startingUp(),
332             closingDown(),
333             type().
334     \endtable
335
336     \sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
337 */
338
339 /*!
340     \enum QApplication::ColorSpec
341
342     \value NormalColor the default color allocation policy
343     \value CustomColor the same as NormalColor for X11; allocates colors
344     to a palette on demand under Windows
345     \value ManyColor the right choice for applications that use thousands of
346     colors
347
348     See setColorSpec() for full details.
349 */
350
351 /*!
352     \fn QWidget *QApplication::topLevelAt(const QPoint &point)
353
354     Returns the top-level widget at the given \a point; returns 0 if
355     there is no such widget.
356 */
357
358 /*!
359     \fn QWidget *QApplication::topLevelAt(int x, int y)
360
361     \overload
362
363     Returns the top-level widget at the point (\a{x}, \a{y}); returns
364     0 if there is no such widget.
365 */
366
367
368 /*
369     The qt_init() and qt_cleanup() functions are implemented in the
370     qapplication_xyz.cpp file.
371 */
372
373 void qt_init(QApplicationPrivate *priv, int type
374    );
375 void qt_cleanup();
376
377 QStyle *QApplicationPrivate::app_style = 0;        // default application style
378 QString QApplicationPrivate::styleOverride;        // style override
379
380 #ifndef QT_NO_STYLE_STYLESHEET
381 QString QApplicationPrivate::styleSheet;           // default application stylesheet
382 #endif
383 QPointer<QWidget> QApplicationPrivate::leaveAfterRelease = 0;
384
385 int QApplicationPrivate::app_cspec = QApplication::NormalColor;
386
387 QPalette *QApplicationPrivate::sys_pal = 0;        // default system palette
388 QPalette *QApplicationPrivate::set_pal = 0;        // default palette set by programmer
389
390 QFont *QApplicationPrivate::sys_font = 0;        // default system font
391 QFont *QApplicationPrivate::set_font = 0;        // default font set by programmer
392
393 QIcon *QApplicationPrivate::app_icon = 0;
394 QWidget *QApplicationPrivate::main_widget = 0;        // main application widget
395 QWidget *QApplicationPrivate::focus_widget = 0;        // has keyboard input focus
396 QWidget *QApplicationPrivate::hidden_focus_widget = 0; // will get keyboard input focus after show()
397 QWidget *QApplicationPrivate::active_window = 0;        // toplevel with keyboard focus
398 #ifndef QT_NO_WHEELEVENT
399 int QApplicationPrivate::wheel_scroll_lines;   // number of lines to scroll
400 #endif
401 bool Q_WIDGETS_EXPORT qt_tab_all_widgets = true;
402 bool qt_in_tab_key_event = false;
403 int qt_antialiasing_threshold = -1;
404 QSize QApplicationPrivate::app_strut = QSize(0,0); // no default application strut
405 int QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
406 bool QApplicationPrivate::widgetCount = false;
407 bool QApplicationPrivate::load_testability = false;
408 #ifdef QT_KEYPAD_NAVIGATION
409 Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadTabOrder;
410 QWidget *QApplicationPrivate::oldEditFocus = 0;
411 #endif
412
413 bool qt_tabletChokeMouse = false;
414
415 inline bool QApplicationPrivate::isAlien(QWidget *widget)
416 {
417     return widget && !widget->isWindow();
418 }
419
420 // ######## move to QApplicationPrivate
421 // Default application palettes and fonts (per widget type)
422 Q_GLOBAL_STATIC(PaletteHash, app_palettes)
423 PaletteHash *qt_app_palettes_hash()
424 {
425     return app_palettes();
426 }
427
428 Q_GLOBAL_STATIC(FontHash, app_fonts)
429 FontHash *qt_app_fonts_hash()
430 {
431     return app_fonts();
432 }
433
434 QWidgetList *QApplicationPrivate::popupWidgets = 0;        // has keyboard input focus
435
436 QDesktopWidget *qt_desktopWidget = 0;                // root window widgets
437
438 /*!
439     \internal
440 */
441 void QApplicationPrivate::process_cmdline()
442 {
443     // process platform-indep command line
444     if (!qt_is_gui_used || !argc)
445         return;
446
447     int i, j;
448
449     j = 1;
450     for (i=1; i<argc; i++) { // if you add anything here, modify QCoreApplication::arguments()
451         if (argv[i] && *argv[i] != '-') {
452             argv[j++] = argv[i];
453             continue;
454         }
455         QByteArray arg = argv[i];
456         arg = arg;
457         QString s;
458         if (arg == "-qdevel" || arg == "-qdebug") {
459             // obsolete argument
460         } else if (arg.indexOf("-style=", 0) != -1) {
461             s = QString::fromLocal8Bit(arg.right(arg.length() - 7).toLower());
462         } else if (arg == "-style" && i < argc-1) {
463             s = QString::fromLocal8Bit(argv[++i]).toLower();
464 #ifndef QT_NO_SESSIONMANAGER
465         } else if (arg == "-session" && i < argc-1) {
466             ++i;
467             if (argv[i] && *argv[i]) {
468                 session_id = QString::fromLatin1(argv[i]);
469                 int p = session_id.indexOf(QLatin1Char('_'));
470                 if (p >= 0) {
471                     session_key = session_id.mid(p +1);
472                     session_id = session_id.left(p);
473                 }
474                 is_session_restored = true;
475             }
476 #endif
477 #ifndef QT_NO_STYLE_STYLESHEET
478         } else if (arg == "-stylesheet" && i < argc -1) {
479             styleSheet = QLatin1String("file:///");
480             styleSheet.append(QString::fromLocal8Bit(argv[++i]));
481         } else if (arg.indexOf("-stylesheet=") != -1) {
482             styleSheet = QLatin1String("file:///");
483             styleSheet.append(QString::fromLocal8Bit(arg.right(arg.length() - 12)));
484 #endif
485         } else if (qstrcmp(arg, "-widgetcount") == 0) {
486             widgetCount = true;
487         } else if (qstrcmp(arg, "-testability") == 0) {
488             load_testability = true;
489         } else {
490             argv[j++] = argv[i];
491         }
492         if (!s.isEmpty()) {
493             if (app_style) {
494                 delete app_style;
495                 app_style = 0;
496             }
497             styleOverride = s;
498         }
499     }
500
501     if(j < argc) {
502         argv[j] = 0;
503         argc = j;
504     }
505 }
506
507 /*!
508     Initializes the window system and constructs an application object with
509     \a argc command line arguments in \a argv.
510
511     \warning The data referred to by \a argc and \a argv must stay valid for
512     the entire lifetime of the QApplication object. In addition, \a argc must
513     be greater than zero and \a argv must contain at least one valid character
514     string.
515
516     The global \c qApp pointer refers to this application object. Only one
517     application object should be created.
518
519     This application object must be constructed before any \l{QPaintDevice}
520     {paint devices} (including widgets, pixmaps, bitmaps etc.).
521
522     \note \a argc and \a argv might be changed as Qt removes command line
523     arguments that it recognizes.
524
525     All Qt programs automatically support the following command line options:
526     \list
527         \li  -style= \e style, sets the application GUI style. Possible values
528             are \c motif, \c windows, and \c platinum. If you compiled Qt with
529             additional styles or have additional styles as plugins these will
530             be available to the \c -style command line option.
531         \li  -style \e style, is the same as listed above.
532         \li  -stylesheet= \e stylesheet, sets the application \l styleSheet. The
533             value must be a path to a file that contains the Style Sheet.
534             \note Relative URLs in the Style Sheet file are relative to the
535             Style Sheet file's path.
536         \li  -stylesheet \e stylesheet, is the same as listed above.
537         \li  -session= \e session, restores the application from an earlier
538             \l{Session Management}{session}.
539         \li  -session \e session, is the same as listed above.
540         \li  -widgetcount, prints debug message at the end about number of
541             widgets left undestroyed and maximum number of widgets existed at
542             the same time
543         \li  -reverse, sets the application's layout direction to
544             Qt::RightToLeft
545         \li  -qmljsdebugger=, activates the QML/JS debugger with a specified port.
546             The value must be of format port:1234[,block], where block is optional
547             and will make the application wait until a debugger connects to it.
548     \endlist
549
550     \sa arguments()
551 */
552
553 QApplication::QApplication(int &argc, char **argv, int _internal)
554     : QGuiApplication(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
555 { Q_D(QApplication); d->construct(); }
556
557
558 /*!
559     Constructs an application object with \a argc command line arguments in
560     \a argv.
561
562     \warning The data referred to by \a argc and \a argv must stay valid for
563     the entire lifetime of the QApplication object. In addition, \a argc must
564     be greater than zero and \a argv must contain at least one valid character
565     string.
566
567     The following example shows how to create an application that uses a
568     graphical interface when available.
569
570     \obsolete
571
572     \snippet code/src_gui_kernel_qapplication.cpp 0
573 */
574
575 QApplication::QApplication(int &argc, char **argv, bool GUIenabled , int _internal)
576     : QGuiApplication(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, _internal))
577 { Q_D(QApplication); d->construct();}
578
579
580
581 /*!
582     Constructs an application object with \a argc command line arguments in
583     \a argv.
584
585     \warning The data referred to by \a argc and \a argv must stay valid for
586     the entire lifetime of the QApplication object. In addition, \a argc must
587     be greater than zero and \a argv must contain at least one valid character
588     string.
589 */
590 QApplication::QApplication(int &argc, char **argv, Type type , int _internal)
591     : QGuiApplication(*new QApplicationPrivate(argc, argv, type, _internal))
592 { Q_D(QApplication); d->construct(); }
593
594 /*!
595     \internal
596 */
597 void QApplicationPrivate::construct()
598 {
599     initResources();
600
601     qt_is_gui_used = (application_type != QApplication::Tty);
602     process_cmdline();
603
604     // Must be called before initialize()
605     qt_init(this, application_type);
606     initialize();
607     eventDispatcher->startingUp();
608
609 #ifdef QT_EVAL
610     extern void qt_gui_eval_init(uint);
611     qt_gui_eval_init(application_type);
612 #endif
613
614 #ifndef QT_NO_LIBRARY
615     if(load_testability) {
616         QLibrary testLib(QLatin1String("qttestability"));
617         if (testLib.load()) {
618             typedef void (*TasInitialize)(void);
619             TasInitialize initFunction = (TasInitialize)testLib.resolve("qt_testability_init");
620             if (initFunction) {
621                 initFunction();
622             } else {
623                 qCritical("Library qttestability resolve failed!");
624             }
625         } else {
626             qCritical("Library qttestability load failed!");
627         }
628     }
629 #endif
630 }
631
632 #ifndef QT_NO_STATEMACHINE
633 void qRegisterGuiStateMachine();
634 void qUnregisterGuiStateMachine();
635 #endif
636
637 /*!
638   \fn void QApplicationPrivate::initialize()
639
640   Initializes the QApplication object, called from the constructors.
641 */
642 void QApplicationPrivate::initialize()
643 {
644     QWidgetPrivate::mapper = new QWidgetMapper;
645     QWidgetPrivate::allWidgets = new QWidgetSet;
646
647     if (application_type != QApplication::Tty)
648         (void) QApplication::style();  // trigger creation of application style
649 #ifndef QT_NO_STATEMACHINE
650     // trigger registering of QStateMachine's GUI types
651     qRegisterGuiStateMachine();
652 #endif
653
654     is_app_running = true; // no longer starting up
655
656     Q_Q(QApplication);
657 #ifndef QT_NO_SESSIONMANAGER
658     // connect to the session manager
659     session_manager = new QSessionManager(q, session_id, session_key);
660 #endif
661
662     if (qgetenv("QT_USE_NATIVE_WINDOWS").toInt() > 0)
663         q->setAttribute(Qt::AA_NativeWindows);
664
665 #ifdef Q_OS_WINCE
666 #ifdef QT_AUTO_MAXIMIZE_THRESHOLD
667     autoMaximizeThreshold = QT_AUTO_MAXIMIZE_THRESHOLD;
668 #else
669     if (qt_wince_is_mobile())
670         autoMaximizeThreshold = 50;
671     else
672         autoMaximizeThreshold = -1;
673 #endif //QT_AUTO_MAXIMIZE_THRESHOLD
674 #endif //Q_OS_WINCE
675
676 #ifndef QT_NO_WHEELEVENT
677     QApplicationPrivate::wheel_scroll_lines = 3;
678 #endif
679
680     if (qt_is_gui_used)
681         initializeMultitouch();
682
683     if (QApplication::desktopSettingsAware())
684         if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
685             QApplicationPrivate::enabledAnimations = theme->themeHint(QPlatformTheme::UiEffects).toInt();
686 }
687
688 /*!
689     Returns the type of application (\l Tty, GuiClient, or
690     GuiServer). The type is set when constructing the QApplication
691     object.
692 */
693 QApplication::Type QApplication::type()
694 {
695     if (QApplicationPrivate::instance())
696         return (QCoreApplication::Type)QApplicationPrivate::instance()->application_type;
697     return Tty;
698 }
699
700 /*****************************************************************************
701   Functions returning the active popup and modal widgets.
702  *****************************************************************************/
703
704 /*!
705     Returns the active popup widget.
706
707     A popup widget is a special top-level widget that sets the \c
708     Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application
709     opens a popup widget, all events are sent to the popup. Normal widgets and
710     modal widgets cannot be accessed before the popup widget is closed.
711
712     Only other popup widgets may be opened when a popup widget is shown. The
713     popup widgets are organized in a stack. This function returns the active
714     popup widget at the top of the stack.
715
716     \sa activeModalWidget(), topLevelWidgets()
717 */
718
719 QWidget *QApplication::activePopupWidget()
720 {
721     return QApplicationPrivate::popupWidgets && !QApplicationPrivate::popupWidgets->isEmpty() ?
722         QApplicationPrivate::popupWidgets->last() : 0;
723 }
724
725
726 /*!
727     Returns the active modal widget.
728
729     A modal widget is a special top-level widget which is a subclass of QDialog
730     that specifies the modal parameter of the constructor as true. A modal
731     widget must be closed before the user can continue with other parts of the
732     program.
733
734     Modal widgets are organized in a stack. This function returns the active
735     modal widget at the top of the stack.
736
737     \sa activePopupWidget(), topLevelWidgets()
738 */
739
740 QWidget *QApplication::activeModalWidget()
741 {
742     QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(modalWindow());
743     return widgetWindow ? widgetWindow->widget() : 0;
744 }
745
746 /*!
747     Cleans up any window system resources that were allocated by this
748     application. Sets the global variable \c qApp to 0.
749 */
750
751 QApplication::~QApplication()
752 {
753     Q_D(QApplication);
754
755     //### this should probable be done even later
756     qt_call_post_routines();
757
758     // kill timers before closing down the dispatcher
759     d->toolTipWakeUp.stop();
760     d->toolTipFallAsleep.stop();
761
762     QApplicationPrivate::is_app_closing = true;
763     QApplicationPrivate::is_app_running = false;
764
765     delete QWidgetPrivate::mapper;
766     QWidgetPrivate::mapper = 0;
767
768     // delete all widgets
769     if (QWidgetPrivate::allWidgets) {
770         QWidgetSet *mySet = QWidgetPrivate::allWidgets;
771         QWidgetPrivate::allWidgets = 0;
772         for (QWidgetSet::ConstIterator it = mySet->constBegin(); it != mySet->constEnd(); ++it) {
773             register QWidget *w = *it;
774             if (!w->parent())                        // window
775                 w->destroy(true, true);
776         }
777         delete mySet;
778     }
779
780     delete qt_desktopWidget;
781     qt_desktopWidget = 0;
782
783     delete QApplicationPrivate::app_pal;
784     QApplicationPrivate::app_pal = 0;
785     clearSystemPalette();
786     delete QApplicationPrivate::set_pal;
787     QApplicationPrivate::set_pal = 0;
788     app_palettes()->clear();
789
790     delete QApplicationPrivate::sys_font;
791     QApplicationPrivate::sys_font = 0;
792     delete QApplicationPrivate::set_font;
793     QApplicationPrivate::set_font = 0;
794     app_fonts()->clear();
795
796     delete QApplicationPrivate::app_style;
797     QApplicationPrivate::app_style = 0;
798     delete QApplicationPrivate::app_icon;
799     QApplicationPrivate::app_icon = 0;
800
801 #ifndef QT_NO_DRAGANDDROP
802     if (qt_is_gui_used)
803         delete QDragManager::self();
804 #endif
805
806     d->cleanupMultitouch();
807
808     qt_cleanup();
809
810     if (QApplicationPrivate::widgetCount)
811         qDebug("Widgets left: %i    Max widgets: %i \n", QWidgetPrivate::instanceCounter, QWidgetPrivate::maxInstances);
812 #ifndef QT_NO_SESSIONMANAGER
813     delete d->session_manager;
814     d->session_manager = 0;
815 #endif //QT_NO_SESSIONMANAGER
816
817     QApplicationPrivate::obey_desktop_settings = true;
818
819     QApplicationPrivate::app_strut = QSize(0, 0);
820     QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
821     QApplicationPrivate::widgetCount = false;
822
823 #ifndef QT_NO_STATEMACHINE
824     // trigger unregistering of QStateMachine's GUI types
825     qUnregisterGuiStateMachine();
826 #endif
827 }
828
829
830 /*!
831     \fn QWidget *QApplication::widgetAt(const QPoint &point)
832
833     Returns the widget at global screen position \a point, or 0 if there is no
834     Qt widget there.
835
836     This function can be slow.
837
838     \sa QCursor::pos(), QWidget::grabMouse(), QWidget::grabKeyboard()
839 */
840 QWidget *QApplication::widgetAt(const QPoint &p)
841 {
842     QWidget *window = QApplication::topLevelAt(p);
843     if (!window)
844         return 0;
845
846     QWidget *child = 0;
847
848     if (!window->testAttribute(Qt::WA_TransparentForMouseEvents))
849         child = window->childAt(window->mapFromGlobal(p));
850
851     if (child)
852         return child;
853
854     if (window->testAttribute(Qt::WA_TransparentForMouseEvents)) {
855         //shoot a hole in the widget and try once again,
856         //suboptimal on Qt for Embedded Linux where we do
857         //know the stacking order of the toplevels.
858         int x = p.x();
859         int y = p.y();
860         QRegion oldmask = window->mask();
861         QPoint wpoint = window->mapFromGlobal(QPoint(x, y));
862         QRegion newmask = (oldmask.isEmpty() ? QRegion(window->rect()) : oldmask)
863                           - QRegion(wpoint.x(), wpoint.y(), 1, 1);
864         window->setMask(newmask);
865         QWidget *recurse = 0;
866         if (QApplication::topLevelAt(p) != window) // verify recursion will terminate
867             recurse = widgetAt(x, y);
868         if (oldmask.isEmpty())
869             window->clearMask();
870         else
871             window->setMask(oldmask);
872         return recurse;
873     }
874     return window;
875 }
876
877 /*!
878     \fn QWidget *QApplication::widgetAt(int x, int y)
879
880     \overload
881
882     Returns the widget at global screen position (\a x, \a y), or 0 if there is
883     no Qt widget there.
884 */
885
886 /*!
887     \fn void QApplication::setArgs(int argc, char **argv)
888     \internal
889 */
890
891
892
893 /*!
894     \internal
895 */
896 bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
897 {
898     if ((event->type() == QEvent::UpdateRequest
899           || event->type() == QEvent::LayoutRequest
900           || event->type() == QEvent::Resize
901           || event->type() == QEvent::Move
902           || event->type() == QEvent::LanguageChange
903           || event->type() == QEvent::UpdateSoftKeys
904           || event->type() == QEvent::InputMethod)) {
905         for (QPostEventList::const_iterator it = postedEvents->constBegin(); it != postedEvents->constEnd(); ++it) {
906             const QPostEvent &cur = *it;
907             if (cur.receiver != receiver || cur.event == 0 || cur.event->type() != event->type())
908                 continue;
909             if (cur.event->type() == QEvent::LayoutRequest
910                  || cur.event->type() == QEvent::UpdateRequest) {
911                 ;
912             } else if (cur.event->type() == QEvent::Resize) {
913                 ((QResizeEvent *)(cur.event))->s = ((QResizeEvent *)event)->s;
914             } else if (cur.event->type() == QEvent::Move) {
915                 ((QMoveEvent *)(cur.event))->p = ((QMoveEvent *)event)->p;
916             } else if (cur.event->type() == QEvent::LanguageChange) {
917                 ;
918             } else if (cur.event->type() == QEvent::UpdateSoftKeys) {
919                 ;
920             } else if ( cur.event->type() == QEvent::InputMethod ) {
921                 *(QInputMethodEvent *)(cur.event) = *(QInputMethodEvent *)event;
922             } else {
923                 continue;
924             }
925             delete event;
926             return true;
927         }
928         return false;
929     }
930     return QGuiApplication::compressEvent(event, receiver, postedEvents);
931 }
932
933 /*!
934     \property QApplication::styleSheet
935     \brief the application style sheet
936     \since 4.2
937
938     By default, this property returns an empty string unless the user specifies
939     the \c{-stylesheet} option on the command line when running the application.
940
941     \sa QWidget::setStyle(), {Qt Style Sheets}
942 */
943
944 /*!
945     \property QApplication::autoMaximizeThreshold
946     \since 4.4
947     \brief defines a threshold for auto maximizing widgets
948
949     \b{The auto maximize threshold is only available as part of Qt for
950     Windows CE.}
951
952     This property defines a threshold for the size of a window as a percentage
953     of the screen size. If the minimum size hint of a window exceeds the
954     threshold, calling show() will cause the window to be maximized
955     automatically.
956
957     Setting the threshold to 100 or greater means that the widget will always
958     be maximized. Alternatively, setting the threshold to 50 means that the
959     widget will be maximized only if the vertical minimum size hint is at least
960     50% of the vertical screen size.
961
962     Setting the threshold to -1 disables the feature.
963
964     On Windows CE the default is -1 (i.e., it is disabled).
965     On Windows Mobile the default is 40.
966 */
967
968 /*!
969     \property QApplication::autoSipEnabled
970     \since 4.5
971     \brief toggles automatic SIP (software input panel) visibility
972
973     Set this property to \c true to automatically display the SIP when entering
974     widgets that accept keyboard input. This property only affects widgets with
975     the WA_InputMethodEnabled attribute set, and is typically used to launch
976     a virtual keyboard on devices which have very few or no keys.
977
978     \b{ The property only has an effect on platforms which use software input
979     panels, such as Windows CE.}
980
981     The default is platform dependent.
982 */
983
984 #ifdef Q_OS_WINCE
985 void QApplication::setAutoMaximizeThreshold(const int threshold)
986 {
987     QApplicationPrivate::autoMaximizeThreshold = threshold;
988 }
989
990 int QApplication::autoMaximizeThreshold() const
991 {
992     return QApplicationPrivate::autoMaximizeThreshold;
993 }
994 #endif
995
996 void QApplication::setAutoSipEnabled(const bool enabled)
997 {
998     QApplicationPrivate::autoSipEnabled = enabled;
999 }
1000
1001 bool QApplication::autoSipEnabled() const
1002 {
1003     return QApplicationPrivate::autoSipEnabled;
1004 }
1005
1006 #ifndef QT_NO_STYLE_STYLESHEET
1007
1008 QString QApplication::styleSheet() const
1009 {
1010     return QApplicationPrivate::styleSheet;
1011 }
1012
1013 void QApplication::setStyleSheet(const QString& styleSheet)
1014 {
1015     QApplicationPrivate::styleSheet = styleSheet;
1016     QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle*>(QApplicationPrivate::app_style);
1017     if (styleSheet.isEmpty()) { // application style sheet removed
1018         if (!proxy)
1019             return; // there was no stylesheet before
1020         setStyle(proxy->base);
1021     } else if (proxy) { // style sheet update, just repolish
1022         proxy->repolish(qApp);
1023     } else { // stylesheet set the first time
1024         QStyleSheetStyle *newProxy = new QStyleSheetStyle(QApplicationPrivate::app_style);
1025         QApplicationPrivate::app_style->setParent(newProxy);
1026         setStyle(newProxy);
1027     }
1028 }
1029
1030 #endif // QT_NO_STYLE_STYLESHEET
1031
1032 /*!
1033     Returns the application's style object.
1034
1035     \sa setStyle(), QStyle
1036 */
1037 QStyle *QApplication::style()
1038 {
1039     if (QApplicationPrivate::app_style)
1040         return QApplicationPrivate::app_style;
1041     if (qApp->type() == QApplication::Tty) {
1042         Q_ASSERT(!"No style available in non-gui applications!");
1043         return 0;
1044     }
1045
1046     if (!QApplicationPrivate::app_style) {
1047         // Compile-time search for default style
1048         //
1049         QString style;
1050 #ifdef QT_BUILD_INTERNAL
1051         QString envStyle = QString::fromLocal8Bit(qgetenv("QT_STYLE_OVERRIDE"));
1052 #else
1053         QString envStyle;
1054 #endif
1055         if (!QApplicationPrivate::styleOverride.isEmpty()) {
1056             style = QApplicationPrivate::styleOverride;
1057         } else if (!envStyle.isEmpty()) {
1058             style = envStyle;
1059         } else {
1060             style = QApplicationPrivate::desktopStyleKey();
1061         }
1062
1063         QStyle *&app_style = QApplicationPrivate::app_style;
1064         app_style = QStyleFactory::create(style);
1065         if (!app_style) {
1066             QStringList styles = QStyleFactory::keys();
1067             for (int i = 0; i < styles.size(); ++i) {
1068                 if ((app_style = QStyleFactory::create(styles.at(i))))
1069                     break;
1070             }
1071         }
1072         if (!app_style) {
1073             Q_ASSERT(!"No styles available!");
1074             return 0;
1075         }
1076     }
1077     // take ownership of the style
1078     QApplicationPrivate::app_style->setParent(qApp);
1079
1080     initSystemPalette();
1081
1082     if (QApplicationPrivate::set_pal) // repolish set palette with the new style
1083         QApplication::setPalette(*QApplicationPrivate::set_pal);
1084
1085 #ifndef QT_NO_STYLE_STYLESHEET
1086     if (!QApplicationPrivate::styleSheet.isEmpty()) {
1087         qApp->setStyleSheet(QApplicationPrivate::styleSheet);
1088     } else
1089 #endif
1090         QApplicationPrivate::app_style->polish(qApp);
1091
1092     return QApplicationPrivate::app_style;
1093 }
1094
1095 /*!
1096     Sets the application's GUI style to \a style. Ownership of the style object
1097     is transferred to QApplication, so QApplication will delete the style
1098     object on application exit or when a new style is set and the old style is
1099     still the parent of the application object.
1100
1101     Example usage:
1102     \snippet code/src_gui_kernel_qapplication.cpp 1
1103
1104     When switching application styles, the color palette is set back to the
1105     initial colors or the system defaults. This is necessary since certain
1106     styles have to adapt the color palette to be fully style-guide compliant.
1107
1108     Setting the style before a palette has been se, i.e., before creating
1109     QApplication, will cause the application to use QStyle::standardPalette()
1110     for the palette.
1111
1112     \warning Qt style sheets are currently not supported for custom QStyle
1113     subclasses. We plan to address this in some future release.
1114
1115     \sa style(), QStyle, setPalette(), desktopSettingsAware()
1116 */
1117 void QApplication::setStyle(QStyle *style)
1118 {
1119     if (!style || style == QApplicationPrivate::app_style)
1120         return;
1121
1122     QWidgetList all = allWidgets();
1123
1124     // clean up the old style
1125     if (QApplicationPrivate::app_style) {
1126         if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1127             for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1128                 register QWidget *w = *it;
1129                 if (!(w->windowType() == Qt::Desktop) &&        // except desktop
1130                      w->testAttribute(Qt::WA_WState_Polished)) { // has been polished
1131                     QApplicationPrivate::app_style->unpolish(w);
1132                 }
1133             }
1134         }
1135         QApplicationPrivate::app_style->unpolish(qApp);
1136     }
1137
1138     QStyle *old = QApplicationPrivate::app_style; // save
1139
1140 #ifndef QT_NO_STYLE_STYLESHEET
1141     if (!QApplicationPrivate::styleSheet.isEmpty() && !qobject_cast<QStyleSheetStyle *>(style)) {
1142         // we have a stylesheet already and a new style is being set
1143         QStyleSheetStyle *newProxy = new QStyleSheetStyle(style);
1144         style->setParent(newProxy);
1145         QApplicationPrivate::app_style = newProxy;
1146     } else
1147 #endif // QT_NO_STYLE_STYLESHEET
1148         QApplicationPrivate::app_style = style;
1149     QApplicationPrivate::app_style->setParent(qApp); // take ownership
1150
1151     // take care of possible palette requirements of certain gui
1152     // styles. Do it before polishing the application since the style
1153     // might call QApplication::setPalette() itself
1154     if (QApplicationPrivate::set_pal) {
1155         QApplication::setPalette(*QApplicationPrivate::set_pal);
1156     } else if (QApplicationPrivate::sys_pal) {
1157         QApplicationPrivate::initializeWidgetPaletteHash();
1158         QApplicationPrivate::setPalette_helper(*QApplicationPrivate::sys_pal, /*className=*/0, /*clearWidgetPaletteHash=*/false);
1159     } else if (!QApplicationPrivate::sys_pal) {
1160         // Initialize the sys_pal if it hasn't happened yet...
1161         QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
1162     }
1163
1164     // initialize the application with the new style
1165     QApplicationPrivate::app_style->polish(qApp);
1166
1167     // re-polish existing widgets if necessary
1168     if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1169         for (QWidgetList::ConstIterator it1 = all.constBegin(); it1 != all.constEnd(); ++it1) {
1170             register QWidget *w = *it1;
1171             if (w->windowType() != Qt::Desktop && w->testAttribute(Qt::WA_WState_Polished)) {
1172                 if (w->style() == QApplicationPrivate::app_style)
1173                     QApplicationPrivate::app_style->polish(w);                // repolish
1174 #ifndef QT_NO_STYLE_STYLESHEET
1175                 else
1176                     w->setStyleSheet(w->styleSheet()); // touch
1177 #endif
1178             }
1179         }
1180
1181         for (QWidgetList::ConstIterator it2 = all.constBegin(); it2 != all.constEnd(); ++it2) {
1182             register QWidget *w = *it2;
1183             if (w->windowType() != Qt::Desktop && !w->testAttribute(Qt::WA_SetStyle)) {
1184                     QEvent e(QEvent::StyleChange);
1185                     QApplication::sendEvent(w, &e);
1186                     w->update();
1187             }
1188         }
1189     }
1190
1191 #ifndef QT_NO_STYLE_STYLESHEET
1192     if (QStyleSheetStyle *oldProxy = qobject_cast<QStyleSheetStyle *>(old)) {
1193         oldProxy->deref();
1194     } else
1195 #endif
1196     if (old && old->parent() == qApp) {
1197         delete old;
1198     }
1199
1200     if (QApplicationPrivate::focus_widget) {
1201         QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
1202         QApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
1203         QApplicationPrivate::focus_widget->update();
1204     }
1205 }
1206
1207 /*!
1208     \overload
1209
1210     Requests a QStyle object for \a style from the QStyleFactory.
1211
1212     The string must be one of the QStyleFactory::keys(), typically one of
1213     "windows", "motif", "cde", "plastique", "windowsxp", or "macintosh". Style
1214     names are case insensitive.
1215
1216     Returns 0 if an unknown \a style is passed, otherwise the QStyle object
1217     returned is set as the application's GUI style.
1218
1219     \warning To ensure that the application's style is set correctly, it is
1220     best to call this function before the QApplication constructor, if
1221     possible.
1222 */
1223 QStyle* QApplication::setStyle(const QString& style)
1224 {
1225     QStyle *s = QStyleFactory::create(style);
1226     if (!s)
1227         return 0;
1228
1229     setStyle(s);
1230     return s;
1231 }
1232
1233 /*!
1234     Returns the color specification.
1235
1236     \sa QApplication::setColorSpec()
1237 */
1238
1239 int QApplication::colorSpec()
1240 {
1241     return QApplicationPrivate::app_cspec;
1242 }
1243
1244 /*!
1245     Sets the color specification for the application to \a spec.
1246
1247     The color specification controls how the application allocates colors when
1248     run on a display with a limited amount of colors, e.g. 8 bit / 256 color
1249     displays.
1250
1251     The color specification must be set before you create the QApplication
1252     object.
1253
1254     The options are:
1255     \list
1256         \li  QApplication::NormalColor. This is the default color allocation
1257             strategy. Use this option if your application uses buttons, menus,
1258             texts and pixmaps with few colors. With this option, the
1259             application uses system global colors. This works fine for most
1260             applications under X11, but on the Windows platform, it may cause
1261             dithering of non-standard colors.
1262         \li  QApplication::CustomColor. Use this option if your application
1263             needs a small number of custom colors. On X11, this option is the
1264             same as NormalColor. On Windows, Qt creates a Windows palette, and
1265             allocates colors to it on demand.
1266         \li  QApplication::ManyColor. Use this option if your application is
1267             very color hungry, e.g., it requires thousands of colors. \br
1268             Under X11 the effect is:
1269             \list
1270                 \li  For 256-color displays which have at best a 256 color true
1271                     color visual, the default visual is used, and colors are
1272                     allocated from a color cube. The color cube is the 6x6x6
1273                     (216 color) "Web palette" (the red, green, and blue
1274                     components always have one of the following values: 0x00,
1275                     0x33, 0x66, 0x99, 0xCC, or 0xFF), but the number of colors
1276                     can be changed by the \e -ncols option. The user can force
1277                     the application to use the true color visual with the
1278                     \l{QApplication::QApplication()}{-visual} option.
1279                 \li  For 256-color displays which have a true color visual with
1280                     more than 256 colors, use that visual. Silicon Graphics X
1281                     servers this feature, for example. They provide an 8 bit
1282                     visual by default but can deliver true color when asked.
1283             \endlist
1284             On Windows, Qt creates a Windows palette, and fills it with a color
1285             cube.
1286     \endlist
1287
1288     Be aware that the CustomColor and ManyColor choices may lead to colormap
1289     flashing: The foreground application gets (most) of the available colors,
1290     while the background windows will look less attractive.
1291
1292     Example:
1293
1294     \snippet code/src_gui_kernel_qapplication.cpp 2
1295
1296     \sa colorSpec()
1297 */
1298
1299 void QApplication::setColorSpec(int spec)
1300 {
1301     if (qApp)
1302         qWarning("QApplication::setColorSpec: This function must be "
1303                  "called before the QApplication object is created");
1304     QApplicationPrivate::app_cspec = spec;
1305 }
1306
1307 /*!
1308     \property QApplication::globalStrut
1309     \brief the minimum size that any GUI element that the user can interact
1310            with should have
1311
1312     For example, no button should be resized to be smaller than the global
1313     strut size. The strut size should be considered when reimplementing GUI
1314     controls that may be used on touch-screens or similar I/O devices.
1315
1316     Example:
1317
1318     \snippet code/src_gui_kernel_qapplication.cpp 3
1319
1320     By default, this property contains a QSize object with zero width and height.
1321 */
1322 QSize QApplication::globalStrut()
1323 {
1324     return QApplicationPrivate::app_strut;
1325 }
1326
1327 void QApplication::setGlobalStrut(const QSize& strut)
1328 {
1329     QApplicationPrivate::app_strut = strut;
1330 }
1331
1332
1333 /*!
1334     \fn QPalette QApplication::palette(const QWidget* widget)
1335     \overload
1336
1337     If a \a widget is passed, the default palette for the widget's class is
1338     returned. This may or may not be the application palette. In most cases
1339     there is no special palette for certain types of widgets, but one notable
1340     exception is the popup menu under Windows, if the user has defined a
1341     special background color for menus in the display settings.
1342
1343     \sa setPalette(), QWidget::palette()
1344 */
1345 QPalette QApplication::palette(const QWidget* w)
1346 {
1347     PaletteHash *hash = app_palettes();
1348     if (w && hash && hash->size()) {
1349         QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(w->metaObject()->className());
1350         if (it != hash->constEnd())
1351             return *it;
1352         for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1353             if (w->inherits(it.key()))
1354                 return it.value();
1355         }
1356     }
1357     return palette();
1358 }
1359
1360 /*!
1361     \overload
1362
1363     Returns the palette for widgets of the given \a className.
1364
1365     \sa setPalette(), QWidget::palette()
1366 */
1367 QPalette QApplication::palette(const char *className)
1368 {
1369     if (!QApplicationPrivate::app_pal)
1370         palette();
1371     PaletteHash *hash = app_palettes();
1372     if (className && hash && hash->size()) {
1373         QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(className);
1374         if (it != hash->constEnd())
1375             return *it;
1376     }
1377     return *QApplicationPrivate::app_pal;
1378 }
1379
1380 void QApplicationPrivate::setPalette_helper(const QPalette &palette, const char* className, bool clearWidgetPaletteHash)
1381 {
1382     QPalette pal = palette;
1383
1384     if (QApplicationPrivate::app_style)
1385         QApplicationPrivate::app_style->polish(pal); // NB: non-const reference
1386
1387     bool all = false;
1388     PaletteHash *hash = app_palettes();
1389     if (!className) {
1390         if (QApplicationPrivate::app_pal && pal.isCopyOf(*QApplicationPrivate::app_pal))
1391             return;
1392         if (!QApplicationPrivate::app_pal)
1393             QApplicationPrivate::app_pal = new QPalette(pal);
1394         else
1395             *QApplicationPrivate::app_pal = pal;
1396         if (hash && hash->size()) {
1397             all = true;
1398             if (clearWidgetPaletteHash)
1399                 hash->clear();
1400         }
1401     } else if (hash) {
1402         hash->insert(className, pal);
1403     }
1404
1405     if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1406         // Send ApplicationPaletteChange to qApp itself, and to the widgets.
1407         QEvent e(QEvent::ApplicationPaletteChange);
1408         QApplication::sendEvent(QApplication::instance(), &e);
1409
1410         QWidgetList wids = QApplication::allWidgets();
1411         for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1412             register QWidget *w = *it;
1413             if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1414                 QApplication::sendEvent(w, &e);
1415         }
1416
1417         // Send to all scenes as well.
1418 #ifndef QT_NO_GRAPHICSVIEW
1419         QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1420         for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1421              it != scenes.constEnd(); ++it) {
1422             QApplication::sendEvent(*it, &e);
1423         }
1424 #endif //QT_NO_GRAPHICSVIEW
1425     }
1426     if (!className && (!QApplicationPrivate::sys_pal || !palette.isCopyOf(*QApplicationPrivate::sys_pal))) {
1427         if (!QApplicationPrivate::set_pal)
1428             QApplicationPrivate::set_pal = new QPalette(palette);
1429         else
1430             *QApplicationPrivate::set_pal = palette;
1431     }
1432 }
1433
1434 /*!
1435     Changes the default application palette to \a palette.
1436
1437     If \a className is passed, the change applies only to widgets that inherit
1438     \a className (as reported by QObject::inherits()). If \a className is left
1439     0, the change affects all widgets, thus overriding any previously set class
1440     specific palettes.
1441
1442     The palette may be changed according to the current GUI style in
1443     QStyle::polish().
1444
1445     \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1446     When using style sheets, the palette of a widget can be customized using
1447     the "color", "background-color", "selection-color",
1448     "selection-background-color" and "alternate-background-color".
1449
1450     \note Some styles do not use the palette for all drawing, for instance, if
1451     they make use of native theme engines. This is the case for the Windows XP,
1452     Windows Vista, and Mac OS X styles.
1453
1454     \sa QWidget::setPalette(), palette(), QStyle::polish()
1455 */
1456
1457 void QApplication::setPalette(const QPalette &palette, const char* className)
1458 {
1459     QApplicationPrivate::setPalette_helper(palette, className, /*clearWidgetPaletteHash=*/ true);
1460 }
1461
1462
1463
1464 void QApplicationPrivate::setSystemPalette(const QPalette &pal)
1465 {
1466     QPalette adjusted;
1467
1468 #if 0
1469     // adjust the system palette to avoid dithering
1470     QColormap cmap = QColormap::instance();
1471     if (cmap.depths() > 4 && cmap.depths() < 24) {
1472         for (int g = 0; g < QPalette::NColorGroups; g++)
1473             for (int i = 0; i < QPalette::NColorRoles; i++) {
1474                 QColor color = pal.color((QPalette::ColorGroup)g, (QPalette::ColorRole)i);
1475                 color = cmap.colorAt(cmap.pixel(color));
1476                 adjusted.setColor((QPalette::ColorGroup)g, (QPalette::ColorRole) i, color);
1477             }
1478     }
1479 #else
1480     adjusted = pal;
1481 #endif
1482
1483     if (!sys_pal)
1484         sys_pal = new QPalette(adjusted);
1485     else
1486         *sys_pal = adjusted;
1487
1488
1489     if (!QApplicationPrivate::set_pal)
1490         QApplication::setPalette(*sys_pal);
1491 }
1492
1493 /*!
1494     Returns the default application font.
1495
1496     \sa fontMetrics(), QWidget::font()
1497 */
1498 QFont QApplication::font()
1499 {
1500     return QGuiApplication::font();
1501 }
1502
1503 /*!
1504     \overload
1505
1506     Returns the default font for the \a widget.
1507
1508     \sa fontMetrics(), QWidget::setFont()
1509 */
1510
1511 QFont QApplication::font(const QWidget *widget)
1512 {
1513     FontHash *hash = app_fonts();
1514
1515     if (widget && hash  && hash->size()) {
1516         QHash<QByteArray, QFont>::ConstIterator it =
1517                 hash->constFind(widget->metaObject()->className());
1518         if (it != hash->constEnd())
1519             return it.value();
1520         for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1521             if (widget->inherits(it.key()))
1522                 return it.value();
1523         }
1524     }
1525     return font();
1526 }
1527
1528 /*!
1529     \overload
1530
1531     Returns the font for widgets of the given \a className.
1532
1533     \sa setFont(), QWidget::font()
1534 */
1535 QFont QApplication::font(const char *className)
1536 {
1537     FontHash *hash = app_fonts();
1538     if (className && hash && hash->size()) {
1539         QHash<QByteArray, QFont>::ConstIterator it = hash->constFind(className);
1540         if (it != hash->constEnd())
1541             return *it;
1542     }
1543     return font();
1544 }
1545
1546
1547 /*!
1548     Changes the default application font to \a font. If \a className is passed,
1549     the change applies only to classes that inherit \a className (as reported
1550     by QObject::inherits()).
1551
1552     On application start-up, the default font depends on the window system. It
1553     can vary depending on both the window system version and the locale. This
1554     function lets you override the default font; but overriding may be a bad
1555     idea because, for example, some locales need extra large fonts to support
1556     their special characters.
1557
1558     \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1559     The font of an application can be customized using the "font" style sheet
1560     property. To set a bold font for all QPushButtons, set the application
1561     styleSheet() as "QPushButton { font: bold }"
1562
1563     \sa font(), fontMetrics(), QWidget::setFont()
1564 */
1565
1566 void QApplication::setFont(const QFont &font, const char *className)
1567 {
1568     bool all = false;
1569     FontHash *hash = app_fonts();
1570     if (!className) {
1571         QGuiApplication::setFont(font);
1572         if (hash && hash->size()) {
1573             all = true;
1574             hash->clear();
1575         }
1576     } else if (hash) {
1577         hash->insert(className, font);
1578     }
1579     if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1580         // Send ApplicationFontChange to qApp itself, and to the widgets.
1581         QEvent e(QEvent::ApplicationFontChange);
1582         QApplication::sendEvent(QApplication::instance(), &e);
1583
1584         QWidgetList wids = QApplication::allWidgets();
1585         for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1586             register QWidget *w = *it;
1587             if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1588                 sendEvent(w, &e);
1589         }
1590
1591 #ifndef QT_NO_GRAPHICSVIEW
1592         // Send to all scenes as well.
1593         QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1594         for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1595              it != scenes.constEnd(); ++it) {
1596             QApplication::sendEvent(*it, &e);
1597         }
1598 #endif //QT_NO_GRAPHICSVIEW
1599     }
1600     if (!className && (!QApplicationPrivate::sys_font || !font.isCopyOf(*QApplicationPrivate::sys_font))) {
1601         if (!QApplicationPrivate::set_font)
1602             QApplicationPrivate::set_font = new QFont(font);
1603         else
1604             *QApplicationPrivate::set_font = font;
1605     }
1606 }
1607
1608 /*! \internal
1609 */
1610 void QApplicationPrivate::setSystemFont(const QFont &font)
1611 {
1612      if (!sys_font)
1613         sys_font = new QFont(font);
1614     else
1615         *sys_font = font;
1616
1617     if (!QApplicationPrivate::set_font)
1618         QApplication::setFont(*sys_font);
1619 }
1620
1621 /*! \internal
1622 */
1623 QString QApplicationPrivate::desktopStyleKey()
1624 {
1625     // The platform theme might return a style that is not available, find
1626     // first valid one.
1627     if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
1628         const QStringList availableKeys = QStyleFactory::keys();
1629         foreach (const QString &style, theme->themeHint(QPlatformTheme::StyleNames).toStringList())
1630             if (availableKeys.contains(style, Qt::CaseInsensitive))
1631                 return style;
1632     }
1633     return QString();
1634 }
1635
1636 /*!
1637     \property QApplication::windowIcon
1638     \brief the default window icon
1639
1640     \sa QWidget::setWindowIcon(), {Setting the Application Icon}
1641 */
1642 QIcon QApplication::windowIcon()
1643 {
1644     return QApplicationPrivate::app_icon ? *QApplicationPrivate::app_icon : QIcon();
1645 }
1646
1647 void QApplication::setWindowIcon(const QIcon &icon)
1648 {
1649     if (!QApplicationPrivate::app_icon)
1650         QApplicationPrivate::app_icon = new QIcon();
1651     *QApplicationPrivate::app_icon = icon;
1652     if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1653         QEvent e(QEvent::ApplicationWindowIconChange);
1654         QWidgetList all = QApplication::allWidgets();
1655         for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1656             register QWidget *w = *it;
1657             if (w->isWindow())
1658                 sendEvent(w, &e);
1659         }
1660     }
1661 }
1662
1663 /*!
1664     Returns a list of the top-level widgets (windows) in the application.
1665
1666     \note Some of the top-level widgets may be hidden, for example a tooltip if
1667     no tooltip is currently shown.
1668
1669     Example:
1670
1671     \snippet code/src_gui_kernel_qapplication.cpp 4
1672
1673     \sa allWidgets(), QWidget::isWindow(), QWidget::isHidden()
1674 */
1675 QWidgetList QApplication::topLevelWidgets()
1676 {
1677     QWidgetList list;
1678     QWidgetList all = allWidgets();
1679
1680     for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1681         QWidget *w = *it;
1682         if (w->isWindow() && w->windowType() != Qt::Desktop)
1683             list.append(w);
1684     }
1685     return list;
1686 }
1687
1688 /*!
1689     Returns a list of all the widgets in the application.
1690
1691     The list is empty (QList::isEmpty()) if there are no widgets.
1692
1693     \note Some of the widgets may be hidden.
1694
1695     Example:
1696     \snippet code/src_gui_kernel_qapplication.cpp 5
1697
1698     \sa topLevelWidgets(), QWidget::isVisible()
1699 */
1700
1701 QWidgetList QApplication::allWidgets()
1702 {
1703     if (QWidgetPrivate::allWidgets)
1704         return QWidgetPrivate::allWidgets->toList();
1705     return QWidgetList();
1706 }
1707
1708 /*!
1709     Returns the application widget that has the keyboard input focus, or 0 if
1710     no widget in this application has the focus.
1711
1712     \sa QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), focusChanged()
1713 */
1714
1715 QWidget *QApplication::focusWidget()
1716 {
1717     return QApplicationPrivate::focus_widget;
1718 }
1719
1720 void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
1721 {
1722 #ifndef QT_NO_GRAPHICSVIEW
1723     if (focus && focus->window()->graphicsProxyWidget())
1724         return;
1725 #endif
1726
1727     hidden_focus_widget = 0;
1728
1729     if (focus != focus_widget) {
1730         if (focus && focus->isHidden()) {
1731             hidden_focus_widget = focus;
1732             return;
1733         }
1734
1735         if (focus && (reason == Qt::BacktabFocusReason || reason == Qt::TabFocusReason)
1736             && qt_in_tab_key_event)
1737             focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1738         else if (focus && reason == Qt::ShortcutFocusReason) {
1739             focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1740         }
1741         QWidget *prev = focus_widget;
1742         focus_widget = focus;
1743
1744         if(focus_widget)
1745             focus_widget->d_func()->setFocus_sys();
1746
1747         if (reason != Qt::NoFocusReason) {
1748
1749             //send events
1750             if (prev) {
1751 #ifdef QT_KEYPAD_NAVIGATION
1752                 if (QApplication::keypadNavigationEnabled()) {
1753                     if (prev->hasEditFocus() && reason != Qt::PopupFocusReason)
1754                         prev->setEditFocus(false);
1755                 }
1756 #endif
1757                 QFocusEvent out(QEvent::FocusOut, reason);
1758                 QPointer<QWidget> that = prev;
1759                 QApplication::sendEvent(prev, &out);
1760                 if (that)
1761                     QApplication::sendEvent(that->style(), &out);
1762             }
1763             if(focus && QApplicationPrivate::focus_widget == focus) {
1764                 QFocusEvent in(QEvent::FocusIn, reason);
1765                 QPointer<QWidget> that = focus;
1766                 QApplication::sendEvent(focus, &in);
1767                 if (that)
1768                     QApplication::sendEvent(that->style(), &in);
1769             }
1770             emit qApp->focusChanged(prev, focus_widget);
1771         }
1772     }
1773 }
1774
1775
1776 /*!
1777     Returns the application top-level window that has the keyboard input focus,
1778     or 0 if no application window has the focus. There might be an
1779     activeWindow() even if there is no focusWidget(), for example if no widget
1780     in that window accepts key events.
1781
1782     \sa QWidget::setFocus(), QWidget::hasFocus(), focusWidget()
1783 */
1784
1785 QWidget *QApplication::activeWindow()
1786 {
1787     return QApplicationPrivate::active_window;
1788 }
1789
1790 /*!
1791     Returns display (screen) font metrics for the application font.
1792
1793     \sa font(), setFont(), QWidget::fontMetrics(), QPainter::fontMetrics()
1794 */
1795
1796 QFontMetrics QApplication::fontMetrics()
1797 {
1798     return desktop()->fontMetrics();
1799 }
1800
1801
1802 /*!
1803     Closes all top-level windows.
1804
1805     This function is particularly useful for applications with many top-level
1806     windows. It could, for example, be connected to a \uicontrol{Exit} entry in the
1807     \uicontrol{File} menu:
1808
1809     \snippet mainwindows/mdi/mainwindow.cpp 0
1810
1811     The windows are closed in random order, until one window does not accept
1812     the close event. The application quits when the last window was
1813     successfully closed; this can be turned off by setting
1814     \l quitOnLastWindowClosed to false.
1815
1816     \sa quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(),
1817     QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(),
1818     QWidget::isWindow()
1819 */
1820 void QApplication::closeAllWindows()
1821 {
1822     bool did_close = true;
1823     QWidget *w;
1824     while ((w = activeModalWidget()) && did_close) {
1825         if (!w->isVisible() || w->data->is_closing)
1826             break;
1827         did_close = w->close();
1828     }
1829     QWidgetList list = QApplication::topLevelWidgets();
1830     for (int i = 0; did_close && i < list.size(); ++i) {
1831         w = list.at(i);
1832         if (w->isVisible()
1833             && w->windowType() != Qt::Desktop
1834             && !w->data->is_closing) {
1835             did_close = w->close();
1836             list = QApplication::topLevelWidgets();
1837             i = -1;
1838         }
1839     }
1840 }
1841
1842 /*!
1843     Displays a simple message box about Qt. The message includes the version
1844     number of Qt being used by the application.
1845
1846     This is useful for inclusion in the \uicontrol Help menu of an application, as
1847     shown in the \l{mainwindows/menus}{Menus} example.
1848
1849     This function is a convenience slot for QMessageBox::aboutQt().
1850 */
1851 void QApplication::aboutQt()
1852 {
1853 #ifndef QT_NO_MESSAGEBOX
1854     QMessageBox::aboutQt(activeWindow());
1855 #endif // QT_NO_MESSAGEBOX
1856 }
1857
1858 /*!
1859     \since 4.1
1860     \fn void QApplication::focusChanged(QWidget *old, QWidget *now)
1861
1862     This signal is emitted when the widget that has keyboard focus changed from
1863     \a old to \a now, i.e., because the user pressed the tab-key, clicked into
1864     a widget or changed the active window. Both \a old and \a now can be the
1865     null-pointer.
1866
1867     The signal is emitted after both widget have been notified about the change
1868     through QFocusEvent.
1869
1870     \sa QWidget::setFocus(), QWidget::clearFocus(), Qt::FocusReason
1871 */
1872
1873 /*!\reimp
1874
1875 */
1876 bool QApplication::event(QEvent *e)
1877 {
1878     Q_D(QApplication);
1879     if(e->type() == QEvent::Close) {
1880         QCloseEvent *ce = static_cast<QCloseEvent*>(e);
1881         ce->accept();
1882         closeAllWindows();
1883
1884         QWidgetList list = topLevelWidgets();
1885         for (int i = 0; i < list.size(); ++i) {
1886             QWidget *w = list.at(i);
1887             if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
1888                  (!(w->windowType() == Qt::Dialog) || !w->parentWidget())) {
1889                 ce->ignore();
1890                 break;
1891             }
1892         }
1893         if (ce->isAccepted()) {
1894             return true;
1895         }
1896 #ifndef Q_OS_WIN
1897     } else if (e->type() == QEvent::LocaleChange) {
1898         // on Windows the event propagation is taken care by the
1899         // WM_SETTINGCHANGE event handler.
1900         QWidgetList list = topLevelWidgets();
1901         for (int i = 0; i < list.size(); ++i) {
1902             QWidget *w = list.at(i);
1903             if (!(w->windowType() == Qt::Desktop)) {
1904                 if (!w->testAttribute(Qt::WA_SetLocale))
1905                     w->d_func()->setLocale_helper(QLocale(), true);
1906             }
1907         }
1908 #endif
1909     } else if (e->type() == QEvent::Timer) {
1910         QTimerEvent *te = static_cast<QTimerEvent*>(e);
1911         Q_ASSERT(te != 0);
1912         if (te->timerId() == d->toolTipWakeUp.timerId()) {
1913             d->toolTipWakeUp.stop();
1914             if (d->toolTipWidget) {
1915                 QWidget *w = d->toolTipWidget->window();
1916                 // show tooltip if WA_AlwaysShowToolTips is set, or if
1917                 // any ancestor of d->toolTipWidget is the active
1918                 // window
1919                 bool showToolTip = w->testAttribute(Qt::WA_AlwaysShowToolTips);
1920                 while (w && !showToolTip) {
1921                     showToolTip = w->isActiveWindow();
1922                     w = w->parentWidget();
1923                     w = w ? w->window() : 0;
1924                 }
1925                 if (showToolTip) {
1926                     QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
1927                     QApplication::sendEvent(d->toolTipWidget, &e);
1928                     if (e.isAccepted())
1929                         d->toolTipFallAsleep.start(2000, this);
1930                 }
1931             }
1932         } else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
1933             d->toolTipFallAsleep.stop();
1934         }
1935     }
1936
1937     if(e->type() == QEvent::LanguageChange) {
1938         QWidgetList list = topLevelWidgets();
1939         for (int i = 0; i < list.size(); ++i) {
1940             QWidget *w = list.at(i);
1941             if (!(w->windowType() == Qt::Desktop))
1942                 postEvent(w, new QEvent(QEvent::LanguageChange));
1943         }
1944     }
1945
1946     return QGuiApplication::event(e);
1947 }
1948
1949 /*!
1950    \fn void QApplication::syncX()
1951     Was used to synchronize with the X server in 4.x, here for source compatibility.
1952     \internal
1953     \obsolete
1954 */
1955
1956 void QApplicationPrivate::notifyLayoutDirectionChange()
1957 {
1958     QWidgetList list = QApplication::topLevelWidgets();
1959     for (int i = 0; i < list.size(); ++i) {
1960         QWidget *w = list.at(i);
1961         QEvent ev(QEvent::ApplicationLayoutDirectionChange);
1962         QCoreApplication::sendEvent(w, &ev);
1963     }
1964 }
1965
1966 /*!
1967     \fn Qt::WindowsVersion QApplication::winVersion()
1968
1969     Use \l QSysInfo::WindowsVersion instead.
1970 */
1971
1972 /*!
1973     \fn void QApplication::setActiveWindow(QWidget* active)
1974
1975     Sets the active window to the \a active widget in response to a system
1976     event. The function is called from the platform specific event handlers.
1977
1978     \warning This function does \e not set the keyboard focus to the active
1979     widget. Call QWidget::activateWindow() instead.
1980
1981     It sets the activeWindow() and focusWidget() attributes and sends proper
1982     \l{QEvent::WindowActivate}{WindowActivate}/\l{QEvent::WindowDeactivate}
1983     {WindowDeactivate} and \l{QEvent::FocusIn}{FocusIn}/\l{QEvent::FocusOut}
1984     {FocusOut} events to all appropriate widgets. The window will then be
1985     painted in active state (e.g. cursors in line edits will blink), and it
1986     will have tool tips enabled.
1987
1988     \sa activeWindow(), QWidget::activateWindow()
1989 */
1990 void QApplication::setActiveWindow(QWidget* act)
1991 {
1992     QWidget* window = act?act->window():0;
1993
1994     if (QApplicationPrivate::active_window == window)
1995         return;
1996
1997 #ifndef QT_NO_GRAPHICSVIEW
1998     if (window && window->graphicsProxyWidget()) {
1999         // Activate the proxy's view->viewport() ?
2000         return;
2001     }
2002 #endif
2003
2004     QWidgetList toBeActivated;
2005     QWidgetList toBeDeactivated;
2006
2007     if (QApplicationPrivate::active_window) {
2008         if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2009             QWidgetList list = topLevelWidgets();
2010             for (int i = 0; i < list.size(); ++i) {
2011                 QWidget *w = list.at(i);
2012                 if (w->isVisible() && w->isActiveWindow())
2013                     toBeDeactivated.append(w);
2014             }
2015         } else {
2016             toBeDeactivated.append(QApplicationPrivate::active_window);
2017         }
2018     }
2019
2020     if (QApplicationPrivate::focus_widget) {
2021         if (QApplicationPrivate::focus_widget->testAttribute(Qt::WA_InputMethodEnabled))
2022             qApp->inputMethod()->commit();
2023
2024         QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, Qt::ActiveWindowFocusReason);
2025         QApplication::sendEvent(QApplicationPrivate::focus_widget, &focusAboutToChange);
2026     }
2027
2028     QApplicationPrivate::active_window = window;
2029
2030     if (QApplicationPrivate::active_window) {
2031         if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2032             QWidgetList list = topLevelWidgets();
2033             for (int i = 0; i < list.size(); ++i) {
2034                 QWidget *w = list.at(i);
2035                 if (w->isVisible() && w->isActiveWindow())
2036                     toBeActivated.append(w);
2037             }
2038         } else {
2039             toBeActivated.append(QApplicationPrivate::active_window);
2040         }
2041
2042     }
2043
2044     // first the activation/deactivation events
2045     QEvent activationChange(QEvent::ActivationChange);
2046     QEvent windowActivate(QEvent::WindowActivate);
2047     QEvent windowDeactivate(QEvent::WindowDeactivate);
2048
2049     for (int i = 0; i < toBeActivated.size(); ++i) {
2050         QWidget *w = toBeActivated.at(i);
2051         sendSpontaneousEvent(w, &windowActivate);
2052         sendSpontaneousEvent(w, &activationChange);
2053     }
2054
2055     for(int i = 0; i < toBeDeactivated.size(); ++i) {
2056         QWidget *w = toBeDeactivated.at(i);
2057         sendSpontaneousEvent(w, &windowDeactivate);
2058         sendSpontaneousEvent(w, &activationChange);
2059     }
2060
2061     if (QApplicationPrivate::popupWidgets == 0) { // !inPopupMode()
2062         // then focus events
2063         if (!QApplicationPrivate::active_window && QApplicationPrivate::focus_widget) {
2064             QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2065         } else if (QApplicationPrivate::active_window) {
2066             QWidget *w = QApplicationPrivate::active_window->focusWidget();
2067             if (w && w->isVisible() /*&& w->focusPolicy() != QWidget::NoFocus*/)
2068                 w->setFocus(Qt::ActiveWindowFocusReason);
2069             else {
2070                 w = QApplicationPrivate::focusNextPrevChild_helper(QApplicationPrivate::active_window, true);
2071                 if (w) {
2072                     w->setFocus(Qt::ActiveWindowFocusReason);
2073                 } else {
2074                     // If the focus widget is not in the activate_window, clear the focus
2075                     w = QApplicationPrivate::focus_widget;
2076                     if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus)
2077                         QApplicationPrivate::setFocusWidget(QApplicationPrivate::active_window, Qt::ActiveWindowFocusReason);
2078                     else if (!QApplicationPrivate::active_window->isAncestorOf(w))
2079                         QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2080                 }
2081             }
2082         }
2083     }
2084 }
2085
2086 /*!internal
2087  * Helper function that returns the new focus widget, but does not set the focus reason.
2088  * Returns 0 if a new focus widget could not be found.
2089  * Shared with QGraphicsProxyWidgetPrivate::findFocusChild()
2090 */
2091 QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool next)
2092 {
2093     uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
2094
2095     QWidget *f = toplevel->focusWidget();
2096     if (!f)
2097         f = toplevel;
2098
2099     QWidget *w = f;
2100     QWidget *test = f->d_func()->focus_next;
2101     while (test && test != f) {
2102         if ((test->focusPolicy() & focus_flag) == focus_flag
2103             && !(test->d_func()->extra && test->d_func()->extra->focus_proxy)
2104             && test->isVisibleTo(toplevel) && test->isEnabled()
2105             && !(w->windowType() == Qt::SubWindow && !w->isAncestorOf(test))
2106             && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))) {
2107             w = test;
2108             if (next)
2109                 break;
2110         }
2111         test = test->d_func()->focus_next;
2112     }
2113     if (w == f) {
2114         if (qt_in_tab_key_event) {
2115             w->window()->setAttribute(Qt::WA_KeyboardFocusChange);
2116             w->update();
2117         }
2118         return 0;
2119     }
2120     return w;
2121 }
2122
2123 /*!
2124     \fn void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave)
2125     \internal
2126
2127     Creates the proper Enter/Leave event when widget \a enter is entered and
2128     widget \a leave is left.
2129  */
2130 void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave) {
2131 #if 0
2132     if (leave) {
2133         QEvent e(QEvent::Leave);
2134         QApplication::sendEvent(leave, & e);
2135     }
2136     if (enter) {
2137         QEvent e(QEvent::Enter);
2138         QApplication::sendEvent(enter, & e);
2139     }
2140     return;
2141 #endif
2142
2143     QWidget* w ;
2144     if ((!enter && !leave) || (enter == leave))
2145         return;
2146 #ifdef ALIEN_DEBUG
2147     qDebug() << "QApplicationPrivate::dispatchEnterLeave, ENTER:" << enter << "LEAVE:" << leave;
2148 #endif
2149     QWidgetList leaveList;
2150     QWidgetList enterList;
2151
2152     bool sameWindow = leave && enter && leave->window() == enter->window();
2153     if (leave && !sameWindow) {
2154         w = leave;
2155         do {
2156             leaveList.append(w);
2157         } while (!w->isWindow() && (w = w->parentWidget()));
2158     }
2159     if (enter && !sameWindow) {
2160         w = enter;
2161         do {
2162             enterList.prepend(w);
2163         } while (!w->isWindow() && (w = w->parentWidget()));
2164     }
2165     if (sameWindow) {
2166         int enterDepth = 0;
2167         int leaveDepth = 0;
2168         w = enter;
2169         while (!w->isWindow() && (w = w->parentWidget()))
2170             enterDepth++;
2171         w = leave;
2172         while (!w->isWindow() && (w = w->parentWidget()))
2173             leaveDepth++;
2174         QWidget* wenter = enter;
2175         QWidget* wleave = leave;
2176         while (enterDepth > leaveDepth) {
2177             wenter = wenter->parentWidget();
2178             enterDepth--;
2179         }
2180         while (leaveDepth > enterDepth) {
2181             wleave = wleave->parentWidget();
2182             leaveDepth--;
2183         }
2184         while (!wenter->isWindow() && wenter != wleave) {
2185             wenter = wenter->parentWidget();
2186             wleave = wleave->parentWidget();
2187         }
2188
2189         w = leave;
2190         while (w != wleave) {
2191             leaveList.append(w);
2192             w = w->parentWidget();
2193         }
2194         w = enter;
2195         while (w != wenter) {
2196             enterList.prepend(w);
2197             w = w->parentWidget();
2198         }
2199     }
2200
2201     QEvent leaveEvent(QEvent::Leave);
2202     for (int i = 0; i < leaveList.size(); ++i) {
2203         w = leaveList.at(i);
2204         if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2205             QApplication::sendEvent(w, &leaveEvent);
2206             if (w->testAttribute(Qt::WA_Hover) &&
2207                 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2208                 Q_ASSERT(instance());
2209                 QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos),
2210                                QApplication::keyboardModifiers());
2211                 qApp->d_func()->notify_helper(w, &he);
2212             }
2213         }
2214     }
2215     QPoint posEnter = QCursor::pos();
2216     QEvent enterEvent(QEvent::Enter);
2217     for (int i = 0; i < enterList.size(); ++i) {
2218         w = enterList.at(i);
2219         if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2220             QApplication::sendEvent(w, &enterEvent);
2221             if (w->testAttribute(Qt::WA_Hover) &&
2222                 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2223                 QHoverEvent he(QEvent::HoverEnter, w->mapFromGlobal(posEnter), QPoint(-1, -1),
2224                                QApplication::keyboardModifiers());
2225                 qApp->d_func()->notify_helper(w, &he);
2226             }
2227         }
2228     }
2229
2230 #ifndef QT_NO_CURSOR
2231     // Update cursor for alien/graphics widgets.
2232
2233     const bool enterOnAlien = (enter && (isAlien(enter) || enter->testAttribute(Qt::WA_DontShowOnScreen)));
2234     // Whenever we leave an alien widget on X11/QPA, we need to reset its nativeParentWidget()'s cursor.
2235     // This is not required on Windows as the cursor is reset on every single mouse move.
2236     QWidget *parentOfLeavingCursor = 0;
2237     for (int i = 0; i < leaveList.size(); ++i) {
2238         w = leaveList.at(i);
2239         if (!isAlien(w))
2240             break;
2241         if (w->testAttribute(Qt::WA_SetCursor)) {
2242             QWidget *parent = w->parentWidget();
2243             while (parent && parent->d_func()->data.in_destructor)
2244                 parent = parent->parentWidget();
2245             parentOfLeavingCursor = parent;
2246             //continue looping, we need to find the downest alien widget with a cursor.
2247             // (downest on the screen)
2248         }
2249     }
2250     //check that we will not call qt_x11_enforce_cursor twice with the same native widget
2251     if (parentOfLeavingCursor && (!enterOnAlien
2252         || parentOfLeavingCursor->effectiveWinId() != enter->effectiveWinId())) {
2253 #ifndef QT_NO_GRAPHICSVIEW
2254         if (!parentOfLeavingCursor->window()->graphicsProxyWidget())
2255 #endif
2256         {
2257             if (enter == QApplication::desktop()) {
2258                 qt_qpa_set_cursor(enter, true);
2259             } else {
2260                 qt_qpa_set_cursor(parentOfLeavingCursor, true);
2261             }
2262         }
2263     }
2264     if (enterOnAlien) {
2265         QWidget *cursorWidget = enter;
2266         while (!cursorWidget->isWindow() && !cursorWidget->isEnabled())
2267             cursorWidget = cursorWidget->parentWidget();
2268
2269         if (!cursorWidget)
2270             return;
2271
2272 #ifndef QT_NO_GRAPHICSVIEW
2273         if (cursorWidget->window()->graphicsProxyWidget()) {
2274             QWidgetPrivate::nearestGraphicsProxyWidget(cursorWidget)->setCursor(cursorWidget->cursor());
2275         } else
2276 #endif
2277         {
2278             qt_qpa_set_cursor(cursorWidget, true);
2279         }
2280     }
2281 #endif
2282 }
2283
2284 /* exported for the benefit of testing tools */
2285 Q_WIDGETS_EXPORT bool qt_tryModalHelper(QWidget *widget, QWidget **rettop)
2286 {
2287     return QApplicationPrivate::tryModalHelper(widget, rettop);
2288 }
2289
2290 /*! \internal
2291     Returns true if \a widget is blocked by a modal window.
2292  */
2293 bool QApplicationPrivate::isBlockedByModal(QWidget *widget)
2294 {
2295     widget = widget->window();
2296     return self->isWindowBlocked(widget->windowHandle());
2297 }
2298
2299 bool QApplicationPrivate::isWindowBlocked(QWindow *window, QWindow **blockingWindow) const
2300 {
2301     QWindow *unused = 0;
2302     if (!blockingWindow)
2303         blockingWindow = &unused;
2304
2305     if (modalWindowList.isEmpty()) {
2306         *blockingWindow = 0;
2307         return false;
2308     }
2309     QWidget *popupWidget = QApplication::activePopupWidget();
2310     QWindow *popupWindow = popupWidget ? popupWidget->windowHandle() : 0;
2311     if (popupWindow == window) {
2312         *blockingWindow = 0;
2313         return false;
2314     }
2315
2316     for (int i = 0; i < modalWindowList.count(); ++i) {
2317         QWindow *modalWindow = modalWindowList.at(i);
2318
2319         {
2320             // check if the modal window is our window or a (transient) parent of our window
2321             QWindow *w = window;
2322             while (w) {
2323                 if (w == modalWindow) {
2324                     *blockingWindow = 0;
2325                     return false;
2326                 }
2327                 QWindow *p = w->parent();
2328                 if (!p)
2329                     p = w->transientParent();
2330                 w = p;
2331             }
2332         }
2333
2334         Qt::WindowModality windowModality = modalWindow->windowModality();
2335         QWidgetWindow *modalWidgetWindow = qobject_cast<QWidgetWindow *>(modalWindow);
2336         if (windowModality == Qt::NonModal) {
2337             // determine the modality type if it hasn't been set on the
2338             // modalWindow's widget, this normally happens when waiting for a
2339             // native dialog. use WindowModal if we are the child of a group
2340             // leader; otherwise use ApplicationModal.
2341             QWidget *m = modalWidgetWindow ? modalWidgetWindow->widget() : 0;
2342             while (m && !m->testAttribute(Qt::WA_GroupLeader)) {
2343                 m = m->parentWidget();
2344                 if (m)
2345                     m = m->window();
2346             }
2347             windowModality = (m && m->testAttribute(Qt::WA_GroupLeader))
2348                              ? Qt::WindowModal
2349                              : Qt::ApplicationModal;
2350         }
2351
2352         switch (windowModality) {
2353         case Qt::ApplicationModal:
2354         {
2355             QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(window);
2356             QWidget *groupLeaderForWidget = widgetWindow ? widgetWindow->widget() : 0;
2357             while (groupLeaderForWidget && !groupLeaderForWidget->testAttribute(Qt::WA_GroupLeader))
2358                 groupLeaderForWidget = groupLeaderForWidget->parentWidget();
2359
2360             if (groupLeaderForWidget) {
2361                 // if \a widget has WA_GroupLeader, it can only be blocked by ApplicationModal children
2362                 QWidget *m = modalWidgetWindow ? modalWidgetWindow->widget() : 0;
2363                 while (m && m != groupLeaderForWidget && !m->testAttribute(Qt::WA_GroupLeader))
2364                     m = m->parentWidget();
2365                 if (m == groupLeaderForWidget) {
2366                     *blockingWindow = m->windowHandle();
2367                     return true;
2368                 }
2369             } else if (modalWindow != window) {
2370                 *blockingWindow = modalWindow;
2371                 return true;
2372             }
2373             break;
2374         }
2375         case Qt::WindowModal:
2376         {
2377             QWindow *w = window;
2378             do {
2379                 QWindow *m = modalWindow;
2380                 do {
2381                     if (m == w) {
2382                         *blockingWindow = m;
2383                         return true;
2384                     }
2385                     QWindow *p = m->parent();
2386                     if (!p)
2387                         p = m->transientParent();
2388                     m = p;
2389                 } while (m);
2390                 QWindow *p = w->parent();
2391                 if (!p)
2392                     p = w->transientParent();
2393                 w = p;
2394             } while (w);
2395             break;
2396         }
2397         default:
2398             Q_ASSERT_X(false, "QApplication", "internal error, a modal window cannot be modeless");
2399             break;
2400         }
2401     }
2402     *blockingWindow = 0;
2403     return false;
2404 }
2405
2406 /*!\internal
2407
2408   Called from qapplication_\e{platform}.cpp, returns true
2409   if the widget should accept the event.
2410  */
2411 bool QApplicationPrivate::tryModalHelper(QWidget *widget, QWidget **rettop)
2412 {
2413     QWidget *top = QApplication::activeModalWidget();
2414     if (rettop)
2415         *rettop = top;
2416
2417     // the active popup widget always gets the input event
2418     if (QApplication::activePopupWidget())
2419         return true;
2420
2421     return !isBlockedByModal(widget->window());
2422 }
2423
2424 /*
2425    \internal
2426 */
2427 QWidget *QApplicationPrivate::pickMouseReceiver(QWidget *candidate, const QPoint &windowPos,
2428                                                 QPoint *pos, QEvent::Type type,
2429                                                 Qt::MouseButtons buttons, QWidget *buttonDown,
2430                                                 QWidget *alienWidget)
2431 {
2432     Q_ASSERT(candidate);
2433
2434     QWidget *mouseGrabber = QWidget::mouseGrabber();
2435     if (((type == QEvent::MouseMove && buttons) || (type == QEvent::MouseButtonRelease))
2436             && !buttonDown && !mouseGrabber) {
2437         return 0;
2438     }
2439
2440     if (alienWidget && alienWidget->internalWinId())
2441         alienWidget = 0;
2442
2443     QWidget *receiver = candidate;
2444
2445     if (!mouseGrabber)
2446         mouseGrabber = (buttonDown && !isBlockedByModal(buttonDown)) ? buttonDown : alienWidget;
2447
2448     if (mouseGrabber && mouseGrabber != candidate) {
2449         receiver = mouseGrabber;
2450         *pos = receiver->mapFromGlobal(candidate->mapToGlobal(windowPos));
2451 #ifdef ALIEN_DEBUG
2452         qDebug() << "  ** receiver adjusted to:" << receiver << "pos:" << pos;
2453 #endif
2454     }
2455
2456     return receiver;
2457
2458 }
2459
2460 /*
2461    \internal
2462 */
2463 bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
2464                                          QWidget *alienWidget, QWidget *nativeWidget,
2465                                          QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
2466                                          bool spontaneous)
2467 {
2468     Q_ASSERT(receiver);
2469     Q_ASSERT(event);
2470     Q_ASSERT(nativeWidget);
2471     Q_ASSERT(buttonDown);
2472
2473     if (alienWidget && !isAlien(alienWidget))
2474         alienWidget = 0;
2475
2476     QPointer<QWidget> receiverGuard = receiver;
2477     QPointer<QWidget> nativeGuard = nativeWidget;
2478     QPointer<QWidget> alienGuard = alienWidget;
2479     QPointer<QWidget> activePopupWidget = QApplication::activePopupWidget();
2480
2481     const bool graphicsWidget = nativeWidget->testAttribute(Qt::WA_DontShowOnScreen);
2482
2483     if (*buttonDown) {
2484         if (!graphicsWidget) {
2485             // Register the widget that shall receive a leave event
2486             // after the last button is released.
2487             if ((alienWidget || !receiver->internalWinId()) && !leaveAfterRelease && !QWidget::mouseGrabber())
2488                 leaveAfterRelease = *buttonDown;
2489             if (event->type() == QEvent::MouseButtonRelease && !event->buttons())
2490                 *buttonDown = 0;
2491         }
2492     } else if (lastMouseReceiver) {
2493         // Dispatch enter/leave if we move:
2494         // 1) from an alien widget to another alien widget or
2495         //    from a native widget to an alien widget (first OR case)
2496         // 2) from an alien widget to a native widget (second OR case)
2497         if ((alienWidget && alienWidget != lastMouseReceiver)
2498             || (isAlien(lastMouseReceiver) && !alienWidget)) {
2499             if (activePopupWidget) {
2500                 if (!QWidget::mouseGrabber())
2501                     dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver);
2502             } else {
2503                 dispatchEnterLeave(receiver, lastMouseReceiver);
2504             }
2505
2506         }
2507     }
2508
2509 #ifdef ALIEN_DEBUG
2510     qDebug() << "QApplicationPrivate::sendMouseEvent: receiver:" << receiver
2511              << "pos:" << event->pos() << "alien" << alienWidget << "button down"
2512              << *buttonDown << "last" << lastMouseReceiver << "leave after release"
2513              << leaveAfterRelease;
2514 #endif
2515
2516     // We need this quard in case someone opens a modal dialog / popup. If that's the case
2517     // leaveAfterRelease is set to null, but we shall not update lastMouseReceiver.
2518     const bool wasLeaveAfterRelease = leaveAfterRelease != 0;
2519     bool result;
2520     if (spontaneous)
2521         result = QApplication::sendSpontaneousEvent(receiver, event);
2522     else
2523         result = QApplication::sendEvent(receiver, event);
2524
2525     if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease
2526         && !event->buttons() && QWidget::mouseGrabber() != leaveAfterRelease) {
2527         // Dispatch enter/leave if:
2528         // 1) the mouse grabber is an alien widget
2529         // 2) the button is released on an alien widget
2530         QWidget *enter = 0;
2531         if (nativeGuard)
2532             enter = alienGuard ? alienWidget : nativeWidget;
2533         else // The receiver is typically deleted on mouse release with drag'n'drop.
2534             enter = QApplication::widgetAt(event->globalPos());
2535         dispatchEnterLeave(enter, leaveAfterRelease);
2536         leaveAfterRelease = 0;
2537         lastMouseReceiver = enter;
2538     } else if (!wasLeaveAfterRelease) {
2539         if (activePopupWidget) {
2540             if (!QWidget::mouseGrabber())
2541                 lastMouseReceiver = alienGuard ? alienWidget : (nativeGuard ? nativeWidget : 0);
2542         } else {
2543             lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPos());
2544         }
2545     }
2546
2547     return result;
2548 }
2549
2550 /*
2551     This function should only be called when the widget changes visibility, i.e.
2552     when the \a widget is shown, hidden or deleted. This function does nothing
2553     if the widget is a top-level or native, i.e. not an alien widget. In that
2554     case enter/leave events are genereated by the underlying windowing system.
2555 */
2556 extern QPointer<QWidget> qt_last_mouse_receiver;
2557 extern QWidget *qt_button_down;
2558 void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
2559 {
2560 #ifndef QT_NO_CURSOR
2561     if (!widget || widget->isWindow())
2562         return;
2563     const bool widgetInShow = widget->isVisible() && !widget->data->in_destructor;
2564     if (!widgetInShow && widget != qt_last_mouse_receiver)
2565         return; // Widget was not under the cursor when it was hidden/deleted.
2566
2567     if (widgetInShow && widget->parentWidget()->data->in_show)
2568         return; // Ingore recursive show.
2569
2570     QWidget *mouseGrabber = QWidget::mouseGrabber();
2571     if (mouseGrabber && mouseGrabber != widget)
2572         return; // Someone else has the grab; enter/leave should not occur.
2573
2574     QWidget *tlw = widget->window();
2575     if (tlw->data->in_destructor || tlw->data->is_closing)
2576         return; // Closing down the business.
2577
2578     if (widgetInShow && (!qt_last_mouse_receiver || qt_last_mouse_receiver->window() != tlw))
2579         return; // Mouse cursor not inside the widget's top-level.
2580
2581     const QPoint globalPos(QCursor::pos());
2582     QPoint windowPos = tlw->mapFromGlobal(globalPos);
2583
2584     // Find the current widget under the mouse. If this function was called from
2585     // the widget's destructor, we have to make sure childAt() doesn't take into
2586     // account widgets that are about to be destructed.
2587     QWidget *widgetUnderCursor = tlw->d_func()->childAt_helper(windowPos, widget->data->in_destructor);
2588     if (!widgetUnderCursor)
2589         widgetUnderCursor = tlw;
2590     QPoint pos = widgetUnderCursor->mapFrom(tlw, windowPos);
2591
2592     if (widgetInShow && widgetUnderCursor != widget && !widget->isAncestorOf(widgetUnderCursor))
2593         return; // Mouse cursor not inside the widget or any of its children.
2594
2595     if (widget->data->in_destructor && qt_button_down == widget)
2596         qt_button_down = 0;
2597
2598     // Send enter/leave events followed by a mouse move on the entered widget.
2599     QMouseEvent e(QEvent::MouseMove, pos, windowPos, globalPos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
2600     sendMouseEvent(widgetUnderCursor, &e, widgetUnderCursor, tlw, &qt_button_down, qt_last_mouse_receiver);
2601 #endif // QT_NO_CURSOR
2602 }
2603
2604 /*!
2605     Returns the desktop widget (also called the root window).
2606
2607     The desktop may be composed of multiple screens, so it would be incorrect,
2608     for example, to attempt to \e center some widget in the desktop's geometry.
2609     QDesktopWidget has various functions for obtaining useful geometries upon
2610     the desktop, such as QDesktopWidget::screenGeometry() and
2611     QDesktopWidget::availableGeometry().
2612
2613     On X11, it is also possible to draw on the desktop.
2614 */
2615 QDesktopWidget *QApplication::desktop()
2616 {
2617     if (!qt_desktopWidget || // not created yet
2618          !(qt_desktopWidget->windowType() == Qt::Desktop)) { // reparented away
2619         qt_desktopWidget = new QDesktopWidget();
2620     }
2621     return qt_desktopWidget;
2622 }
2623
2624
2625 /*!
2626     \fn bool QApplication::isSessionRestored() const
2627
2628     Returns true if the application has been restored from an earlier
2629     \l{Session Management}{session}; otherwise returns false.
2630
2631     \sa sessionId(), commitData(), saveState()
2632 */
2633
2634
2635 /*!
2636     \fn QString QApplication::sessionId() const
2637
2638     Returns the current \l{Session Management}{session's} identifier.
2639
2640     If the application has been restored from an earlier session, this
2641     identifier is the same as it was in that previous session. The session
2642     identifier is guaranteed to be unique both for different applications
2643     and for different instances of the same application.
2644
2645     \sa isSessionRestored(), sessionKey(), commitData(), saveState()
2646 */
2647
2648 /*!
2649     \fn QString QApplication::sessionKey() const
2650
2651     Returns the session key in the current \l{Session Management}{session}.
2652
2653     If the application has been restored from an earlier session, this key is
2654     the same as it was when the previous session ended.
2655
2656     The session key changes with every call of commitData() or saveState().
2657
2658     \sa isSessionRestored(), sessionId(), commitData(), saveState()
2659 */
2660 #ifndef QT_NO_SESSIONMANAGER
2661 bool QApplication::isSessionRestored() const
2662 {
2663     Q_D(const QApplication);
2664     return d->is_session_restored;
2665 }
2666
2667 QString QApplication::sessionId() const
2668 {
2669     Q_D(const QApplication);
2670     return d->session_id;
2671 }
2672
2673 QString QApplication::sessionKey() const
2674 {
2675     Q_D(const QApplication);
2676     return d->session_key;
2677 }
2678 #endif
2679
2680
2681
2682 /*!
2683     \since 4.2
2684     \fn void QApplication::commitDataRequest(QSessionManager &manager)
2685
2686     This signal deals with \l{Session Management}{session management}. It is
2687     emitted when the QSessionManager wants the application to commit all its
2688     data.
2689
2690     Usually this means saving all open files, after getting permission from
2691     the user. Furthermore you may want to provide a means by which the user
2692     can cancel the shutdown.
2693
2694     You should not exit the application within this signal. Instead,
2695     the session manager may or may not do this afterwards, depending on the
2696     context.
2697
2698     \warning Within this signal, no user interaction is possible, \e
2699     unless you ask the \a manager for explicit permission. See
2700     QSessionManager::allowsInteraction() and
2701     QSessionManager::allowsErrorInteraction() for details and example
2702     usage.
2703
2704     \note You should use Qt::DirectConnection when connecting to this signal.
2705
2706     \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
2707 */
2708
2709 /*!
2710     This function deals with \l{Session Management}{session management}. It is
2711     invoked when the QSessionManager wants the application to commit all its
2712     data.
2713
2714     Usually this means saving all open files, after getting permission from the
2715     user. Furthermore you may want to provide a means by which the user can
2716     cancel the shutdown.
2717
2718     You should not exit the application within this function. Instead, the
2719     session manager may or may not do this afterwards, depending on the
2720     context.
2721
2722     \warning Within this function, no user interaction is possible, \e
2723     unless you ask the \a manager for explicit permission. See
2724     QSessionManager::allowsInteraction() and
2725     QSessionManager::allowsErrorInteraction() for details and example
2726     usage.
2727
2728     The default implementation requests interaction and sends a close event to
2729     all visible top-level widgets. If any event was rejected, the shutdown is
2730     canceled.
2731
2732     \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
2733 */
2734 #ifndef QT_NO_SESSIONMANAGER
2735 void QApplication::commitData(QSessionManager& manager )
2736 {
2737     emit commitDataRequest(manager);
2738     if (manager.allowsInteraction()) {
2739         QWidgetList done;
2740         QWidgetList list = QApplication::topLevelWidgets();
2741         bool cancelled = false;
2742         for (int i = 0; !cancelled && i < list.size(); ++i) {
2743             QWidget* w = list.at(i);
2744             if (w->isVisible() && !done.contains(w)) {
2745                 cancelled = !w->close();
2746                 if (!cancelled)
2747                     done.append(w);
2748                 list = QApplication::topLevelWidgets();
2749                 i = -1;
2750             }
2751         }
2752         if (cancelled)
2753             manager.cancel();
2754     }
2755 }
2756
2757 /*!
2758     \since 4.2
2759     \fn void QApplication::saveStateRequest(QSessionManager &manager)
2760
2761     This signal deals with \l{Session Management}{session management}. It is
2762     invoked when the \l{QSessionManager}{session manager} wants the application
2763     to preserve its state for a future session.
2764
2765     For example, a text editor would create a temporary file that includes the
2766     current contents of its edit buffers, the location of the cursor and other
2767     aspects of the current editing session.
2768
2769     You should never exit the application within this signal. Instead, the
2770     session manager may or may not do this afterwards, depending on the
2771     context. Futhermore, most session managers will very likely request a saved
2772     state immediately after the application has been started. This permits the
2773     session manager to learn about the application's restart policy.
2774
2775     \warning Within this function, no user interaction is possible, \e
2776     unless you ask the \a manager for explicit permission. See
2777     QSessionManager::allowsInteraction() and
2778     QSessionManager::allowsErrorInteraction() for details.
2779
2780     \note You should use Qt::DirectConnection when connecting to this signal.
2781
2782     \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
2783 */
2784
2785 /*!
2786     This function deals with \l{Session Management}{session management}. It is
2787     invoked when the \l{QSessionManager}{session manager} wants the application
2788     to preserve its state for a future session.
2789
2790     For example, a text editor would create a temporary file that includes the
2791     current contents of its edit buffers, the location of the cursor and other
2792     aspects of the current editing session.
2793
2794     You should never exit the application within this function. Instead, the
2795     session manager may or may not do this afterwards, depending on the
2796     context. Futhermore, most session managers will very likely request a saved
2797     state immediately after the application has been started. This permits the
2798     session manager to learn about the application's restart policy.
2799
2800     \warning Within this function, no user interaction is possible, \e
2801     unless you ask the \a manager for explicit permission. See
2802     QSessionManager::allowsInteraction() and
2803     QSessionManager::allowsErrorInteraction() for details.
2804
2805     \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
2806 */
2807
2808 void QApplication::saveState(QSessionManager &manager)
2809 {
2810     emit saveStateRequest(manager);
2811 }
2812 #endif //QT_NO_SESSIONMANAGER
2813 /*
2814   Sets the time after which a drag should start to \a ms ms.
2815
2816   \sa startDragTime()
2817 */
2818
2819 void QApplication::setStartDragTime(int ms)
2820 {
2821     Q_UNUSED(ms)
2822 }
2823
2824 /*!
2825     \property QApplication::startDragTime
2826     \brief the time in milliseconds that a mouse button must be held down
2827     before a drag and drop operation will begin
2828
2829     If you support drag and drop in your application, and want to start a drag
2830     and drop operation after the user has held down a mouse button for a
2831     certain amount of time, you should use this property's value as the delay.
2832
2833     Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for
2834     starting a drag.
2835
2836     The default value is 500 ms.
2837
2838     \sa startDragDistance(), {Drag and Drop}
2839 */
2840
2841 int QApplication::startDragTime()
2842 {
2843     return qApp->styleHints()->startDragTime();
2844 }
2845
2846 /*
2847     Sets the distance after which a drag should start to \a l pixels.
2848
2849     \sa startDragDistance()
2850 */
2851
2852 void QApplication::setStartDragDistance(int l)
2853 {
2854     Q_UNUSED(l);
2855 }
2856
2857 /*!
2858     \property QApplication::startDragDistance
2859
2860     If you support drag and drop in your application, and want to start a drag
2861     and drop operation after the user has moved the cursor a certain distance
2862     with a button held down, you should use this property's value as the
2863     minimum distance required.
2864
2865     For example, if the mouse position of the click is stored in \c startPos
2866     and the current position (e.g. in the mouse move event) is \c currentPos,
2867     you can find out if a drag should be started with code like this:
2868
2869     \snippet code/src_gui_kernel_qapplication.cpp 7
2870
2871     Qt uses this value internally, e.g. in QFileDialog.
2872
2873     The default value is 4 pixels.
2874
2875     \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop}
2876 */
2877
2878 int QApplication::startDragDistance()
2879 {
2880     return qApp->styleHints()->startDragDistance();
2881 }
2882
2883 /*!
2884     \fn void QApplication::setReverseLayout(bool reverse)
2885
2886     Use setLayoutDirection() instead.
2887 */
2888
2889 /*!
2890     \fn void QApplication::reverseLayout()
2891
2892     Use layoutDirection() instead.
2893 */
2894
2895
2896 /*!
2897     \obsolete
2898
2899     Strips out vertical alignment flags and transforms an alignment \a align
2900     of Qt::AlignLeft into Qt::AlignLeft or Qt::AlignRight according to the
2901     language used.
2902 */
2903
2904
2905 /*!
2906     Enters the main event loop and waits until exit() is called, then returns
2907     the value that was set to exit() (which is 0 if exit() is called via
2908     quit()).
2909
2910     It is necessary to call this function to start event handling. The main
2911     event loop receives events from the window system and dispatches these to
2912     the application widgets.
2913
2914     Generally, no user interaction can take place before calling exec(). As a
2915     special case, modal widgets like QMessageBox can be used before calling
2916     exec(), because modal widgets call exec() to start a local event loop.
2917
2918     To make your application perform idle processing, i.e., executing a special
2919     function whenever there are no pending events, use a QTimer with 0 timeout.
2920     More advanced idle processing schemes can be achieved using processEvents().
2921
2922     We recommend that you connect clean-up code to the
2923     \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
2924     application's \c{main()} function. This is because, on some platforms the
2925     QApplication::exec() call may not return. For example, on the Windows
2926     platform, when the user logs off, the system terminates the process after Qt
2927     closes all top-level windows. Hence, there is \e{no guarantee} that the
2928     application will have time to exit its event loop and execute code at the
2929     end of the \c{main()} function, after the QApplication::exec() call.
2930
2931     \sa quitOnLastWindowClosed, quit(), exit(), processEvents(),
2932         QCoreApplication::exec()
2933 */
2934 int QApplication::exec()
2935 {
2936 #ifndef QT_NO_ACCESSIBILITY
2937     QAccessible::setRootObject(qApp);
2938 #endif
2939     return QGuiApplication::exec();
2940 }
2941
2942 bool QApplicationPrivate::shouldQuit()
2943 {
2944     /* if there is no non-withdrawn primary window left (except
2945         the ones without QuitOnClose), we emit the lastWindowClosed
2946         signal */
2947     QWidgetList list = QApplication::topLevelWidgets();
2948     for (int i = 0; i < list.size(); ++i) {
2949         QWidget *w = list.at(i);
2950         if (w->isVisible() && !w->parentWidget() && w->testAttribute(Qt::WA_QuitOnClose))
2951             return false;
2952     }
2953     return true;
2954 }
2955
2956 /*! \reimp
2957  */
2958 bool QApplication::notify(QObject *receiver, QEvent *e)
2959 {
2960     Q_D(QApplication);
2961     // no events are delivered after ~QCoreApplication() has started
2962     if (QApplicationPrivate::is_app_closing)
2963         return true;
2964
2965     if (receiver == 0) {                        // serious error
2966         qWarning("QApplication::notify: Unexpected null receiver");
2967         return true;
2968     }
2969
2970 #ifndef QT_NO_DEBUG
2971     d->checkReceiverThread(receiver);
2972 #endif
2973
2974     QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(qobject_cast<QWindow *>(receiver), e);
2975
2976     // capture the current mouse/keyboard state
2977     if(e->spontaneous()) {
2978         if (e->type() == QEvent::MouseButtonPress
2979             || e->type() == QEvent::MouseButtonRelease) {
2980                 QMouseEvent *me = static_cast<QMouseEvent*>(e);
2981                 if(me->type() == QEvent::MouseButtonPress)
2982                     QApplicationPrivate::mouse_buttons |= me->button();
2983                 else
2984                     QApplicationPrivate::mouse_buttons &= ~me->button();
2985             }
2986     }
2987
2988 #ifndef QT_NO_GESTURES
2989     // walk through parents and check for gestures
2990     if (d->gestureManager) {
2991         switch (e->type()) {
2992         case QEvent::Paint:
2993         case QEvent::MetaCall:
2994         case QEvent::DeferredDelete:
2995         case QEvent::DragEnter: case QEvent::DragMove: case QEvent::DragLeave:
2996         case QEvent::Drop: case QEvent::DragResponse:
2997         case QEvent::ChildAdded: case QEvent::ChildPolished:
2998         case QEvent::ChildRemoved:
2999         case QEvent::UpdateRequest:
3000         case QEvent::UpdateLater:
3001         case QEvent::LocaleChange:
3002         case QEvent::Style:
3003         case QEvent::IconDrag:
3004         case QEvent::StyleChange:
3005         case QEvent::GraphicsSceneDragEnter:
3006         case QEvent::GraphicsSceneDragMove:
3007         case QEvent::GraphicsSceneDragLeave:
3008         case QEvent::GraphicsSceneDrop:
3009         case QEvent::DynamicPropertyChange:
3010         case QEvent::NetworkReplyUpdated:
3011             break;
3012         default:
3013             if (receiver->isWidgetType()) {
3014                 if (d->gestureManager->filterEvent(static_cast<QWidget *>(receiver), e))
3015                     return true;
3016             } else {
3017                 // a special case for events that go to QGesture objects.
3018                 // We pass the object to the gesture manager and it'll figure
3019                 // out if it's QGesture or not.
3020                 if (d->gestureManager->filterEvent(receiver, e))
3021                     return true;
3022             }
3023         }
3024     }
3025 #endif // QT_NO_GESTURES
3026
3027     // User input and window activation makes tooltips sleep
3028     switch (e->type()) {
3029     case QEvent::Wheel:
3030     case QEvent::ActivationChange:
3031     case QEvent::KeyPress:
3032     case QEvent::KeyRelease:
3033     case QEvent::FocusOut:
3034     case QEvent::FocusIn:
3035     case QEvent::MouseButtonPress:
3036     case QEvent::MouseButtonRelease:
3037     case QEvent::MouseButtonDblClick:
3038         d->toolTipFallAsleep.stop();
3039         // fall-through
3040     case QEvent::Leave:
3041         d->toolTipWakeUp.stop();
3042     default:
3043         break;
3044     }
3045
3046     bool res = false;
3047     if (!receiver->isWidgetType()) {
3048         res = d->notify_helper(receiver, e);
3049     } else switch (e->type()) {
3050     case QEvent::ShortcutOverride:
3051     case QEvent::KeyPress:
3052     case QEvent::KeyRelease:
3053         {
3054             bool isWidget = receiver->isWidgetType();
3055             bool isGraphicsWidget = false;
3056 #ifndef QT_NO_GRAPHICSVIEW
3057             isGraphicsWidget = !isWidget && qobject_cast<QGraphicsWidget *>(receiver);
3058 #endif
3059             if (!isWidget && !isGraphicsWidget) {
3060                 res = d->notify_helper(receiver, e);
3061                 break;
3062             }
3063
3064             QKeyEvent* key = static_cast<QKeyEvent*>(e);
3065             if (key->type()==QEvent::KeyPress) {
3066 #ifndef QT_NO_SHORTCUT
3067                 // Try looking for a Shortcut before sending key events
3068                 if ((res = qApp->d_func()->shortcutMap.tryShortcutEvent(receiver, key)))
3069                     return res;
3070 #endif
3071                 qt_in_tab_key_event = (key->key() == Qt::Key_Backtab
3072                                        || key->key() == Qt::Key_Tab
3073                                        || key->key() == Qt::Key_Left
3074                                        || key->key() == Qt::Key_Up
3075                                        || key->key() == Qt::Key_Right
3076                                        || key->key() == Qt::Key_Down);
3077             }
3078             bool def = key->isAccepted();
3079             QPointer<QObject> pr = receiver;
3080             while (receiver) {
3081                 if (def)
3082                     key->accept();
3083                 else
3084                     key->ignore();
3085                 res = d->notify_helper(receiver, e);
3086                 QWidget *w = isWidget ? static_cast<QWidget *>(receiver) : 0;
3087 #ifndef QT_NO_GRAPHICSVIEW
3088                 QGraphicsWidget *gw = isGraphicsWidget ? static_cast<QGraphicsWidget *>(receiver) : 0;
3089 #endif
3090
3091                 if ((res && key->isAccepted())
3092                     /*
3093                        QLineEdit will emit a signal on Key_Return, but
3094                        ignore the event, and sometimes the connected
3095                        slot deletes the QLineEdit (common in itemview
3096                        delegates), so we have to check if the widget
3097                        was destroyed even if the event was ignored (to
3098                        prevent a crash)
3099
3100                        note that we don't have to reset pw while
3101                        propagating (because the original receiver will
3102                        be destroyed if one of its ancestors is)
3103                     */
3104                     || !pr
3105                     || (isWidget && (w->isWindow() || !w->parentWidget()))
3106 #ifndef QT_NO_GRAPHICSVIEW
3107                     || (isGraphicsWidget && (gw->isWindow() || !gw->parentWidget()))
3108 #endif
3109                     ) {
3110                     break;
3111                 }
3112
3113 #ifndef QT_NO_GRAPHICSVIEW
3114                 receiver = w ? (QObject *)w->parentWidget() : (QObject *)gw->parentWidget();
3115 #else
3116                 receiver = w->parentWidget();
3117 #endif
3118             }
3119             qt_in_tab_key_event = false;
3120         }
3121         break;
3122     case QEvent::MouseButtonPress:
3123     case QEvent::MouseButtonRelease:
3124     case QEvent::MouseButtonDblClick:
3125     case QEvent::MouseMove:
3126         {
3127             QWidget* w = static_cast<QWidget *>(receiver);
3128
3129             QMouseEvent* mouse = static_cast<QMouseEvent*>(e);
3130             QPoint relpos = mouse->pos();
3131
3132             if (e->spontaneous()) {
3133
3134                 if (e->type() == QEvent::MouseButtonPress) {
3135                     QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3136                                                                          Qt::ClickFocus,
3137                                                                          Qt::MouseFocusReason);
3138                 }
3139
3140                 // ### Qt 5 These dynamic tool tips should be an OPT-IN feature. Some platforms
3141                 // like Mac OS X (probably others too), can optimize their views by not
3142                 // dispatching mouse move events. We have attributes to control hover,
3143                 // and mouse tracking, but as long as we are deciding to implement this
3144                 // feature without choice of opting-in or out, you ALWAYS have to have
3145                 // tracking enabled. Therefore, the other properties give a false sense of
3146                 // performance enhancement.
3147                 if (e->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3148                     d->toolTipWidget = w;
3149                     d->toolTipPos = relpos;
3150                     d->toolTipGlobalPos = mouse->globalPos();
3151                     d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive()?20:700, this);
3152                 }
3153             }
3154
3155             bool eventAccepted = mouse->isAccepted();
3156
3157             QPointer<QWidget> pw = w;
3158             while (w) {
3159                 QMouseEvent me(mouse->type(), relpos, mouse->windowPos(), mouse->globalPos(), mouse->button(), mouse->buttons(),
3160                                mouse->modifiers());
3161                 me.spont = mouse->spontaneous();
3162                 me.setTimestamp(mouse->timestamp());
3163                 // throw away any mouse-tracking-only mouse events
3164                 if (!w->hasMouseTracking()
3165                     && mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3166                     // but still send them through all application event filters (normally done by notify_helper)
3167                     for (int i = 0; d->extraData && i < d->extraData->eventFilters.size(); ++i) {
3168                         register QObject *obj = d->extraData->eventFilters.at(i);
3169                         if (!obj)
3170                             continue;
3171                         if (obj->d_func()->threadData != w->d_func()->threadData) {
3172                             qWarning("QApplication: Object event filter cannot be in a different thread.");
3173                             continue;
3174                         }
3175                         if (obj->eventFilter(w, w == receiver ? mouse : &me))
3176                             break;
3177                     }
3178                     res = true;
3179                 } else {
3180                     w->setAttribute(Qt::WA_NoMouseReplay, false);
3181                     res = d->notify_helper(w, w == receiver ? mouse : &me);
3182                     e->spont = false;
3183                 }
3184                 eventAccepted = (w == receiver ? mouse : &me)->isAccepted();
3185                 if (res && eventAccepted)
3186                     break;
3187                 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3188                     break;
3189                 relpos += w->pos();
3190                 w = w->parentWidget();
3191             }
3192
3193             mouse->setAccepted(eventAccepted);
3194
3195             if (e->type() == QEvent::MouseMove) {
3196                 if (!pw)
3197                     break;
3198
3199                 w = static_cast<QWidget *>(receiver);
3200                 relpos = mouse->pos();
3201                 QPoint diff = relpos - w->mapFromGlobal(d->hoverGlobalPos);
3202                 while (w) {
3203                     if (w->testAttribute(Qt::WA_Hover) &&
3204                         (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
3205                         QHoverEvent he(QEvent::HoverMove, relpos, relpos - diff, mouse->modifiers());
3206                         d->notify_helper(w, &he);
3207                     }
3208                     if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3209                         break;
3210                     relpos += w->pos();
3211                     w = w->parentWidget();
3212                 }
3213             }
3214
3215             d->hoverGlobalPos = mouse->globalPos();
3216         }
3217         break;
3218 #ifndef QT_NO_WHEELEVENT
3219     case QEvent::Wheel:
3220         {
3221             QWidget* w = static_cast<QWidget *>(receiver);
3222             QWheelEvent* wheel = static_cast<QWheelEvent*>(e);
3223             QPoint relpos = wheel->pos();
3224             bool eventAccepted = wheel->isAccepted();
3225
3226             if (e->spontaneous()) {
3227                 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3228                                                                      Qt::WheelFocus,
3229                                                                      Qt::MouseFocusReason);
3230             }
3231
3232             while (w) {
3233                 QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
3234                                wheel->modifiers());
3235                 we.spont = wheel->spontaneous();
3236                 res = d->notify_helper(w, w == receiver ? wheel : &we);
3237                 eventAccepted = ((w == receiver) ? wheel : &we)->isAccepted();
3238                 e->spont = false;
3239                 if ((res && eventAccepted)
3240                     || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3241                     break;
3242
3243                 relpos += w->pos();
3244                 w = w->parentWidget();
3245             }
3246             wheel->setAccepted(eventAccepted);
3247         }
3248         break;
3249 #endif
3250 #ifndef QT_NO_CONTEXTMENU
3251     case QEvent::ContextMenu:
3252         {
3253             QWidget* w = static_cast<QWidget *>(receiver);
3254             QContextMenuEvent *context = static_cast<QContextMenuEvent*>(e);
3255             QPoint relpos = context->pos();
3256             bool eventAccepted = context->isAccepted();
3257             while (w) {
3258                 QContextMenuEvent ce(context->reason(), relpos, context->globalPos(), context->modifiers());
3259                 ce.spont = e->spontaneous();
3260                 res = d->notify_helper(w, w == receiver ? context : &ce);
3261                 eventAccepted = ((w == receiver) ? context : &ce)->isAccepted();
3262                 e->spont = false;
3263
3264                 if ((res && eventAccepted)
3265                     || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3266                     break;
3267
3268                 relpos += w->pos();
3269                 w = w->parentWidget();
3270             }
3271             context->setAccepted(eventAccepted);
3272         }
3273         break;
3274 #endif // QT_NO_CONTEXTMENU
3275 #ifndef QT_NO_TABLETEVENT
3276     case QEvent::TabletMove:
3277     case QEvent::TabletPress:
3278     case QEvent::TabletRelease:
3279         {
3280             QWidget *w = static_cast<QWidget *>(receiver);
3281             QTabletEvent *tablet = static_cast<QTabletEvent*>(e);
3282             QPointF relpos = tablet->posF();
3283             bool eventAccepted = tablet->isAccepted();
3284             while (w) {
3285                 QTabletEvent te(tablet->type(), relpos, tablet->globalPosF(),
3286                                 tablet->device(), tablet->pointerType(),
3287                                 tablet->pressure(), tablet->xTilt(), tablet->yTilt(),
3288                                 tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
3289                                 tablet->modifiers(), tablet->uniqueId());
3290                 te.spont = e->spontaneous();
3291                 res = d->notify_helper(w, w == receiver ? tablet : &te);
3292                 eventAccepted = ((w == receiver) ? tablet : &te)->isAccepted();
3293                 e->spont = false;
3294                 if ((res && eventAccepted)
3295                      || w->isWindow()
3296                      || w->testAttribute(Qt::WA_NoMousePropagation))
3297                     break;
3298
3299                 relpos += w->pos();
3300                 w = w->parentWidget();
3301             }
3302             tablet->setAccepted(eventAccepted);
3303             qt_tabletChokeMouse = tablet->isAccepted();
3304         }
3305         break;
3306 #endif // QT_NO_TABLETEVENT
3307
3308 #if !defined(QT_NO_TOOLTIP) || !defined(QT_NO_WHATSTHIS)
3309     case QEvent::ToolTip:
3310     case QEvent::WhatsThis:
3311     case QEvent::QueryWhatsThis:
3312         {
3313             QWidget* w = static_cast<QWidget *>(receiver);
3314             QHelpEvent *help = static_cast<QHelpEvent*>(e);
3315             QPoint relpos = help->pos();
3316             bool eventAccepted = help->isAccepted();
3317             while (w) {
3318                 QHelpEvent he(help->type(), relpos, help->globalPos());
3319                 he.spont = e->spontaneous();
3320                 res = d->notify_helper(w, w == receiver ? help : &he);
3321                 e->spont = false;
3322                 eventAccepted = (w == receiver ? help : &he)->isAccepted();
3323                 if ((res && eventAccepted) || w->isWindow())
3324                     break;
3325
3326                 relpos += w->pos();
3327                 w = w->parentWidget();
3328             }
3329             help->setAccepted(eventAccepted);
3330         }
3331         break;
3332 #endif
3333 #if !defined(QT_NO_STATUSTIP) || !defined(QT_NO_WHATSTHIS)
3334     case QEvent::StatusTip:
3335     case QEvent::WhatsThisClicked:
3336         {
3337             QWidget *w = static_cast<QWidget *>(receiver);
3338             while (w) {
3339                 res = d->notify_helper(w, e);
3340                 if ((res && e->isAccepted()) || w->isWindow())
3341                     break;
3342                 w = w->parentWidget();
3343             }
3344         }
3345         break;
3346 #endif
3347
3348 #ifndef QT_NO_DRAGANDDROP
3349     case QEvent::DragEnter: {
3350             QWidget* w = static_cast<QWidget *>(receiver);
3351             QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent *>(e);
3352 #ifndef QT_NO_GRAPHICSVIEW
3353             // QGraphicsProxyWidget handles its own propagation,
3354             // and we must not change QDragManagers currentTarget.
3355             QWExtra *extra = w->window()->d_func()->extra;
3356             if (extra && extra->proxyWidget) {
3357                 res = d->notify_helper(w, dragEvent);
3358                 break;
3359             }
3360 #endif
3361             while (w) {
3362                 if (w->isEnabled() && w->acceptDrops()) {
3363                     res = d->notify_helper(w, dragEvent);
3364                     if (res && dragEvent->isAccepted()) {
3365                         QDragManager::self()->setCurrentTarget(w);
3366                         break;
3367                     }
3368                 }
3369                 if (w->isWindow())
3370                     break;
3371                 dragEvent->p = w->mapToParent(dragEvent->p.toPoint());
3372                 w = w->parentWidget();
3373             }
3374         }
3375         break;
3376     case QEvent::DragMove:
3377     case QEvent::Drop:
3378     case QEvent::DragLeave: {
3379             QWidget* w = static_cast<QWidget *>(receiver);
3380 #ifndef QT_NO_GRAPHICSVIEW
3381             // QGraphicsProxyWidget handles its own propagation,
3382             // and we must not change QDragManagers currentTarget.
3383             QWExtra *extra = w->window()->d_func()->extra;
3384             bool isProxyWidget = extra && extra->proxyWidget;
3385             if (!isProxyWidget)
3386 #endif
3387                 w = qobject_cast<QWidget *>(QDragManager::self()->currentTarget());
3388
3389             if (!w) {
3390                     break;
3391             }
3392             if (e->type() == QEvent::DragMove || e->type() == QEvent::Drop) {
3393                 QDropEvent *dragEvent = static_cast<QDropEvent *>(e);
3394                 QWidget *origReciver = static_cast<QWidget *>(receiver);
3395                 while (origReciver && w != origReciver) {
3396                     dragEvent->p = origReciver->mapToParent(dragEvent->p.toPoint());
3397                     origReciver = origReciver->parentWidget();
3398                 }
3399             }
3400             res = d->notify_helper(w, e);
3401             if (e->type() != QEvent::DragMove
3402 #ifndef QT_NO_GRAPHICSVIEW
3403                 && !isProxyWidget
3404 #endif
3405                 )
3406                 QDragManager::self()->setCurrentTarget(0, e->type() == QEvent::Drop);
3407         }
3408         break;
3409 #endif
3410     case QEvent::TouchBegin:
3411     // Note: TouchUpdate and TouchEnd events are never propagated
3412     {
3413         QWidget *widget = static_cast<QWidget *>(receiver);
3414         QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
3415         bool eventAccepted = touchEvent->isAccepted();
3416         if (widget->testAttribute(Qt::WA_AcceptTouchEvents) && e->spontaneous()) {
3417             // give the widget focus if the focus policy allows it
3418             QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget,
3419                                                                  Qt::ClickFocus,
3420                                                                  Qt::MouseFocusReason);
3421         }
3422
3423         while (widget) {
3424             // first, try to deliver the touch event
3425             bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
3426             touchEvent->setTarget(widget);
3427             touchEvent->setAccepted(acceptTouchEvents);
3428             QPointer<QWidget> p = widget;
3429             res = acceptTouchEvents && d->notify_helper(widget, touchEvent);
3430             eventAccepted = touchEvent->isAccepted();
3431             if (p.isNull()) {
3432                 // widget was deleted
3433                 widget = 0;
3434             } else {
3435                 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
3436             }
3437             touchEvent->spont = false;
3438             if (res && eventAccepted) {
3439                 // the first widget to accept the TouchBegin gets an implicit grab.
3440                 for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
3441                     const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i);
3442                     d->activeTouchPoints[QGuiApplicationPrivate::ActiveTouchPointsKey(touchEvent->device(), touchPoint.id())].target = widget;
3443                 }
3444                 break;
3445             } else if (p.isNull() || widget->isWindow() || widget->testAttribute(Qt::WA_NoMousePropagation)) {
3446                 break;
3447             }
3448             QPoint offset = widget->pos();
3449             widget = widget->parentWidget();
3450             touchEvent->setTarget(widget);
3451             for (int i = 0; i < touchEvent->_touchPoints.size(); ++i) {
3452                 QTouchEvent::TouchPoint &pt = touchEvent->_touchPoints[i];
3453                 QRectF rect = pt.rect();
3454                 rect.moveCenter(offset);
3455                 pt.d->rect = rect;
3456                 pt.d->startPos = pt.startPos() + offset;
3457                 pt.d->lastPos = pt.lastPos() + offset;
3458             }
3459         }
3460
3461         touchEvent->setAccepted(eventAccepted);
3462         break;
3463     }
3464     case QEvent::RequestSoftwareInputPanel:
3465         inputMethod()->show();
3466         break;
3467     case QEvent::CloseSoftwareInputPanel:
3468         inputMethod()->hide();
3469         break;
3470
3471 #ifndef QT_NO_GESTURES
3472     case QEvent::NativeGesture:
3473     {
3474         // only propagate the first gesture event (after the GID_BEGIN)
3475         QWidget *w = static_cast<QWidget *>(receiver);
3476         while (w) {
3477             e->ignore();
3478             res = d->notify_helper(w, e);
3479             if ((res && e->isAccepted()) || w->isWindow())
3480                 break;
3481             w = w->parentWidget();
3482         }
3483         break;
3484     }
3485     case QEvent::Gesture:
3486     case QEvent::GestureOverride:
3487     {
3488         if (receiver->isWidgetType()) {
3489             QWidget *w = static_cast<QWidget *>(receiver);
3490             QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(e);
3491             QList<QGesture *> allGestures = gestureEvent->gestures();
3492
3493             bool eventAccepted = gestureEvent->isAccepted();
3494             bool wasAccepted = eventAccepted;
3495             while (w) {
3496                 // send only gestures the widget expects
3497                 QList<QGesture *> gestures;
3498                 QWidgetPrivate *wd = w->d_func();
3499                 for (int i = 0; i < allGestures.size();) {
3500                     QGesture *g = allGestures.at(i);
3501                     Qt::GestureType type = g->gestureType();
3502                     QMap<Qt::GestureType, Qt::GestureFlags>::iterator contextit =
3503                             wd->gestureContext.find(type);
3504                     bool deliver = contextit != wd->gestureContext.end() &&
3505                         (g->state() == Qt::GestureStarted || w == receiver ||
3506                          (contextit.value() & Qt::ReceivePartialGestures));
3507                     if (deliver) {
3508                         allGestures.removeAt(i);
3509                         gestures.append(g);
3510                     } else {
3511                         ++i;
3512                     }
3513                 }
3514                 if (!gestures.isEmpty()) { // we have gestures for this w
3515                     QGestureEvent ge(gestures);
3516                     ge.t = gestureEvent->t;
3517                     ge.spont = gestureEvent->spont;
3518                     ge.m_accept = wasAccepted;
3519                     ge.m_accepted = gestureEvent->m_accepted;
3520                     res = d->notify_helper(w, &ge);
3521                     gestureEvent->spont = false;
3522                     eventAccepted = ge.isAccepted();
3523                     for (int i = 0; i < gestures.size(); ++i) {
3524                         QGesture *g = gestures.at(i);
3525                         // Ignore res [event return value] because handling of multiple gestures
3526                         // packed into a single QEvent depends on not consuming the event
3527                         if (eventAccepted || ge.isAccepted(g)) {
3528                             // if the gesture was accepted, mark the target widget for it
3529                             gestureEvent->m_targetWidgets[g->gestureType()] = w;
3530                             gestureEvent->setAccepted(g, true);
3531                         } else {
3532                             // if the gesture was explicitly ignored by the application,
3533                             // put it back so a parent can get it
3534                             allGestures.append(g);
3535                         }
3536                     }
3537                 }
3538                 if (allGestures.isEmpty()) // everything delivered
3539                     break;
3540                 if (w->isWindow())
3541                     break;
3542                 w = w->parentWidget();
3543             }
3544             foreach (QGesture *g, allGestures)
3545                 gestureEvent->setAccepted(g, false);
3546             gestureEvent->m_accept = false; // to make sure we check individual gestures
3547         } else {
3548             res = d->notify_helper(receiver, e);
3549         }
3550         break;
3551     }
3552 #endif // QT_NO_GESTURES
3553     default:
3554         res = d->notify_helper(receiver, e);
3555         break;
3556     }
3557
3558     return res;
3559 }
3560
3561 bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
3562 {
3563     // send to all application event filters
3564     if (sendThroughApplicationEventFilters(receiver, e))
3565         return true;
3566
3567     if (receiver->isWidgetType()) {
3568         QWidget *widget = static_cast<QWidget *>(receiver);
3569
3570 #if !defined(Q_OS_WINCE) || (defined(GWES_ICONCURS) && !defined(QT_NO_CURSOR))
3571         // toggle HasMouse widget state on enter and leave
3572         if ((e->type() == QEvent::Enter || e->type() == QEvent::DragEnter) &&
3573             (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == widget->window()))
3574             widget->setAttribute(Qt::WA_UnderMouse, true);
3575         else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave)
3576             widget->setAttribute(Qt::WA_UnderMouse, false);
3577 #endif
3578
3579         if (QLayout *layout=widget->d_func()->layout) {
3580             layout->widgetEvent(e);
3581         }
3582     }
3583
3584     // send to all receiver event filters
3585     if (sendThroughObjectEventFilters(receiver, e))
3586         return true;
3587
3588     // deliver the event
3589     bool consumed = receiver->event(e);
3590     e->spont = false;
3591     return consumed;
3592 }
3593
3594
3595 /*!
3596     \class QSessionManager
3597     \brief The QSessionManager class provides access to the session manager.
3598
3599     \inmodule QtWidgets
3600
3601     A session manager in a desktop environment (in which Qt GUI applications
3602     live) keeps track of a session, which is a group of running applications,
3603     each of which has a particular state. The state of an application contains
3604     (most notably) the documents the application has open and the position and
3605     size of its windows.
3606
3607     The session manager is used to save the session, e.g., when the machine is
3608     shut down, and to restore a session, e.g., when the machine is started up.
3609     We recommend that you use QSettings to save an application's settings,
3610     for example, window positions, recently used files, etc. When the
3611     application is restarted by the session manager, you can restore the
3612     settings.
3613
3614     QSessionManager provides an interface between the application and the
3615     session manager so that the program can work well with the session manager.
3616     In Qt, session management requests for action are handled by the two
3617     virtual functions QApplication::commitData() and QApplication::saveState().
3618     Both provide a reference to a session manager object as argument, to allow
3619     the application to communicate with the session manager. The session
3620     manager can only be accessed through these functions.
3621
3622     No user interaction is possible \e unless the application gets explicit
3623     permission from the session manager. You ask for permission by calling
3624     allowsInteraction() or, if it is really urgent, allowsErrorInteraction().
3625     Qt does not enforce this, but the session manager may.
3626
3627     You can try to abort the shutdown process by calling cancel(). The default
3628     commitData() function does this if some top-level window rejected its
3629     closeEvent().
3630
3631     For sophisticated session managers provided on Unix/X11, QSessionManager
3632     offers further possibilities to fine-tune an application's session
3633     management behavior: setRestartCommand(), setDiscardCommand(),
3634     setRestartHint(), setProperty(), requestPhase2(). See the respective
3635     function descriptions for further details.
3636
3637     \sa QApplication, {Session Management}
3638 */
3639
3640 /*! \enum QSessionManager::RestartHint
3641
3642     This enum type defines the circumstances under which this application wants
3643     to be restarted by the session manager. The current values are:
3644
3645     \value  RestartIfRunning    If the application is still running when the
3646                                 session is shut down, it wants to be restarted
3647                                 at the start of the next session.
3648
3649     \value  RestartAnyway       The application wants to be started at the
3650                                 start of the next session, no matter what.
3651                                 (This is useful for utilities that run just
3652                                 after startup and then quit.)
3653
3654     \value  RestartImmediately  The application wants to be started immediately
3655                                 whenever it is not running.
3656
3657     \value  RestartNever        The application does not want to be restarted
3658                                 automatically.
3659
3660     The default hint is \c RestartIfRunning.
3661 */
3662
3663
3664 /*!
3665     \fn QString QSessionManager::sessionId() const
3666
3667     Returns the identifier of the current session.
3668
3669     If the application has been restored from an earlier session, this
3670     identifier is the same as it was in the earlier session.
3671
3672     \sa sessionKey(), QApplication::sessionId()
3673 */
3674
3675 /*!
3676     \fn QString QSessionManager::sessionKey() const
3677
3678     Returns the session key in the current session.
3679
3680     If the application has been restored from an earlier session, this key is
3681     the same as it was when the previous session ended.
3682
3683     The session key changes with every call of commitData() or saveState().
3684
3685     \sa sessionId(), QApplication::sessionKey()
3686 */
3687
3688 /*!
3689     \fn void* QSessionManager::handle() const
3690
3691     \internal
3692 */
3693
3694 /*!
3695     \fn bool QSessionManager::allowsInteraction()
3696
3697     Asks the session manager for permission to interact with the user. Returns
3698     true if interaction is permitted; otherwise returns false.
3699
3700     The rationale behind this mechanism is to make it possible to synchronize
3701     user interaction during a shutdown. Advanced session managers may ask all
3702     applications simultaneously to commit their data, resulting in a much
3703     faster shutdown.
3704
3705     When the interaction is completed we strongly recommend releasing the user
3706     interaction semaphore with a call to release(). This way, other
3707     applications may get the chance to interact with the user while your
3708     application is still busy saving data. (The semaphore is implicitly
3709     released when the application exits.)
3710
3711     If the user decides to cancel the shutdown process during the interaction
3712     phase, you must tell the session manager that this has happened by calling
3713     cancel().
3714
3715     Here's an example of how an application's QApplication::commitData() might
3716     be implemented:
3717
3718     \snippet code/src_gui_kernel_qapplication.cpp 8
3719
3720     If an error occurred within the application while saving its data, you may
3721     want to try allowsErrorInteraction() instead.
3722
3723     \sa QApplication::commitData(), release(), cancel()
3724 */
3725
3726
3727 /*!
3728     \fn bool QSessionManager::allowsErrorInteraction()
3729
3730     Returns true if error interaction is permitted; otherwise returns false.
3731
3732     This is similar to allowsInteraction(), but also enables the application to
3733     tell the user about any errors that occur. Session managers may give error
3734     interaction requests higher priority, which means that it is more likely
3735     that an error interaction is permitted. However, you are still not
3736     guaranteed that the session manager will allow interaction.
3737
3738     \sa allowsInteraction(), release(), cancel()
3739 */
3740
3741 /*!
3742     \fn void QSessionManager::release()
3743
3744     Releases the session manager's interaction semaphore after an interaction
3745     phase.
3746
3747     \sa allowsInteraction(), allowsErrorInteraction()
3748 */
3749
3750 /*!
3751     \fn void QSessionManager::cancel()
3752
3753     Tells the session manager to cancel the shutdown process.  Applications
3754     should not call this function without asking the user first.
3755
3756     \sa allowsInteraction(), allowsErrorInteraction()
3757 */
3758
3759 /*!
3760     \fn void QSessionManager::setRestartHint(RestartHint hint)
3761
3762     Sets the application's restart hint to \a hint. On application startup, the
3763     hint is set to \c RestartIfRunning.
3764
3765     \note These flags are only hints, a session manager may or may not respect
3766     them.
3767
3768     We recommend setting the restart hint in QApplication::saveState() because
3769     most session managers perform a checkpoint shortly after an application's
3770     startup.
3771
3772     \sa restartHint()
3773 */
3774
3775 /*!
3776     \fn QSessionManager::RestartHint QSessionManager::restartHint() const
3777
3778     Returns the application's current restart hint. The default is
3779     \c RestartIfRunning.
3780
3781     \sa setRestartHint()
3782 */
3783
3784 /*!
3785     \fn void QSessionManager::setRestartCommand(const QStringList& command)
3786
3787     If the session manager is capable of restoring sessions it will execute
3788     \a command in order to restore the application. The command defaults to
3789
3790     \snippet code/src_gui_kernel_qapplication.cpp 9
3791
3792     The \c -session option is mandatory; otherwise QApplication cannot tell
3793     whether it has been restored or what the current session identifier is.
3794     See QApplication::isSessionRestored() and QApplication::sessionId() for
3795     details.
3796
3797     If your application is very simple, it may be possible to store the entire
3798     application state in additional command line options. This is usually a
3799     very bad idea because command lines are often limited to a few hundred
3800     bytes. Instead, use QSettings, temporary files, or a database for this
3801     purpose. By marking the data with the unique sessionId(), you will be able
3802     to restore the application in a future  session.
3803
3804     \sa restartCommand(), setDiscardCommand(), setRestartHint()
3805 */
3806
3807 /*!
3808     \fn QStringList QSessionManager::restartCommand() const
3809
3810     Returns the currently set restart command.
3811
3812     To iterate over the list, you can use the \l foreach pseudo-keyword:
3813
3814     \snippet code/src_gui_kernel_qapplication.cpp 10
3815
3816     \sa setRestartCommand(), restartHint()
3817 */
3818
3819 /*!
3820     \fn void QSessionManager::setDiscardCommand(const QStringList& list)
3821
3822     Sets the discard command to the given \a list.
3823
3824     \sa discardCommand(), setRestartCommand()
3825 */
3826
3827
3828 /*!
3829     \fn QStringList QSessionManager::discardCommand() const
3830
3831     Returns the currently set discard command.
3832
3833     To iterate over the list, you can use the \l foreach pseudo-keyword:
3834
3835     \snippet code/src_gui_kernel_qapplication.cpp 11
3836
3837     \sa setDiscardCommand(), restartCommand(), setRestartCommand()
3838 */
3839
3840 /*!
3841     \fn void QSessionManager::setManagerProperty(const QString &name, const QString &value)
3842     \overload
3843
3844     Low-level write access to the application's identification and state
3845     records are kept in the session manager.
3846
3847     The property called \a name has its value set to the string \a value.
3848 */
3849
3850 /*!
3851     \fn void QSessionManager::setManagerProperty(const QString& name,
3852                                                  const QStringList& value)
3853
3854     Low-level write access to the application's identification and state record
3855     are kept in the session manager.
3856
3857     The property called \a name has its value set to the string list \a value.
3858 */
3859
3860 /*!
3861     \fn bool QSessionManager::isPhase2() const
3862
3863     Returns true if the session manager is currently performing a second
3864     session management phase; otherwise returns false.
3865
3866     \sa requestPhase2()
3867 */
3868
3869 /*!
3870     \fn void QSessionManager::requestPhase2()
3871
3872     Requests a second session management phase for the application. The
3873     application may then return immediately from the QApplication::commitData()
3874     or QApplication::saveState() function, and they will be called again once
3875     most or all other applications have finished their session management.
3876
3877     The two phases are useful for applications such as the X11 window manager
3878     that need to store information about another application's windows and
3879     therefore have to wait until these applications have completed their
3880     respective session management tasks.
3881
3882     \note If another application has requested a second phase it may get called
3883     before, simultaneously with, or after your application's second phase.
3884
3885     \sa isPhase2()
3886 */
3887
3888 /*!
3889     \fn Qt::MacintoshVersion QApplication::macVersion()
3890
3891     Use QSysInfo::MacintoshVersion instead.
3892 */
3893
3894 /*!
3895     \fn QApplication::ColorMode QApplication::colorMode()
3896
3897     Use colorSpec() instead, and use ColorSpec as the enum type.
3898 */
3899
3900 /*!
3901     \fn void QApplication::setColorMode(ColorMode mode)
3902
3903     Use setColorSpec() instead, and pass a ColorSpec value instead.
3904 */
3905
3906 /*!
3907     \fn bool QApplication::hasGlobalMouseTracking()
3908
3909     This feature does not exist anymore. This function always returns true
3910     in Qt 4.
3911 */
3912
3913 /*!
3914     \fn void QApplication::setGlobalMouseTracking(bool dummy)
3915
3916     This function does nothing in Qt 4. The \a dummy parameter is ignored.
3917 */
3918
3919 /*!
3920     \fn void QApplication::flushX()
3921
3922     Use flush() instead.
3923 */
3924
3925 /*!
3926     \fn void QApplication::setWinStyleHighlightColor(const QColor &c)
3927
3928     Use the palette instead.
3929
3930     \oldcode
3931     app.setWinStyleHighlightColor(color);
3932     \newcode
3933     QPalette palette(QApplication::palette());
3934     palette.setColor(QPalette::Highlight, color);
3935     QApplication::setPalette(palette);
3936     \endcode
3937 */
3938
3939 /*!
3940     \fn void QApplication::setPalette(const QPalette &pal, bool b, const char* className = 0)
3941
3942     Use the two-argument overload instead.
3943 */
3944
3945 /*!
3946     \fn void QApplication::setFont(const QFont &font, bool b, const char* className = 0)
3947
3948     Use the two-argument overload instead.
3949 */
3950
3951 /*!
3952     \fn const QColor &QApplication::winStyleHighlightColor()
3953
3954     Use QApplication::palette().color(QPalette::Active, QPalette::Highlight) instead.
3955 */
3956
3957 /*!
3958     \fn QWidget *QApplication::widgetAt(int x, int y, bool child)
3959
3960     Use the two-argument widgetAt() overload to get the child widget. To get
3961     the top-level widget do this:
3962
3963     \snippet code/src_gui_kernel_qapplication.cpp 12
3964 */
3965
3966 /*!
3967     \fn QWidget *QApplication::widgetAt(const QPoint &point, bool child)
3968
3969     Use the single-argument widgetAt() overload to get the child widget. To get
3970     the top-level widget do this:
3971
3972     \snippet code/src_gui_kernel_qapplication.cpp 13
3973 */
3974
3975 bool QApplicationPrivate::inPopupMode() const
3976 {
3977     return QApplicationPrivate::popupWidgets != 0;
3978 }
3979
3980 #ifdef QT_KEYPAD_NAVIGATION
3981 /*!
3982     Sets the kind of focus navigation Qt should use to \a mode.
3983
3984     This feature is available in Qt for Embedded Linux, and Windows CE
3985     only.
3986
3987     \note On Windows CE this feature is disabled by default for touch device
3988           mkspecs. To enable keypad navigation, build Qt with
3989           QT_KEYPAD_NAVIGATION defined.
3990
3991     \since 4.6
3992
3993     \sa keypadNavigationEnabled()
3994 */
3995 void QApplication::setNavigationMode(Qt::NavigationMode mode)
3996 {
3997     QApplicationPrivate::navigationMode = mode;
3998 }
3999
4000 /*!
4001     Returns what kind of focus navigation Qt is using.
4002
4003     This feature is available in Qt for Embedded Linux, and Windows CE only.
4004
4005     \note On Windows CE this feature is disabled by default for touch device
4006           mkspecs. To enable keypad navigation, build Qt with
4007           QT_KEYPAD_NAVIGATION defined.
4008
4009     \since 4.6
4010
4011     \sa keypadNavigationEnabled()
4012 */
4013 Qt::NavigationMode QApplication::navigationMode()
4014 {
4015     return QApplicationPrivate::navigationMode;
4016 }
4017
4018 /*!
4019     Sets whether Qt should use focus navigation suitable for use with a
4020     minimal keypad.
4021
4022     This feature is available in Qt for Embedded Linux, and Windows CE only.
4023
4024     \note On Windows CE this feature is disabled by default for touch device
4025           mkspecs. To enable keypad navigation, build Qt with
4026           QT_KEYPAD_NAVIGATION defined.
4027
4028     \deprecated
4029
4030     \sa setNavigationMode()
4031 */
4032 void QApplication::setKeypadNavigationEnabled(bool enable)
4033 {
4034     if (enable) {
4035         QApplication::setNavigationMode(Qt::NavigationModeKeypadTabOrder);
4036     } else {
4037         QApplication::setNavigationMode(Qt::NavigationModeNone);
4038     }
4039 }
4040
4041 /*!
4042     Returns true if Qt is set to use keypad navigation; otherwise returns
4043     false.  The default value is false.
4044
4045     This feature is available in Qt for Embedded Linux, and Windows CE only.
4046
4047     \note On Windows CE this feature is disabled by default for touch device
4048           mkspecs. To enable keypad navigation, build Qt with
4049           QT_KEYPAD_NAVIGATION defined.
4050
4051     \deprecated
4052
4053     \sa navigationMode()
4054 */
4055 bool QApplication::keypadNavigationEnabled()
4056 {
4057     return QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadTabOrder ||
4058         QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadDirectional;
4059 }
4060 #endif
4061
4062 /*!
4063     \fn void QApplication::alert(QWidget *widget, int msec)
4064     \since 4.3
4065
4066     Causes an alert to be shown for \a widget if the window is not the active
4067     window. The alert is shown for \a msec miliseconds. If \a msec is zero (the
4068     default), then the alert is shown indefinitely until the window becomes
4069     active again.
4070
4071     Currently this function does nothing on Qt for Embedded Linux.
4072
4073     On Mac OS X, this works more at the application level and will cause the
4074     application icon to bounce in the dock.
4075
4076     On Windows, this causes the window's taskbar entry to flash for a time. If
4077     \a msec is zero, the flashing will stop and the taskbar entry will turn a
4078     different color (currently orange).
4079
4080     On X11, this will cause the window to be marked as "demands attention", the
4081     window must not be hidden (i.e. not have hide() called on it, but be
4082     visible in some sort of way) in order for this to work.
4083 */
4084
4085 /*!
4086     \property QApplication::cursorFlashTime
4087     \brief the text cursor's flash (blink) time in milliseconds
4088
4089     The flash time is the time required to display, invert and restore the
4090     caret display. Usually the text cursor is displayed for half the cursor
4091     flash time, then hidden for the same amount of time, but this may vary.
4092
4093     The default value on X11 is 1000 milliseconds. On Windows, the
4094     \uicontrol{Control Panel} value is used and setting this property sets the cursor
4095     flash time for all applications.
4096
4097     We recommend that widgets do not cache this value as it may change at any
4098     time if the user changes the global desktop settings.
4099 */
4100 void QApplication::setCursorFlashTime(int msecs)
4101 {
4102     Q_UNUSED(msecs);
4103 }
4104
4105 int QApplication::cursorFlashTime()
4106 {
4107     return qApp->styleHints()->cursorFlashTime();
4108 }
4109
4110
4111 /*!
4112     \property QApplication::doubleClickInterval
4113     \brief the time limit in milliseconds that distinguishes a double click
4114     from two consecutive mouse clicks
4115
4116     The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
4117     operating system's value is used.
4118
4119     Setting the interval is not supported anymore in Qt 5.
4120 */
4121 void QApplication::setDoubleClickInterval(int ms)
4122 {
4123     Q_UNUSED(ms);
4124 }
4125
4126 int QApplication::doubleClickInterval()
4127 {
4128     return qApp->styleHints()->mouseDoubleClickInterval();
4129 }
4130
4131 /*!
4132     \property QApplication::keyboardInputInterval
4133     \brief the time limit in milliseconds that distinguishes a key press
4134     from two consecutive key presses
4135     \since 4.2
4136
4137     The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
4138     operating system's value is used.
4139 */
4140 void QApplication::setKeyboardInputInterval(int ms)
4141 {
4142     Q_UNUSED(ms);
4143 }
4144
4145 int QApplication::keyboardInputInterval()
4146 {
4147     return qApp->styleHints()->keyboardInputInterval();
4148 }
4149
4150 /*!
4151     \property QApplication::wheelScrollLines
4152     \brief the number of lines to scroll a widget, when the
4153     mouse wheel is rotated.
4154
4155     If the value exceeds the widget's number of visible lines, the widget
4156     should interpret the scroll operation as a single \e{page up} or
4157     \e{page down}. If the widget is an \l{QAbstractItemView}{item view class},
4158     then the result of scrolling one \e line depends on the setting of the
4159     widget's \l{QAbstractItemView::verticalScrollMode()}{scroll mode}. Scroll
4160     one \e line can mean \l{QAbstractItemView::ScrollPerItem}{scroll one item}
4161     or \l{QAbstractItemView::ScrollPerPixel}{scroll one pixel}.
4162
4163     By default, this property has a value of 3.
4164 */
4165
4166 /*!
4167     \fn void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
4168
4169     Enables the UI effect \a effect if \a enable is true, otherwise the effect
4170     will not be used.
4171
4172     \note All effects are disabled on screens running at less than 16-bit color
4173     depth.
4174
4175     \sa isEffectEnabled(), Qt::UIEffect, setDesktopSettingsAware()
4176 */
4177
4178 /*!
4179     \fn bool QApplication::isEffectEnabled(Qt::UIEffect effect)
4180
4181     Returns true if \a effect is enabled; otherwise returns false.
4182
4183     By default, Qt will try to use the desktop settings. To prevent this, call
4184     setDesktopSettingsAware(false).
4185
4186     \note All effects are disabled on screens running at less than 16-bit color
4187     depth.
4188
4189     \sa setEffectEnabled(), Qt::UIEffect
4190 */
4191
4192 /*!
4193     \fn QWidget *QApplication::mainWidget()
4194
4195     Returns the main application widget, or 0 if there is no main widget.
4196 */
4197
4198 /*!
4199     \fn void QApplication::setMainWidget(QWidget *mainWidget)
4200
4201     Sets the application's main widget to \a mainWidget.
4202
4203     In most respects the main widget is like any other widget, except that if
4204     it is closed, the application exits. QApplication does \e not take
4205     ownership of the \a mainWidget, so if you create your main widget on the
4206     heap you must delete it yourself.
4207
4208     You need not have a main widget; connecting lastWindowClosed() to quit()
4209     is an alternative.
4210
4211     On X11, this function also resizes and moves the main widget according
4212     to the \e -geometry command-line option, so you should set the default
4213     geometry (using \l QWidget::setGeometry()) before calling setMainWidget().
4214
4215     \sa mainWidget(), exec(), quit()
4216 */
4217
4218 /*!
4219     \fn void QApplication::beep()
4220
4221     Sounds the bell, using the default volume and sound. The function is \e not
4222     available in Qt for Embedded Linux.
4223 */
4224
4225
4226 /*!
4227     \macro qApp
4228     \relates QApplication
4229
4230     A global pointer referring to the unique application object. It is
4231     equivalent to the pointer returned by the QCoreApplication::instance()
4232     function except that, in GUI applications, it is a pointer to a
4233     QApplication instance.
4234
4235     Only one application object can be created.
4236
4237     \sa QCoreApplication::instance()
4238 */
4239
4240 /*!
4241     \fn QLocale QApplication::keyboardInputLocale()
4242     \since 4.2
4243     \obsolete
4244
4245     Returns the current keyboard input locale. Replaced with QInputMethod::locale()
4246 */
4247
4248 /*!
4249     \fn Qt::LayoutDirection QApplication::keyboardInputDirection()*
4250     \since 4.2
4251     \obsolete
4252
4253     Returns the current keyboard input direction. Replaced with QInputMethod::inputDirection()
4254 */
4255
4256 bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
4257 {
4258     return QGuiApplication::sendSpontaneousEvent(receiver, event);
4259 }
4260
4261
4262 void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget,
4263                                                           Qt::FocusPolicy focusPolicy,
4264                                                           Qt::FocusReason focusReason)
4265 {
4266     QWidget *focusWidget = widget;
4267     while (focusWidget) {
4268         if (focusWidget->isEnabled()
4269             && QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) {
4270             focusWidget->setFocus(focusReason);
4271             break;
4272         }
4273         if (focusWidget->isWindow())
4274             break;
4275         focusWidget = focusWidget->parentWidget();
4276     }
4277 }
4278
4279 bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy)
4280 {
4281     QWidget *f = w;
4282     while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
4283         f = f->d_func()->extra->focus_proxy;
4284
4285     if ((w->focusPolicy() & policy) != policy)
4286         return false;
4287     if (w != f && (f->focusPolicy() & policy) != policy)
4288         return false;
4289     return true;
4290 }
4291
4292 /*! \fn void QApplication::winFocus(QWidget *widget, bool gotFocus)
4293     \internal
4294     \since 4.1
4295
4296     If \a gotFocus is true, \a widget will become the active window.
4297     Otherwise the active window is reset to 0.
4298 */
4299
4300 /*! \fn void QApplication::winMouseButtonUp()
4301   \internal
4302  */
4303
4304 void QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent)
4305 {
4306     for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
4307         QTouchEvent::TouchPoint &touchPoint = touchEvent->_touchPoints[i];
4308
4309         // preserve the sub-pixel resolution
4310         QRectF rect = touchPoint.screenRect();
4311         const QPointF screenPos = rect.center();
4312         const QPointF delta = screenPos - screenPos.toPoint();
4313
4314         rect.moveCenter(widget->mapFromGlobal(screenPos.toPoint()) + delta);
4315         touchPoint.d->rect = rect;
4316         touchPoint.d->startPos = widget->mapFromGlobal(touchPoint.startScreenPos().toPoint()) + delta;
4317         touchPoint.d->lastPos = widget->mapFromGlobal(touchPoint.lastScreenPos().toPoint()) + delta;
4318     }
4319 }
4320
4321 void QApplicationPrivate::initializeMultitouch()
4322 {
4323     initializeMultitouch_sys();
4324 }
4325
4326 void QApplicationPrivate::cleanupMultitouch()
4327 {
4328     cleanupMultitouch_sys();
4329 }
4330
4331 QWidget *QApplicationPrivate::findClosestTouchPointTarget(QTouchDevice *device, const QPointF &screenPos)
4332 {
4333     int closestTouchPointId = -1;
4334     QObject *closestTarget = 0;
4335     qreal closestDistance = qreal(0.);
4336     QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it = activeTouchPoints.constBegin(),
4337             ite = activeTouchPoints.constEnd();
4338     while (it != ite) {
4339         if (it.key().device == device) {
4340             const QTouchEvent::TouchPoint &touchPoint = it->touchPoint;
4341             qreal dx = screenPos.x() - touchPoint.screenPos().x();
4342             qreal dy = screenPos.y() - touchPoint.screenPos().y();
4343             qreal distance = dx * dx + dy * dy;
4344             if (closestTouchPointId == -1 || distance < closestDistance) {
4345                 closestTouchPointId = touchPoint.id();
4346                 closestDistance = distance;
4347                 closestTarget = it.value().target.data();
4348             }
4349         }
4350         ++it;
4351     }
4352     return static_cast<QWidget *>(closestTarget);
4353 }
4354
4355 void QApplicationPrivate::translateRawTouchEvent(QWidget *window,
4356                                                  QTouchDevice *device,
4357                                                  const QList<QTouchEvent::TouchPoint> &touchPoints,
4358                                                  ulong timestamp)
4359 {
4360     QApplicationPrivate *d = self;
4361     typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
4362     QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents;
4363
4364     for (int i = 0; i < touchPoints.count(); ++i) {
4365         QTouchEvent::TouchPoint touchPoint = touchPoints.at(i);
4366         // explicitly detach from the original touch point that we got, so even
4367         // if the touchpoint structs are reused, we will make a copy that we'll
4368         // deliver to the user (which might want to store the struct for later use).
4369         touchPoint.d = touchPoint.d->detach();
4370
4371         // update state
4372         QPointer<QObject> target;
4373         ActiveTouchPointsKey touchInfoKey(device, touchPoint.id());
4374         ActiveTouchPointsValue &touchInfo = d->activeTouchPoints[touchInfoKey];
4375         if (touchPoint.state() == Qt::TouchPointPressed) {
4376             if (device->type() == QTouchDevice::TouchPad) {
4377                 // on touch-pads, send all touch points to the same widget
4378                 target = d->activeTouchPoints.isEmpty()
4379                         ? QPointer<QObject>()
4380                         : d->activeTouchPoints.constBegin().value().target;
4381             }
4382
4383             if (!target) {
4384                 // determine which widget this event will go to
4385                 if (!window)
4386                     window = QApplication::topLevelAt(touchPoint.screenPos().toPoint());
4387                 if (!window)
4388                     continue;
4389                 target = window->childAt(window->mapFromGlobal(touchPoint.screenPos().toPoint()));
4390                 if (!target)
4391                     target = window;
4392             }
4393
4394             if (device->type() == QTouchDevice::TouchScreen) {
4395                 QWidget *closestWidget = d->findClosestTouchPointTarget(device, touchPoint.screenPos());
4396                 QWidget *widget = static_cast<QWidget *>(target.data());
4397                 if (closestWidget
4398                         && (widget->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget))) {
4399                     target = closestWidget;
4400                 }
4401             }
4402
4403             touchInfo.target = target;
4404         } else {
4405             target = touchInfo.target;
4406             if (!target)
4407                 continue;
4408         }
4409         Q_ASSERT(target.data() != 0);
4410
4411         StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[static_cast<QWidget *>(target.data())];
4412         maskAndPoints.first |= touchPoint.state();
4413         maskAndPoints.second.append(touchPoint);
4414     }
4415
4416     if (widgetsNeedingEvents.isEmpty())
4417         return;
4418
4419     QHash<QWidget *, StatesAndTouchPoints>::ConstIterator it = widgetsNeedingEvents.constBegin();
4420     const QHash<QWidget *, StatesAndTouchPoints>::ConstIterator end = widgetsNeedingEvents.constEnd();
4421     for (; it != end; ++it) {
4422         QWidget *widget = it.key();
4423         if (!QApplicationPrivate::tryModalHelper(widget, 0))
4424             continue;
4425
4426         QEvent::Type eventType;
4427         switch (it.value().first) {
4428         case Qt::TouchPointPressed:
4429             eventType = QEvent::TouchBegin;
4430             break;
4431         case Qt::TouchPointReleased:
4432             eventType = QEvent::TouchEnd;
4433             break;
4434         case Qt::TouchPointStationary:
4435             // don't send the event if nothing changed
4436             continue;
4437         default:
4438             eventType = QEvent::TouchUpdate;
4439             break;
4440         }
4441
4442         QTouchEvent touchEvent(eventType,
4443                                device,
4444                                QApplication::keyboardModifiers(),
4445                                it.value().first,
4446                                it.value().second);
4447         updateTouchPointsForWidget(widget, &touchEvent);
4448         touchEvent.setTimestamp(timestamp);
4449         touchEvent.setWindow(window->windowHandle());
4450         touchEvent.setTarget(widget);
4451
4452         switch (touchEvent.type()) {
4453         case QEvent::TouchBegin:
4454         {
4455             // if the TouchBegin handler recurses, we assume that means the event
4456             // has been implicitly accepted and continue to send touch events
4457             widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
4458             (void ) QApplication::sendSpontaneousEvent(widget, &touchEvent);
4459             break;
4460         }
4461         default:
4462             if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent)) {
4463                 if (touchEvent.type() == QEvent::TouchEnd)
4464                     widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, false);
4465                 (void) QApplication::sendSpontaneousEvent(widget, &touchEvent);
4466             }
4467             break;
4468         }
4469     }
4470 }
4471
4472 void QApplicationPrivate::translateTouchCancel(QTouchDevice *device, ulong timestamp)
4473 {
4474     QTouchEvent touchEvent(QEvent::TouchCancel, device, QApplication::keyboardModifiers());
4475     touchEvent.setTimestamp(timestamp);
4476     QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it
4477             = self->activeTouchPoints.constBegin(), ite = self->activeTouchPoints.constEnd();
4478     QSet<QWidget *> widgetsNeedingCancel;
4479     while (it != ite) {
4480         QWidget *widget = static_cast<QWidget *>(it->target.data());
4481         if (widget)
4482             widgetsNeedingCancel.insert(widget);
4483         ++it;
4484     }
4485     for (QSet<QWidget *>::const_iterator widIt = widgetsNeedingCancel.constBegin(),
4486          widItEnd = widgetsNeedingCancel.constEnd(); widIt != widItEnd; ++widIt) {
4487         QWidget *widget = *widIt;
4488         touchEvent.setWindow(widget->windowHandle());
4489         touchEvent.setTarget(widget);
4490         QApplication::sendSpontaneousEvent(widget, &touchEvent);
4491     }
4492 }
4493
4494 void QApplicationPrivate::notifyThemeChanged()
4495 {
4496     QGuiApplicationPrivate::notifyThemeChanged();
4497     clearSystemPalette();
4498     initSystemPalette();
4499 }
4500
4501 #ifndef QT_NO_GESTURES
4502 QGestureManager* QGestureManager::instance()
4503 {
4504     QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
4505     if (!qAppPriv)
4506         return 0;
4507     if (!qAppPriv->gestureManager)
4508         qAppPriv->gestureManager = new QGestureManager(qApp);
4509     return qAppPriv->gestureManager;
4510 }
4511 #endif // QT_NO_GESTURES
4512
4513 QPixmap QApplicationPrivate::applyQIconStyleHelper(QIcon::Mode mode, const QPixmap& base) const
4514 {
4515     QStyleOption opt(0);
4516     opt.palette = QGuiApplication::palette();
4517     return QApplication::style()->generatedIconPixmap(mode, base, &opt);
4518 }
4519
4520 QT_END_NAMESPACE
4521
4522 #include "moc_qapplication.cpp"