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