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