summaryrefslogtreecommitdiffstats
path: root/src/gui/kernel
diff options
context:
space:
mode:
authorQt by Nokia <qt-info@nokia.com>2011-04-27 12:05:43 +0200
committeraxis <qt-info@nokia.com>2011-04-27 12:05:43 +0200
commit38be0d13830efd2d98281c645c3a60afe05ffece (patch)
tree6ea73f3ec77f7d153333779883e8120f82820abe /src/gui/kernel
Initial import from the monolithic Qt.
This is the beginning of revision history for this module. If you want to look at revision history older than this, please refer to the Qt Git wiki for how to use Git history grafting. At the time of writing, this wiki is located here: http://qt.gitorious.org/qt/pages/GitIntroductionWithQt If you have already performed the grafting and you don't see any history beyond this commit, try running "git log" with the "--follow" argument. Branched from the monolithic repo, Qt master branch, at commit 896db169ea224deb96c59ce8af800d019de63f12
Diffstat (limited to 'src/gui/kernel')
-rw-r--r--src/gui/kernel/kernel.pri329
-rw-r--r--src/gui/kernel/mac.pri4
-rw-r--r--src/gui/kernel/qaction.cpp1520
-rw-r--r--src/gui/kernel/qaction.h264
-rw-r--r--src/gui/kernel/qaction_p.h144
-rw-r--r--src/gui/kernel/qactiongroup.cpp422
-rw-r--r--src/gui/kernel/qactiongroup.h112
-rw-r--r--src/gui/kernel/qapplication.cpp6139
-rw-r--r--src/gui/kernel/qapplication.h430
-rw-r--r--src/gui/kernel/qapplication_mac.mm3134
-rw-r--r--src/gui/kernel/qapplication_p.h683
-rw-r--r--src/gui/kernel/qapplication_qpa.cpp965
-rw-r--r--src/gui/kernel/qapplication_qws.cpp3797
-rw-r--r--src/gui/kernel/qapplication_s60.cpp2712
-rw-r--r--src/gui/kernel/qapplication_win.cpp4232
-rw-r--r--src/gui/kernel/qapplication_x11.cpp6239
-rw-r--r--src/gui/kernel/qboxlayout.cpp1550
-rw-r--r--src/gui/kernel/qboxlayout.h173
-rw-r--r--src/gui/kernel/qclipboard.cpp667
-rw-r--r--src/gui/kernel/qclipboard.h130
-rw-r--r--src/gui/kernel/qclipboard_mac.cpp634
-rw-r--r--src/gui/kernel/qclipboard_p.h131
-rw-r--r--src/gui/kernel/qclipboard_qpa.cpp105
-rw-r--r--src/gui/kernel/qclipboard_qws.cpp304
-rw-r--r--src/gui/kernel/qclipboard_s60.cpp331
-rw-r--r--src/gui/kernel/qclipboard_win.cpp398
-rw-r--r--src/gui/kernel/qclipboard_x11.cpp1539
-rw-r--r--src/gui/kernel/qcocoaapplication_mac.mm222
-rw-r--r--src/gui/kernel/qcocoaapplication_mac_p.h117
-rw-r--r--src/gui/kernel/qcocoaapplicationdelegate_mac.mm354
-rw-r--r--src/gui/kernel/qcocoaapplicationdelegate_mac_p.h128
-rw-r--r--src/gui/kernel/qcocoaintrospection_mac.mm125
-rw-r--r--src/gui/kernel/qcocoaintrospection_p.h84
-rw-r--r--src/gui/kernel/qcocoamenuloader_mac.mm264
-rw-r--r--src/gui/kernel/qcocoamenuloader_mac_p.h95
-rw-r--r--src/gui/kernel/qcocoapanel_mac.mm70
-rw-r--r--src/gui/kernel/qcocoapanel_mac_p.h83
-rw-r--r--src/gui/kernel/qcocoasharedwindowmethods_mac_p.h610
-rw-r--r--src/gui/kernel/qcocoaview_mac.mm1389
-rw-r--r--src/gui/kernel/qcocoaview_mac_p.h87
-rw-r--r--src/gui/kernel/qcocoawindow_mac.mm90
-rw-r--r--src/gui/kernel/qcocoawindow_mac_p.h97
-rw-r--r--src/gui/kernel/qcocoawindowcustomthemeframe_mac.mm62
-rw-r--r--src/gui/kernel/qcocoawindowcustomthemeframe_mac_p.h61
-rw-r--r--src/gui/kernel/qcocoawindowdelegate_mac.mm439
-rw-r--r--src/gui/kernel/qcocoawindowdelegate_mac_p.h110
-rw-r--r--src/gui/kernel/qcursor.cpp573
-rw-r--r--src/gui/kernel/qcursor.h180
-rw-r--r--src/gui/kernel/qcursor_mac.mm689
-rw-r--r--src/gui/kernel/qcursor_p.h134
-rw-r--r--src/gui/kernel/qcursor_qpa.cpp127
-rw-r--r--src/gui/kernel/qcursor_qws.cpp138
-rw-r--r--src/gui/kernel/qcursor_s60.cpp533
-rw-r--r--src/gui/kernel/qcursor_win.cpp492
-rw-r--r--src/gui/kernel/qcursor_x11.cpp637
-rw-r--r--src/gui/kernel/qdesktopwidget.cpp76
-rw-r--r--src/gui/kernel/qdesktopwidget.h110
-rw-r--r--src/gui/kernel/qdesktopwidget.qdoc269
-rw-r--r--src/gui/kernel/qdesktopwidget_mac.mm257
-rw-r--r--src/gui/kernel/qdesktopwidget_mac_p.h75
-rw-r--r--src/gui/kernel/qdesktopwidget_qpa.cpp180
-rw-r--r--src/gui/kernel/qdesktopwidget_qpa_p.h82
-rw-r--r--src/gui/kernel/qdesktopwidget_qws.cpp159
-rw-r--r--src/gui/kernel/qdesktopwidget_s60.cpp316
-rw-r--r--src/gui/kernel/qdesktopwidget_win.cpp387
-rw-r--r--src/gui/kernel/qdesktopwidget_x11.cpp406
-rw-r--r--src/gui/kernel/qdnd.cpp491
-rw-r--r--src/gui/kernel/qdnd_mac.mm753
-rw-r--r--src/gui/kernel/qdnd_p.h336
-rw-r--r--src/gui/kernel/qdnd_qws.cpp426
-rw-r--r--src/gui/kernel/qdnd_s60.cpp359
-rw-r--r--src/gui/kernel/qdnd_win.cpp1027
-rw-r--r--src/gui/kernel/qdnd_x11.cpp2076
-rw-r--r--src/gui/kernel/qdrag.cpp359
-rw-r--r--src/gui/kernel/qdrag.h105
-rw-r--r--src/gui/kernel/qevent.cpp4851
-rw-r--r--src/gui/kernel/qevent.h942
-rw-r--r--src/gui/kernel/qevent_p.h219
-rw-r--r--src/gui/kernel/qeventdispatcher_glib_qpa.cpp147
-rw-r--r--src/gui/kernel/qeventdispatcher_glib_qpa_p.h88
-rw-r--r--src/gui/kernel/qeventdispatcher_glib_qws.cpp195
-rw-r--r--src/gui/kernel/qeventdispatcher_glib_qws_p.h78
-rw-r--r--src/gui/kernel/qeventdispatcher_mac.mm1200
-rw-r--r--src/gui/kernel/qeventdispatcher_mac_p.h224
-rw-r--r--src/gui/kernel/qeventdispatcher_qpa.cpp334
-rw-r--r--src/gui/kernel/qeventdispatcher_qpa_p.h86
-rw-r--r--src/gui/kernel/qeventdispatcher_qws.cpp168
-rw-r--r--src/gui/kernel/qeventdispatcher_qws_p.h86
-rw-r--r--src/gui/kernel/qeventdispatcher_s60.cpp196
-rw-r--r--src/gui/kernel/qeventdispatcher_s60_p.h127
-rw-r--r--src/gui/kernel/qeventdispatcher_x11.cpp191
-rw-r--r--src/gui/kernel/qeventdispatcher_x11_p.h86
-rw-r--r--src/gui/kernel/qformlayout.cpp2079
-rw-r--r--src/gui/kernel/qformlayout.h163
-rw-r--r--src/gui/kernel/qgenericplugin_qpa.cpp112
-rw-r--r--src/gui/kernel/qgenericplugin_qpa.h84
-rw-r--r--src/gui/kernel/qgenericpluginfactory_qpa.cpp115
-rw-r--r--src/gui/kernel/qgenericpluginfactory_qpa.h67
-rw-r--r--src/gui/kernel/qgesture.cpp807
-rw-r--r--src/gui/kernel/qgesture.h275
-rw-r--r--src/gui/kernel/qgesture_p.h197
-rw-r--r--src/gui/kernel/qgesturemanager.cpp721
-rw-r--r--src/gui/kernel/qgesturemanager_p.h151
-rw-r--r--src/gui/kernel/qgesturerecognizer.cpp240
-rw-r--r--src/gui/kernel/qgesturerecognizer.h102
-rw-r--r--src/gui/kernel/qgridlayout.cpp1889
-rw-r--r--src/gui/kernel/qgridlayout.h176
-rw-r--r--src/gui/kernel/qguieventdispatcher_glib.cpp224
-rw-r--r--src/gui/kernel/qguieventdispatcher_glib_p.h79
-rw-r--r--src/gui/kernel/qguifunctions_wince.cpp408
-rw-r--r--src/gui/kernel/qguifunctions_wince.h151
-rw-r--r--src/gui/kernel/qguiplatformplugin.cpp298
-rw-r--r--src/gui/kernel/qguiplatformplugin_p.h126
-rw-r--r--src/gui/kernel/qguivariant.cpp828
-rw-r--r--src/gui/kernel/qkde.cpp176
-rw-r--r--src/gui/kernel/qkde_p.h81
-rw-r--r--src/gui/kernel/qkeymapper.cpp118
-rw-r--r--src/gui/kernel/qkeymapper_mac.cpp1023
-rw-r--r--src/gui/kernel/qkeymapper_p.h224
-rw-r--r--src/gui/kernel/qkeymapper_qws.cpp77
-rw-r--r--src/gui/kernel/qkeymapper_s60.cpp258
-rw-r--r--src/gui/kernel/qkeymapper_win.cpp1207
-rw-r--r--src/gui/kernel/qkeymapper_x11.cpp1869
-rw-r--r--src/gui/kernel/qkeymapper_x11_p.cpp489
-rw-r--r--src/gui/kernel/qkeysequence.cpp1726
-rw-r--r--src/gui/kernel/qkeysequence.h240
-rw-r--r--src/gui/kernel/qkeysequence_p.h98
-rw-r--r--src/gui/kernel/qlayout.cpp1632
-rw-r--r--src/gui/kernel/qlayout.h245
-rw-r--r--src/gui/kernel/qlayout_p.h101
-rw-r--r--src/gui/kernel/qlayoutengine.cpp436
-rw-r--r--src/gui/kernel/qlayoutengine_p.h140
-rw-r--r--src/gui/kernel/qlayoutitem.cpp834
-rw-r--r--src/gui/kernel/qlayoutitem.h182
-rw-r--r--src/gui/kernel/qmacdefines_mac.h180
-rw-r--r--src/gui/kernel/qmacgesturerecognizer_mac.mm272
-rw-r--r--src/gui/kernel/qmacgesturerecognizer_mac_p.h106
-rw-r--r--src/gui/kernel/qmime.cpp97
-rw-r--r--src/gui/kernel/qmime.h176
-rw-r--r--src/gui/kernel/qmime_mac.cpp1310
-rw-r--r--src/gui/kernel/qmime_win.cpp1556
-rw-r--r--src/gui/kernel/qmotifdnd_x11.cpp1031
-rw-r--r--src/gui/kernel/qmultitouch_mac.mm218
-rw-r--r--src/gui/kernel/qmultitouch_mac_p.h102
-rw-r--r--src/gui/kernel/qnsframeview_mac_p.h154
-rw-r--r--src/gui/kernel/qnsthemeframe_mac_p.h246
-rw-r--r--src/gui/kernel/qnstitledframe_mac_p.h205
-rw-r--r--src/gui/kernel/qole_win.cpp255
-rw-r--r--src/gui/kernel/qpalette.cpp1406
-rw-r--r--src/gui/kernel/qpalette.h270
-rw-r--r--src/gui/kernel/qplatformclipboard_qpa.cpp105
-rw-r--r--src/gui/kernel/qplatformclipboard_qpa.h73
-rw-r--r--src/gui/kernel/qplatformcursor_qpa.cpp660
-rw-r--r--src/gui/kernel/qplatformcursor_qpa.h103
-rw-r--r--src/gui/kernel/qplatformeventloopintegration_qpa.cpp86
-rw-r--r--src/gui/kernel/qplatformeventloopintegration_qpa.h82
-rw-r--r--src/gui/kernel/qplatformglcontext_qpa.cpp209
-rw-r--r--src/gui/kernel/qplatformglcontext_qpa.h91
-rw-r--r--src/gui/kernel/qplatformintegration_qpa.cpp224
-rw-r--r--src/gui/kernel/qplatformintegration_qpa.h107
-rw-r--r--src/gui/kernel/qplatformintegrationfactory_qpa.cpp109
-rw-r--r--src/gui/kernel/qplatformintegrationfactory_qpa_p.h78
-rw-r--r--src/gui/kernel/qplatformintegrationplugin_qpa.cpp55
-rw-r--r--src/gui/kernel/qplatformintegrationplugin_qpa.h92
-rw-r--r--src/gui/kernel/qplatformnativeinterface_qpa.cpp53
-rw-r--r--src/gui/kernel/qplatformnativeinterface_qpa.h65
-rw-r--r--src/gui/kernel/qplatformscreen_qpa.cpp129
-rw-r--r--src/gui/kernel/qplatformscreen_qpa.h86
-rw-r--r--src/gui/kernel/qplatformwindow_qpa.cpp229
-rw-r--r--src/gui/kernel/qplatformwindow_qpa.h95
-rw-r--r--src/gui/kernel/qplatformwindowformat_qpa.cpp1008
-rw-r--r--src/gui/kernel/qplatformwindowformat_qpa.h234
-rw-r--r--src/gui/kernel/qsessionmanager.h111
-rw-r--r--src/gui/kernel/qsessionmanager_qpa.cpp172
-rw-r--r--src/gui/kernel/qsessionmanager_qws.cpp171
-rw-r--r--src/gui/kernel/qshortcut.cpp407
-rw-r--r--src/gui/kernel/qshortcut.h107
-rw-r--r--src/gui/kernel/qshortcutmap.cpp897
-rw-r--r--src/gui/kernel/qshortcutmap_p.h123
-rw-r--r--src/gui/kernel/qsizepolicy.h244
-rw-r--r--src/gui/kernel/qsizepolicy.qdoc529
-rw-r--r--src/gui/kernel/qsoftkeymanager.cpp319
-rw-r--r--src/gui/kernel/qsoftkeymanager_common_p.h86
-rw-r--r--src/gui/kernel/qsoftkeymanager_p.h115
-rw-r--r--src/gui/kernel/qsoftkeymanager_s60.cpp440
-rw-r--r--src/gui/kernel/qsoftkeymanager_s60_p.h113
-rw-r--r--src/gui/kernel/qsound.cpp390
-rw-r--r--src/gui/kernel/qsound.h95
-rw-r--r--src/gui/kernel/qsound_mac.mm190
-rw-r--r--src/gui/kernel/qsound_p.h100
-rw-r--r--src/gui/kernel/qsound_qws.cpp350
-rw-r--r--src/gui/kernel/qsound_s60.cpp224
-rw-r--r--src/gui/kernel/qsound_win.cpp205
-rw-r--r--src/gui/kernel/qsound_x11.cpp296
-rw-r--r--src/gui/kernel/qstackedlayout.cpp543
-rw-r--r--src/gui/kernel/qstackedlayout.h115
-rw-r--r--src/gui/kernel/qstandardgestures.cpp595
-rw-r--r--src/gui/kernel/qstandardgestures_p.h117
-rw-r--r--src/gui/kernel/qt_cocoa_helpers_mac.mm1824
-rw-r--r--src/gui/kernel/qt_cocoa_helpers_mac_p.h340
-rw-r--r--src/gui/kernel/qt_gui_pch.h85
-rw-r--r--src/gui/kernel/qt_mac.cpp174
-rw-r--r--src/gui/kernel/qt_mac_p.h286
-rw-r--r--src/gui/kernel/qt_s60_p.h625
-rw-r--r--src/gui/kernel/qt_x11_p.h757
-rw-r--r--src/gui/kernel/qtooltip.cpp623
-rw-r--r--src/gui/kernel/qtooltip.h84
-rw-r--r--src/gui/kernel/qwhatsthis.cpp777
-rw-r--r--src/gui/kernel/qwhatsthis.h88
-rw-r--r--src/gui/kernel/qwidget.cpp12679
-rw-r--r--src/gui/kernel/qwidget.h1090
-rw-r--r--src/gui/kernel/qwidget_mac.mm5420
-rw-r--r--src/gui/kernel/qwidget_p.h1035
-rw-r--r--src/gui/kernel/qwidget_qpa.cpp875
-rw-r--r--src/gui/kernel/qwidget_qws.cpp1221
-rw-r--r--src/gui/kernel/qwidget_s60.cpp1450
-rw-r--r--src/gui/kernel/qwidget_win.cpp2139
-rw-r--r--src/gui/kernel/qwidget_wince.cpp675
-rw-r--r--src/gui/kernel/qwidget_x11.cpp3146
-rw-r--r--src/gui/kernel/qwidgetaction.cpp287
-rw-r--r--src/gui/kernel/qwidgetaction.h91
-rw-r--r--src/gui/kernel/qwidgetaction_p.h77
-rw-r--r--src/gui/kernel/qwidgetcreate_x11.cpp79
-rw-r--r--src/gui/kernel/qwindowdefs.h163
-rw-r--r--src/gui/kernel/qwindowdefs_win.h132
-rw-r--r--src/gui/kernel/qwindowsysteminterface_qpa.cpp291
-rw-r--r--src/gui/kernel/qwindowsysteminterface_qpa.h107
-rw-r--r--src/gui/kernel/qwindowsysteminterface_qpa_p.h208
-rw-r--r--src/gui/kernel/qwinnativepangesturerecognizer_win.cpp133
-rw-r--r--src/gui/kernel/qwinnativepangesturerecognizer_win_p.h80
-rw-r--r--src/gui/kernel/qx11embed_x11.cpp1808
-rw-r--r--src/gui/kernel/qx11embed_x11.h132
-rw-r--r--src/gui/kernel/qx11info_x11.cpp543
-rw-r--r--src/gui/kernel/qx11info_x11.h123
-rw-r--r--src/gui/kernel/symbian.pri7
-rw-r--r--src/gui/kernel/win.pri4
-rw-r--r--src/gui/kernel/x11.pri4
237 files changed, 141266 insertions, 0 deletions
diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri
new file mode 100644
index 0000000000..3c57368bab
--- /dev/null
+++ b/src/gui/kernel/kernel.pri
@@ -0,0 +1,329 @@
+# Qt kernel module
+
+# Only used on platforms with CONFIG += precompile_header
+PRECOMPILED_HEADER = kernel/qt_gui_pch.h
+
+
+KERNEL_P= kernel
+HEADERS += \
+ kernel/qaction.h \
+ kernel/qaction_p.h \
+ kernel/qactiongroup.h \
+ kernel/qapplication.h \
+ kernel/qapplication_p.h \
+ kernel/qboxlayout.h \
+ kernel/qclipboard.h \
+ kernel/qcursor.h \
+ kernel/qdesktopwidget.h \
+ kernel/qdrag.h \
+ kernel/qdnd_p.h \
+ kernel/qevent.h \
+ kernel/qevent_p.h \
+ kernel/qformlayout.h \
+ kernel/qgridlayout.h \
+ kernel/qkeysequence.h \
+ kernel/qlayout.h \
+ kernel/qlayout_p.h \
+ kernel/qlayoutengine_p.h \
+ kernel/qlayoutitem.h \
+ kernel/qmime.h \
+ kernel/qsessionmanager.h \
+ kernel/qshortcut.h \
+ kernel/qshortcutmap_p.h \
+ kernel/qsizepolicy.h \
+ kernel/qpalette.h \
+ kernel/qstackedlayout.h \
+ kernel/qtooltip.h \
+ kernel/qwhatsthis.h \
+ kernel/qwidget.h \
+ kernel/qwidget_p.h \
+ kernel/qwidgetaction.h \
+ kernel/qwidgetaction_p.h \
+ kernel/qwindowdefs.h \
+ kernel/qkeymapper_p.h \
+ kernel/qgesture.h \
+ kernel/qgesture_p.h \
+ kernel/qstandardgestures_p.h \
+ kernel/qgesturerecognizer.h \
+ kernel/qgesturemanager_p.h \
+ kernel/qsoftkeymanager_p.h \
+ kernel/qsoftkeymanager_common_p.h \
+ kernel/qguiplatformplugin_p.h \
+
+SOURCES += \
+ kernel/qaction.cpp \
+ kernel/qactiongroup.cpp \
+ kernel/qapplication.cpp \
+ kernel/qboxlayout.cpp \
+ kernel/qclipboard.cpp \
+ kernel/qcursor.cpp \
+ kernel/qdrag.cpp \
+ kernel/qdnd.cpp \
+ kernel/qevent.cpp \
+ kernel/qformlayout.cpp \
+ kernel/qgridlayout.cpp \
+ kernel/qkeysequence.cpp \
+ kernel/qlayout.cpp \
+ kernel/qlayoutengine.cpp \
+ kernel/qlayoutitem.cpp \
+ kernel/qmime.cpp \
+ kernel/qpalette.cpp \
+ kernel/qshortcut.cpp \
+ kernel/qshortcutmap.cpp \
+ kernel/qstackedlayout.cpp \
+ kernel/qtooltip.cpp \
+ kernel/qguivariant.cpp \
+ kernel/qwhatsthis.cpp \
+ kernel/qwidget.cpp \
+ kernel/qwidgetaction.cpp \
+ kernel/qkeymapper.cpp \
+ kernel/qgesture.cpp \
+ kernel/qstandardgestures.cpp \
+ kernel/qgesturerecognizer.cpp \
+ kernel/qgesturemanager.cpp \
+ kernel/qsoftkeymanager.cpp \
+ kernel/qdesktopwidget.cpp \
+ kernel/qguiplatformplugin.cpp
+
+win32 {
+ DEFINES += QT_NO_DIRECTDRAW
+
+ HEADERS += \
+ kernel/qwinnativepangesturerecognizer_win_p.h
+
+ SOURCES += \
+ kernel/qapplication_win.cpp \
+ kernel/qclipboard_win.cpp \
+ kernel/qcursor_win.cpp \
+ kernel/qdesktopwidget_win.cpp \
+ kernel/qdnd_win.cpp \
+ kernel/qmime_win.cpp \
+ kernel/qsound_win.cpp \
+ kernel/qwidget_win.cpp \
+ kernel/qole_win.cpp \
+ kernel/qkeymapper_win.cpp \
+ kernel/qwinnativepangesturerecognizer_win.cpp
+
+ !contains(DEFINES, QT_NO_DIRECTDRAW):LIBS += ddraw.lib
+}
+
+symbian {
+ exists($${EPOCROOT}epoc32/include/platform/mw/akntranseffect.h): DEFINES += QT_SYMBIAN_HAVE_AKNTRANSEFFECT_H
+
+ SOURCES += \
+ kernel/qapplication_s60.cpp \
+ kernel/qeventdispatcher_s60.cpp \
+ kernel/qwidget_s60.cpp \
+ kernel/qcursor_s60.cpp \
+ kernel/qdesktopwidget_s60.cpp \
+ kernel/qkeymapper_s60.cpp\
+ kernel/qclipboard_s60.cpp\
+ kernel/qdnd_s60.cpp \
+ kernel/qsound_s60.cpp
+
+ HEADERS += \
+ kernel/qt_s60_p.h \
+ kernel/qeventdispatcher_s60_p.h
+
+ LIBS += -lbafl -lestor
+
+ INCLUDEPATH += $$MW_LAYER_SYSTEMINCLUDE
+ INCLUDEPATH += ../3rdparty/s60
+
+ contains(QT_CONFIG, s60) {
+ SOURCES += kernel/qsoftkeymanager_s60.cpp
+ HEADERS += kernel/qsoftkeymanager_s60_p.h
+ }
+}
+
+
+unix:x11 {
+ INCLUDEPATH += ../3rdparty/xorg
+ HEADERS += \
+ kernel/qx11embed_x11.h \
+ kernel/qx11info_x11.h \
+ kernel/qkde_p.h
+
+ SOURCES += \
+ kernel/qapplication_x11.cpp \
+ kernel/qclipboard_x11.cpp \
+ kernel/qcursor_x11.cpp \
+ kernel/qdnd_x11.cpp \
+ kernel/qdesktopwidget_x11.cpp \
+ kernel/qmotifdnd_x11.cpp \
+ kernel/qsound_x11.cpp \
+ kernel/qwidget_x11.cpp \
+ kernel/qwidgetcreate_x11.cpp \
+ kernel/qx11embed_x11.cpp \
+ kernel/qx11info_x11.cpp \
+ kernel/qkeymapper_x11.cpp \
+ kernel/qkde.cpp
+
+ contains(QT_CONFIG, glib) {
+ SOURCES += \
+ kernel/qguieventdispatcher_glib.cpp
+ HEADERS += \
+ kernel/qguieventdispatcher_glib_p.h
+ QMAKE_CXXFLAGS += $$QT_CFLAGS_GLIB
+ LIBS_PRIVATE +=$$QT_LIBS_GLIB
+ }
+ SOURCES += \
+ kernel/qeventdispatcher_x11.cpp
+ HEADERS += \
+ kernel/qeventdispatcher_x11_p.h
+}
+
+embedded {
+ HEADERS += \
+ kernel/qeventdispatcher_qws_p.h
+
+ SOURCES += \
+ kernel/qapplication_qws.cpp \
+ kernel/qclipboard_qws.cpp \
+ kernel/qcursor_qws.cpp \
+ kernel/qdesktopwidget_qws.cpp \
+ kernel/qdnd_qws.cpp \
+ kernel/qeventdispatcher_qws.cpp \
+ kernel/qsound_qws.cpp \
+ kernel/qwidget_qws.cpp \
+ kernel/qkeymapper_qws.cpp \
+ kernel/qsessionmanager_qws.cpp
+
+ contains(QT_CONFIG, glib) {
+ SOURCES += \
+ kernel/qeventdispatcher_glib_qws.cpp
+ HEADERS += \
+ kernel/qeventdispatcher_glib_qws_p.h
+ QMAKE_CXXFLAGS += $$QT_CFLAGS_GLIB
+ LIBS_PRIVATE +=$$QT_LIBS_GLIB
+ }
+}
+
+!qpa {
+ HEADERS += \
+ kernel/qsound.h \
+ kernel/qsound_p.h
+
+ SOURCES += \
+ kernel/qsound.cpp
+}
+
+qpa {
+ HEADERS += \
+ kernel/qgenericpluginfactory_qpa.h \
+ kernel/qgenericplugin_qpa.h \
+ kernel/qeventdispatcher_qpa_p.h \
+ kernel/qwindowsysteminterface_qpa.h \
+ kernel/qwindowsysteminterface_qpa_p.h \
+ kernel/qplatformintegration_qpa.h \
+ kernel/qplatformscreen_qpa.h \
+ kernel/qplatformintegrationfactory_qpa_p.h \
+ kernel/qplatformintegrationplugin_qpa.h \
+ kernel/qplatformwindow_qpa.h \
+ kernel/qplatformwindowformat_qpa.h \
+ kernel/qplatformglcontext_qpa.h \
+ kernel/qdesktopwidget_qpa_p.h \
+ kernel/qplatformeventloopintegration_qpa.h \
+ kernel/qplatformcursor_qpa.h \
+ kernel/qplatformclipboard_qpa.h \
+ kernel/qplatformnativeinterface_qpa.h
+
+ SOURCES += \
+ kernel/qapplication_qpa.cpp \
+ kernel/qclipboard_qpa.cpp \
+ kernel/qcursor_qpa.cpp \
+ kernel/qdnd_qws.cpp \
+ kernel/qdesktopwidget_qpa.cpp \
+ kernel/qgenericpluginfactory_qpa.cpp \
+ kernel/qgenericplugin_qpa.cpp \
+ kernel/qkeymapper_qws.cpp \
+ kernel/qwidget_qpa.cpp \
+ kernel/qeventdispatcher_qpa.cpp \
+ kernel/qwindowsysteminterface_qpa.cpp \
+ kernel/qplatformintegration_qpa.cpp \
+ kernel/qplatformscreen_qpa.cpp \
+ kernel/qplatformintegrationfactory_qpa.cpp \
+ kernel/qplatformintegrationplugin_qpa.cpp \
+ kernel/qplatformwindow_qpa.cpp \
+ kernel/qplatformwindowformat_qpa.cpp \
+ kernel/qplatformeventloopintegration_qpa.cpp \
+ kernel/qplatformglcontext_qpa.cpp \
+ kernel/qplatformcursor_qpa.cpp \
+ kernel/qplatformclipboard_qpa.cpp \
+ kernel/qplatformnativeinterface_qpa.cpp \
+ kernel/qsessionmanager_qpa.cpp
+
+ contains(QT_CONFIG, glib) {
+ SOURCES += \
+ kernel/qeventdispatcher_glib_qpa.cpp
+ HEADERS += \
+ kernel/qeventdispatcher_glib_qpa_p.h
+ QMAKE_CXXFLAGS += $$QT_CFLAGS_GLIB
+ LIBS_PRIVATE +=$$QT_LIBS_GLIB
+ }
+}
+
+!embedded:!qpa:!x11:mac {
+ SOURCES += \
+ kernel/qclipboard_mac.cpp \
+ kernel/qmime_mac.cpp \
+ kernel/qt_mac.cpp \
+ kernel/qkeymapper_mac.cpp
+
+ OBJECTIVE_HEADERS += \
+ qcocoawindow_mac_p.h \
+ qcocoapanel_mac_p.h \
+ qcocoawindowdelegate_mac_p.h \
+ qcocoaview_mac_p.h \
+ qcocoaapplication_mac_p.h \
+ qcocoaapplicationdelegate_mac_p.h \
+ qmacgesturerecognizer_mac_p.h \
+ qmultitouch_mac_p.h \
+ qcocoasharedwindowmethods_mac_p.h \
+ qcocoaintrospection_p.h
+
+ OBJECTIVE_SOURCES += \
+ kernel/qcursor_mac.mm \
+ kernel/qdnd_mac.mm \
+ kernel/qsound_mac.mm \
+ kernel/qapplication_mac.mm \
+ kernel/qwidget_mac.mm \
+ kernel/qcocoapanel_mac.mm \
+ kernel/qcocoaview_mac.mm \
+ kernel/qcocoawindow_mac.mm \
+ kernel/qcocoawindowdelegate_mac.mm \
+ kernel/qcocoamenuloader_mac.mm \
+ kernel/qcocoaapplication_mac.mm \
+ kernel/qcocoaapplicationdelegate_mac.mm \
+ kernel/qt_cocoa_helpers_mac.mm \
+ kernel/qdesktopwidget_mac.mm \
+ kernel/qeventdispatcher_mac.mm \
+ kernel/qcocoawindowcustomthemeframe_mac.mm \
+ kernel/qmacgesturerecognizer_mac.mm \
+ kernel/qmultitouch_mac.mm \
+ kernel/qcocoaintrospection_mac.mm
+
+ HEADERS += \
+ kernel/qt_cocoa_helpers_mac_p.h \
+ kernel/qcocoaapplication_mac_p.h \
+ kernel/qcocoaapplicationdelegate_mac_p.h \
+ kernel/qeventdispatcher_mac_p.h
+
+ MENU_NIB.files = mac/qt_menu.nib
+ MENU_NIB.path = Resources
+ MENU_NIB.version = Versions
+ QMAKE_BUNDLE_DATA += MENU_NIB
+ RESOURCES += mac/macresources.qrc
+
+ LIBS_PRIVATE += -framework AppKit
+}
+
+wince*: {
+ HEADERS += \
+ ../corelib/kernel/qfunctions_wince.h \
+ kernel/qguifunctions_wince.h
+
+ SOURCES += \
+ ../corelib/kernel/qfunctions_wince.cpp \
+ kernel/qguifunctions_wince.cpp
+}
diff --git a/src/gui/kernel/mac.pri b/src/gui/kernel/mac.pri
new file mode 100644
index 0000000000..21acd06e65
--- /dev/null
+++ b/src/gui/kernel/mac.pri
@@ -0,0 +1,4 @@
+!x11:!embedded:!qpa:mac {
+ LIBS_PRIVATE += -framework Carbon -lz
+ *-mwerks:INCLUDEPATH += compat
+}
diff --git a/src/gui/kernel/qaction.cpp b/src/gui/kernel/qaction.cpp
new file mode 100644
index 0000000000..69e9889e08
--- /dev/null
+++ b/src/gui/kernel/qaction.cpp
@@ -0,0 +1,1520 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qaction.h"
+#include "qactiongroup.h"
+
+#ifndef QT_NO_ACTION
+#include "qaction_p.h"
+#include "qapplication.h"
+#include "qevent.h"
+#include "qlist.h"
+#include "qdebug.h"
+#include <private/qshortcutmap_p.h>
+#include <private/qapplication_p.h>
+#include <private/qmenu_p.h>
+
+#define QAPP_CHECK(functionName) \
+ if (!qApp) { \
+ qWarning("QAction: Initialize QApplication before calling '" functionName "'."); \
+ return; \
+ }
+
+QT_BEGIN_NAMESPACE
+
+/*
+ internal: guesses a descriptive text from a text suited for a menu entry
+ */
+static QString qt_strippedText(QString s)
+{
+ s.remove( QString::fromLatin1("...") );
+ int i = 0;
+ while (i < s.size()) {
+ ++i;
+ if (s.at(i-1) != QLatin1Char('&'))
+ continue;
+ if (i < s.size() && s.at(i) == QLatin1Char('&'))
+ ++i;
+ s.remove(i-1,1);
+ }
+ return s.trimmed();
+}
+
+
+QActionPrivate::QActionPrivate() : group(0), enabled(1), forceDisabled(0),
+ visible(1), forceInvisible(0), checkable(0), checked(0), separator(0), fontSet(false),
+ forceEnabledInSoftkeys(false), menuActionSoftkeys(false),
+ iconVisibleInMenu(-1),
+ menuRole(QAction::TextHeuristicRole), softKeyRole(QAction::NoSoftKey),
+ priority(QAction::NormalPriority)
+{
+#ifdef QT3_SUPPORT
+ static int qt_static_action_id = -1;
+ param = id = --qt_static_action_id;
+ act_signal = 0;
+#endif
+#ifndef QT_NO_SHORTCUT
+ shortcutId = 0;
+ shortcutContext = Qt::WindowShortcut;
+ autorepeat = true;
+#endif
+}
+
+QActionPrivate::~QActionPrivate()
+{
+}
+
+bool QActionPrivate::showStatusText(QWidget *widget, const QString &str)
+{
+#ifdef QT_NO_STATUSTIP
+ Q_UNUSED(widget);
+ Q_UNUSED(str);
+#else
+ if(QObject *object = widget ? widget : parent) {
+ QStatusTipEvent tip(str);
+ QApplication::sendEvent(object, &tip);
+ return true;
+ }
+#endif
+ return false;
+}
+
+void QActionPrivate::sendDataChanged()
+{
+ Q_Q(QAction);
+ QActionEvent e(QEvent::ActionChanged, q);
+ for (int i = 0; i < widgets.size(); ++i) {
+ QWidget *w = widgets.at(i);
+ QApplication::sendEvent(w, &e);
+ }
+#ifndef QT_NO_GRAPHICSVIEW
+ for (int i = 0; i < graphicsWidgets.size(); ++i) {
+ QGraphicsWidget *w = graphicsWidgets.at(i);
+ QApplication::sendEvent(w, &e);
+ }
+#endif
+ QApplication::sendEvent(q, &e);
+
+ emit q->changed();
+}
+
+#ifndef QT_NO_SHORTCUT
+void QActionPrivate::redoGrab(QShortcutMap &map)
+{
+ Q_Q(QAction);
+ if (shortcutId)
+ map.removeShortcut(shortcutId, q);
+ if (shortcut.isEmpty())
+ return;
+ shortcutId = map.addShortcut(q, shortcut, shortcutContext);
+ if (!enabled)
+ map.setShortcutEnabled(false, shortcutId, q);
+ if (!autorepeat)
+ map.setShortcutAutoRepeat(false, shortcutId, q);
+}
+
+void QActionPrivate::redoGrabAlternate(QShortcutMap &map)
+{
+ Q_Q(QAction);
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ if (const int id = alternateShortcutIds.at(i))
+ map.removeShortcut(id, q);
+ }
+ alternateShortcutIds.clear();
+ if (alternateShortcuts.isEmpty())
+ return;
+ for(int i = 0; i < alternateShortcuts.count(); ++i) {
+ const QKeySequence& alternate = alternateShortcuts.at(i);
+ if (!alternate.isEmpty())
+ alternateShortcutIds.append(map.addShortcut(q, alternate, shortcutContext));
+ else
+ alternateShortcutIds.append(0);
+ }
+ if (!enabled) {
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ const int id = alternateShortcutIds.at(i);
+ map.setShortcutEnabled(false, id, q);
+ }
+ }
+ if (!autorepeat) {
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ const int id = alternateShortcutIds.at(i);
+ map.setShortcutAutoRepeat(false, id, q);
+ }
+ }
+}
+
+void QActionPrivate::setShortcutEnabled(bool enable, QShortcutMap &map)
+{
+ Q_Q(QAction);
+ if (shortcutId)
+ map.setShortcutEnabled(enable, shortcutId, q);
+ for(int i = 0; i < alternateShortcutIds.count(); ++i) {
+ if (const int id = alternateShortcutIds.at(i))
+ map.setShortcutEnabled(enable, id, q);
+ }
+}
+#endif // QT_NO_SHORTCUT
+
+
+/*!
+ \class QAction
+ \brief The QAction class provides an abstract user interface
+ action that can be inserted into widgets.
+
+ \ingroup mainwindow-classes
+
+
+ \omit
+ * parent and widget are different
+ * parent does not define context
+ \endomit
+
+ In applications many common commands can be invoked via menus,
+ toolbar buttons, and keyboard shortcuts. Since the user expects
+ each command to be performed in the same way, regardless of the
+ user interface used, it is useful to represent each command as
+ an \e action.
+
+ Actions can be added to menus and toolbars, and will
+ automatically keep them in sync. For example, in a word processor,
+ if the user presses a Bold toolbar button, the Bold menu item
+ will automatically be checked.
+
+ Actions can be created as independent objects, but they may
+ also be created during the construction of menus; the QMenu class
+ contains convenience functions for creating actions suitable for
+ use as menu items.
+
+ A QAction may contain an icon, menu text, a shortcut, status text,
+ "What's This?" text, and a tooltip. Most of these can be set in
+ the constructor. They can also be set independently with
+ setIcon(), setText(), setIconText(), setShortcut(),
+ setStatusTip(), setWhatsThis(), and setToolTip(). For menu items,
+ it is possible to set an individual font with setFont().
+
+ Actions are added to widgets using QWidget::addAction() or
+ QGraphicsWidget::addAction(). Note that an action must be added to a
+ widget before it can be used; this is also true when the shortcut should
+ be global (i.e., Qt::ApplicationShortcut as Qt::ShortcutContext).
+
+ Once a QAction has been created it should be added to the relevant
+ menu and toolbar, then connected to the slot which will perform
+ the action. For example:
+
+ \snippet examples/mainwindows/application/mainwindow.cpp 19
+ \codeline
+ \snippet examples/mainwindows/application/mainwindow.cpp 28
+ \snippet examples/mainwindows/application/mainwindow.cpp 31
+
+ We recommend that actions are created as children of the window
+ they are used in. In most cases actions will be children of
+ the application's main window.
+
+ \sa QMenu, QToolBar, {Application Example}
+*/
+
+/*!
+ \fn void QAction::trigger()
+
+ This is a convenience slot that calls activate(Trigger).
+*/
+
+/*!
+ \fn void QAction::hover()
+
+ This is a convenience slot that calls activate(Hover).
+*/
+
+/*!
+ \enum QAction::MenuRole
+
+ This enum describes how an action should be moved into the application menu on Mac OS X.
+
+ \value NoRole This action should not be put into the application menu
+ \value TextHeuristicRole This action should be put in the application menu based on the action's text
+ as described in the QMenuBar documentation.
+ \value ApplicationSpecificRole This action should be put in the application menu with an application specific role
+ \value AboutQtRole This action matches handles the "About Qt" menu item.
+ \value AboutRole This action should be placed where the "About" menu item is in the application menu. The text of
+ the menu item will be set to "About <application name>". The application name is fetched from the
+ \c{Info.plist} file in the application's bundle (See \l{Deploying an Application on Mac OS X}).
+ \value PreferencesRole This action should be placed where the "Preferences..." menu item is in the application menu.
+ \value QuitRole This action should be placed where the Quit menu item is in the application menu.
+
+ Setting this value only has effect on items that are in the immediate menus
+ of the menubar, not the submenus of those menus. For example, if you have
+ File menu in your menubar and the File menu has a submenu, setting the
+ MenuRole for the actions in that submenu have no effect. They will never be moved.
+*/
+
+/*! \since 4.6
+
+ \enum QAction::SoftKeyRole
+
+ This enum describes how an action should be placed in the softkey bar. Currently this enum only
+ has an effect on the Symbian platform.
+
+ \value NoSoftKey This action should not be used as a softkey
+ \value PositiveSoftKey This action is used to describe a softkey with a positive or non-destructive
+ role such as Ok, Select, or Options.
+ \value NegativeSoftKey This action is used to describe a soft ey with a negative or destructive role
+ role such as Cancel, Discard, or Close.
+ \value SelectSoftKey This action is used to describe a role that selects a particular item or widget
+ in the application.
+
+ Actions with a softkey role defined are only visible in the softkey bar when the widget containing
+ the action has focus. If no widget currently has focus, the softkey framework will traverse up the
+ widget parent hierarchy looking for a widget containing softkey actions.
+ */
+
+/*!
+ Constructs an action with \a parent. If \a parent is an action
+ group the action will be automatically inserted into the group.
+*/
+QAction::QAction(QObject* parent)
+ : QObject(*(new QActionPrivate), parent)
+{
+ Q_D(QAction);
+ d->group = qobject_cast<QActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+
+
+/*!
+ Constructs an action with some \a text and \a parent. If \a
+ parent is an action group the action will be automatically
+ inserted into the group.
+
+ The action uses a stripped version of \a text (e.g. "\&Menu
+ Option..." becomes "Menu Option") as descriptive text for
+ tool buttons. You can override this by setting a specific
+ description with setText(). The same text will be used for
+ tooltips unless you specify a different text using
+ setToolTip().
+
+*/
+QAction::QAction(const QString &text, QObject* parent)
+ : QObject(*(new QActionPrivate), parent)
+{
+ Q_D(QAction);
+ d->text = text;
+ d->group = qobject_cast<QActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+
+/*!
+ Constructs an action with an \a icon and some \a text and \a
+ parent. If \a parent is an action group the action will be
+ automatically inserted into the group.
+
+ The action uses a stripped version of \a text (e.g. "\&Menu
+ Option..." becomes "Menu Option") as descriptive text for
+ tool buttons. You can override this by setting a specific
+ description with setText(). The same text will be used for
+ tooltips unless you specify a different text using
+ setToolTip().
+*/
+QAction::QAction(const QIcon &icon, const QString &text, QObject* parent)
+ : QObject(*(new QActionPrivate), parent)
+{
+ Q_D(QAction);
+ d->icon = icon;
+ d->text = text;
+ d->group = qobject_cast<QActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+
+/*!
+ \internal
+*/
+QAction::QAction(QActionPrivate &dd, QObject *parent)
+ : QObject(dd, parent)
+{
+ Q_D(QAction);
+ d->group = qobject_cast<QActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+
+/*!
+ Returns the parent widget.
+*/
+QWidget *QAction::parentWidget() const
+{
+ QObject *ret = parent();
+ while (ret && !ret->isWidgetType())
+ ret = ret->parent();
+ return (QWidget*)ret;
+}
+
+/*!
+ \since 4.2
+ Returns a list of widgets this action has been added to.
+
+ \sa QWidget::addAction(), associatedGraphicsWidgets()
+*/
+QList<QWidget *> QAction::associatedWidgets() const
+{
+ Q_D(const QAction);
+ return d->widgets;
+}
+
+#ifndef QT_NO_GRAPHICSVIEW
+/*!
+ \since 4.5
+ Returns a list of widgets this action has been added to.
+
+ \sa QWidget::addAction(), associatedWidgets()
+*/
+QList<QGraphicsWidget *> QAction::associatedGraphicsWidgets() const
+{
+ Q_D(const QAction);
+ return d->graphicsWidgets;
+}
+#endif
+
+#ifndef QT_NO_SHORTCUT
+/*!
+ \property QAction::shortcut
+ \brief the action's primary shortcut key
+
+ Valid keycodes for this property can be found in \l Qt::Key and
+ \l Qt::Modifier. There is no default shortcut key.
+*/
+void QAction::setShortcut(const QKeySequence &shortcut)
+{
+ QAPP_CHECK("setShortcut");
+
+ Q_D(QAction);
+ if (d->shortcut == shortcut)
+ return;
+
+ d->shortcut = shortcut;
+ d->redoGrab(qApp->d_func()->shortcutMap);
+ d->sendDataChanged();
+}
+
+/*!
+ \since 4.2
+
+ Sets \a shortcuts as the list of shortcuts that trigger the
+ action. The first element of the list is the primary shortcut.
+
+ \sa shortcut
+*/
+void QAction::setShortcuts(const QList<QKeySequence> &shortcuts)
+{
+ Q_D(QAction);
+
+ QList <QKeySequence> listCopy = shortcuts;
+
+ QKeySequence primary;
+ if (!listCopy.isEmpty())
+ primary = listCopy.takeFirst();
+
+ if (d->shortcut == primary && d->alternateShortcuts == listCopy)
+ return;
+
+ QAPP_CHECK("setShortcuts");
+
+ d->shortcut = primary;
+ d->alternateShortcuts = listCopy;
+ d->redoGrab(qApp->d_func()->shortcutMap);
+ d->redoGrabAlternate(qApp->d_func()->shortcutMap);
+ d->sendDataChanged();
+}
+
+/*!
+ \since 4.2
+
+ Sets a platform dependent list of shortcuts based on the \a key.
+ The result of calling this function will depend on the currently running platform.
+ Note that more than one shortcut can assigned by this action.
+ If only the primary shortcut is required, use setShortcut instead.
+
+ \sa QKeySequence::keyBindings()
+*/
+void QAction::setShortcuts(QKeySequence::StandardKey key)
+{
+ QList <QKeySequence> list = QKeySequence::keyBindings(key);
+ setShortcuts(list);
+}
+
+/*!
+ Returns the primary shortcut.
+
+ \sa setShortcuts()
+*/
+QKeySequence QAction::shortcut() const
+{
+ Q_D(const QAction);
+ return d->shortcut;
+}
+
+/*!
+ \since 4.2
+
+ Returns the list of shortcuts, with the primary shortcut as
+ the first element of the list.
+
+ \sa setShortcuts()
+*/
+QList<QKeySequence> QAction::shortcuts() const
+{
+ Q_D(const QAction);
+ QList <QKeySequence> shortcuts;
+ if (!d->shortcut.isEmpty())
+ shortcuts << d->shortcut;
+ if (!d->alternateShortcuts.isEmpty())
+ shortcuts << d->alternateShortcuts;
+ return shortcuts;
+}
+
+/*!
+ \property QAction::shortcutContext
+ \brief the context for the action's shortcut
+
+ Valid values for this property can be found in \l Qt::ShortcutContext.
+ The default value is Qt::WindowShortcut.
+*/
+void QAction::setShortcutContext(Qt::ShortcutContext context)
+{
+ Q_D(QAction);
+ if (d->shortcutContext == context)
+ return;
+ QAPP_CHECK("setShortcutContext");
+ d->shortcutContext = context;
+ d->redoGrab(qApp->d_func()->shortcutMap);
+ d->redoGrabAlternate(qApp->d_func()->shortcutMap);
+ d->sendDataChanged();
+}
+
+Qt::ShortcutContext QAction::shortcutContext() const
+{
+ Q_D(const QAction);
+ return d->shortcutContext;
+}
+
+/*!
+ \property QAction::autoRepeat
+ \brief whether the action can auto repeat
+ \since 4.2
+
+ If true, the action will auto repeat when the keyboard shortcut
+ combination is held down, provided that keyboard auto repeat is
+ enabled on the system.
+ The default value is true.
+*/
+void QAction::setAutoRepeat(bool on)
+{
+ Q_D(QAction);
+ if (d->autorepeat == on)
+ return;
+ QAPP_CHECK("setAutoRepeat");
+ d->autorepeat = on;
+ d->redoGrab(qApp->d_func()->shortcutMap);
+ d->redoGrabAlternate(qApp->d_func()->shortcutMap);
+ d->sendDataChanged();
+}
+
+bool QAction::autoRepeat() const
+{
+ Q_D(const QAction);
+ return d->autorepeat;
+}
+#endif // QT_NO_SHORTCUT
+
+/*!
+ \property QAction::font
+ \brief the action's font
+
+ The font property is used to render the text set on the
+ QAction. The font will can be considered a hint as it will not be
+ consulted in all cases based upon application and style.
+
+ By default, this property contains the application's default font.
+
+ \sa QAction::setText() QStyle
+*/
+void QAction::setFont(const QFont &font)
+{
+ Q_D(QAction);
+ if (d->font == font)
+ return;
+
+ d->fontSet = true;
+ d->font = font;
+ d->sendDataChanged();
+}
+
+QFont QAction::font() const
+{
+ Q_D(const QAction);
+ return d->font;
+}
+
+#ifdef QT3_SUPPORT
+/*!
+ Use one of the QAction constructors that doesn't take a \a name
+ argument and call setObjectName() instead.
+*/
+QAction::QAction(QObject* parent, const char* name)
+ : QObject(*(new QActionPrivate), parent)
+{
+ Q_D(QAction);
+ setObjectName(QString::fromAscii(name));
+ d->group = qobject_cast<QActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+
+
+/*!
+ Use one of the QAction constructors that doesn't take a \a name
+ argument and call setObjectName() instead.
+*/
+QAction::QAction(const QString &text, const QKeySequence &shortcut, QObject* parent, const char* name)
+ : QObject(*(new QActionPrivate), parent)
+{
+ Q_D(QAction);
+ setObjectName(QString::fromAscii(name));
+ d->text = text;
+ setShortcut(shortcut);
+ d->group = qobject_cast<QActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+
+/*!
+ Use one of the QAction constructors that doesn't take a \a name
+ argument and call setObjectName() instead.
+*/
+QAction::QAction(const QIcon &icon, const QString &text, const QKeySequence &shortcut,
+ QObject* parent, const char* name)
+ : QObject(*(new QActionPrivate), parent)
+{
+ Q_D(QAction);
+ setObjectName(QString::fromAscii(name));
+ d->text = text;
+ setShortcut(shortcut);
+ d->icon = icon;
+ d->group = qobject_cast<QActionGroup *>(parent);
+ if (d->group)
+ d->group->addAction(this);
+}
+#endif
+
+/*!
+ Destroys the object and frees allocated resources.
+*/
+QAction::~QAction()
+{
+ Q_D(QAction);
+ for (int i = d->widgets.size()-1; i >= 0; --i) {
+ QWidget *w = d->widgets.at(i);
+ w->removeAction(this);
+ }
+#ifndef QT_NO_GRAPHICSVIEW
+ for (int i = d->graphicsWidgets.size()-1; i >= 0; --i) {
+ QGraphicsWidget *w = d->graphicsWidgets.at(i);
+ w->removeAction(this);
+ }
+#endif
+ if (d->group)
+ d->group->removeAction(this);
+#ifndef QT_NO_SHORTCUT
+ if (d->shortcutId && qApp) {
+ qApp->d_func()->shortcutMap.removeShortcut(d->shortcutId, this);
+ for(int i = 0; i < d->alternateShortcutIds.count(); ++i) {
+ const int id = d->alternateShortcutIds.at(i);
+ qApp->d_func()->shortcutMap.removeShortcut(id, this);
+ }
+ }
+#endif
+}
+
+/*!
+ Sets this action group to \a group. The action will be automatically
+ added to the group's list of actions.
+
+ Actions within the group will be mutually exclusive.
+
+ \sa QActionGroup, QAction::actionGroup()
+*/
+void QAction::setActionGroup(QActionGroup *group)
+{
+ Q_D(QAction);
+ if(group == d->group)
+ return;
+
+ if(d->group)
+ d->group->removeAction(this);
+ d->group = group;
+ if(group)
+ group->addAction(this);
+}
+
+/*!
+ Returns the action group for this action. If no action group manages
+ this action then 0 will be returned.
+
+ \sa QActionGroup, QAction::setActionGroup()
+*/
+QActionGroup *QAction::actionGroup() const
+{
+ Q_D(const QAction);
+ return d->group;
+}
+
+
+/*!
+ \property QAction::icon
+ \brief the action's icon
+
+ In toolbars, the icon is used as the tool button icon; in menus,
+ it is displayed to the left of the menu text. There is no default
+ icon.
+
+ On Symbian the icons which are passed to softkeys, i.e. to actions with
+ softkey role, need to have pixmap alpha channel correctly set otherwise
+ drawing artifacts will appear when softkey is pressed down.
+
+ If a null icon (QIcon::isNull() is passed into this function,
+ the icon of the action is cleared.
+*/
+void QAction::setIcon(const QIcon &icon)
+{
+ Q_D(QAction);
+ d->icon = icon;
+ d->sendDataChanged();
+}
+
+QIcon QAction::icon() const
+{
+ Q_D(const QAction);
+ return d->icon;
+}
+
+#ifndef QT_NO_MENU
+/*!
+ Returns the menu contained by this action. Actions that contain
+ menus can be used to create menu items with submenus, or inserted
+ into toolbars to create buttons with popup menus.
+
+ \sa QMenu::addAction()
+*/
+QMenu *QAction::menu() const
+{
+ Q_D(const QAction);
+ return d->menu;
+}
+
+/*!
+ Sets the menu contained by this action to the specified \a menu.
+*/
+void QAction::setMenu(QMenu *menu)
+{
+ Q_D(QAction);
+ if (d->menu)
+ d->menu->d_func()->setOverrideMenuAction(0); //we reset the default action of any previous menu
+ d->menu = menu;
+ if (menu)
+ menu->d_func()->setOverrideMenuAction(this);
+ d->sendDataChanged();
+}
+#endif // QT_NO_MENU
+
+/*!
+ If \a b is true then this action will be considered a separator.
+
+ How a separator is represented depends on the widget it is inserted
+ into. Under most circumstances the text, submenu, and icon will be
+ ignored for separator actions.
+
+ \sa QAction::isSeparator()
+*/
+void QAction::setSeparator(bool b)
+{
+ Q_D(QAction);
+ if (d->separator == b)
+ return;
+
+ d->separator = b;
+ d->sendDataChanged();
+}
+
+/*!
+ Returns true if this action is a separator action; otherwise it
+ returns false.
+
+ \sa QAction::setSeparator()
+*/
+bool QAction::isSeparator() const
+{
+ Q_D(const QAction);
+ return d->separator;
+}
+
+/*!
+ \property QAction::text
+ \brief the action's descriptive text
+
+ If the action is added to a menu, the menu option will consist of
+ the icon (if there is one), the text, and the shortcut (if there
+ is one). If the text is not explicitly set in the constructor, or
+ by using setText(), the action's description icon text will be
+ used as text. There is no default text.
+
+ \sa iconText
+*/
+void QAction::setText(const QString &text)
+{
+ Q_D(QAction);
+ if (d->text == text)
+ return;
+
+ d->text = text;
+ d->sendDataChanged();
+}
+
+QString QAction::text() const
+{
+ Q_D(const QAction);
+ QString s = d->text;
+ if(s.isEmpty()) {
+ s = d->iconText;
+ s.replace(QLatin1Char('&'), QLatin1String("&&"));
+ }
+ return s;
+}
+
+
+
+
+
+/*!
+ \property QAction::iconText
+ \brief the action's descriptive icon text
+
+ If QToolBar::toolButtonStyle is set to a value that permits text to
+ be displayed, the text defined held in this property appears as a
+ label in the relevant tool button.
+
+ It also serves as the default text in menus and tooltips if the action
+ has not been defined with setText() or setToolTip(), and will
+ also be used in toolbar buttons if no icon has been defined using setIcon().
+
+ If the icon text is not explicitly set, the action's normal text will be
+ used for the icon text.
+
+ By default, this property contains an empty string.
+
+ \sa setToolTip(), setStatusTip()
+*/
+void QAction::setIconText(const QString &text)
+{
+ Q_D(QAction);
+ if (d->iconText == text)
+ return;
+
+ d->iconText = text;
+ d->sendDataChanged();
+}
+
+QString QAction::iconText() const
+{
+ Q_D(const QAction);
+ if (d->iconText.isEmpty())
+ return qt_strippedText(d->text);
+ return d->iconText;
+}
+
+/*!
+ \property QAction::toolTip
+ \brief the action's tooltip
+
+ This text is used for the tooltip. If no tooltip is specified,
+ the action's text is used.
+
+ By default, this property contains the action's text.
+
+ \sa setStatusTip() setShortcut()
+*/
+void QAction::setToolTip(const QString &tooltip)
+{
+ Q_D(QAction);
+ if (d->tooltip == tooltip)
+ return;
+
+ d->tooltip = tooltip;
+ d->sendDataChanged();
+}
+
+QString QAction::toolTip() const
+{
+ Q_D(const QAction);
+ if (d->tooltip.isEmpty()) {
+ if (!d->text.isEmpty())
+ return qt_strippedText(d->text);
+ return qt_strippedText(d->iconText);
+ }
+ return d->tooltip;
+}
+
+/*!
+ \property QAction::statusTip
+ \brief the action's status tip
+
+ The status tip is displayed on all status bars provided by the
+ action's top-level parent widget.
+
+ By default, this property contains an empty string.
+
+ \sa setToolTip() showStatusText()
+*/
+void QAction::setStatusTip(const QString &statustip)
+{
+ Q_D(QAction);
+ if (d->statustip == statustip)
+ return;
+
+ d->statustip = statustip;
+ d->sendDataChanged();
+}
+
+QString QAction::statusTip() const
+{
+ Q_D(const QAction);
+ return d->statustip;
+}
+
+/*!
+ \property QAction::whatsThis
+ \brief the action's "What's This?" help text
+
+ The "What's This?" text is used to provide a brief description of
+ the action. The text may contain rich text. There is no default
+ "What's This?" text.
+
+ \sa QWhatsThis Q3StyleSheet
+*/
+void QAction::setWhatsThis(const QString &whatsthis)
+{
+ Q_D(QAction);
+ if (d->whatsthis == whatsthis)
+ return;
+
+ d->whatsthis = whatsthis;
+ d->sendDataChanged();
+}
+
+QString QAction::whatsThis() const
+{
+ Q_D(const QAction);
+ return d->whatsthis;
+}
+
+/*!
+ \enum QAction::Priority
+ \since 4.6
+
+ This enum defines priorities for actions in user interface.
+
+ \value LowPriority The action should not be prioritized in
+ the user interface.
+
+ \value NormalPriority
+
+ \value HighPriority The action should be prioritized in
+ the user interface.
+
+ \sa priority
+*/
+
+
+/*!
+ \property QAction::priority
+ \since 4.6
+
+ \brief the actions's priority in the user interface.
+
+ This property can be set to indicate how the action should be prioritized
+ in the user interface.
+
+ For instance, when toolbars have the Qt::ToolButtonTextBesideIcon
+ mode set, then actions with LowPriority will not show the text
+ labels.
+*/
+void QAction::setPriority(Priority priority)
+{
+ Q_D(QAction);
+ if (d->priority == priority)
+ return;
+
+ d->priority = priority;
+ d->sendDataChanged();
+}
+
+QAction::Priority QAction::priority() const
+{
+ Q_D(const QAction);
+ return d->priority;
+}
+
+/*!
+ \property QAction::checkable
+ \brief whether the action is a checkable action
+
+ A checkable action is one which has an on/off state. For example,
+ in a word processor, a Bold toolbar button may be either on or
+ off. An action which is not a toggle action is a command action;
+ a command action is simply executed, e.g. file save.
+ By default, this property is false.
+
+ In some situations, the state of one toggle action should depend
+ on the state of others. For example, "Left Align", "Center" and
+ "Right Align" toggle actions are mutually exclusive. To achieve
+ exclusive toggling, add the relevant toggle actions to a
+ QActionGroup with the QActionGroup::exclusive property set to
+ true.
+
+ \sa QAction::setChecked()
+*/
+void QAction::setCheckable(bool b)
+{
+ Q_D(QAction);
+ if (d->checkable == b)
+ return;
+
+ d->checkable = b;
+ d->checked = false;
+ d->sendDataChanged();
+}
+
+bool QAction::isCheckable() const
+{
+ Q_D(const QAction);
+ return d->checkable;
+}
+
+/*!
+ \fn void QAction::toggle()
+
+ This is a convenience function for the \l checked property.
+ Connect to it to change the checked state to its opposite state.
+*/
+void QAction::toggle()
+{
+ Q_D(QAction);
+ setChecked(!d->checked);
+}
+
+/*!
+ \property QAction::checked
+ \brief whether the action is checked.
+
+ Only checkable actions can be checked. By default, this is false
+ (the action is unchecked).
+
+ \sa checkable
+*/
+void QAction::setChecked(bool b)
+{
+ Q_D(QAction);
+ if (!d->checkable || d->checked == b)
+ return;
+
+ QPointer<QAction> guard(this);
+ d->checked = b;
+ d->sendDataChanged();
+ if (guard)
+ emit toggled(b);
+}
+
+bool QAction::isChecked() const
+{
+ Q_D(const QAction);
+ return d->checked;
+}
+
+/*!
+ \fn void QAction::setDisabled(bool b)
+
+ This is a convenience function for the \l enabled property, that
+ is useful for signals--slots connections. If \a b is true the
+ action is disabled; otherwise it is enabled.
+*/
+
+/*!
+ \property QAction::enabled
+ \brief whether the action is enabled
+
+ Disabled actions cannot be chosen by the user. They do not
+ disappear from menus or toolbars, but they are displayed in a way
+ which indicates that they are unavailable. For example, they might
+ be displayed using only shades of gray.
+
+ \gui{What's This?} help on disabled actions is still available, provided
+ that the QAction::whatsThis property is set.
+
+ An action will be disabled when all widgets to which it is added
+ (with QWidget::addAction()) are disabled or not visible. When an
+ action is disabled, it is not possible to trigger it through its
+ shortcut.
+
+ By default, this property is true (actions are enabled).
+
+ \sa text
+*/
+void QAction::setEnabled(bool b)
+{
+ Q_D(QAction);
+ if (b == d->enabled && b != d->forceDisabled)
+ return;
+ d->forceDisabled = !b;
+ if (b && (!d->visible || (d->group && !d->group->isEnabled())))
+ return;
+ QAPP_CHECK("setEnabled");
+ d->enabled = b;
+#ifndef QT_NO_SHORTCUT
+ d->setShortcutEnabled(b, qApp->d_func()->shortcutMap);
+#endif
+ d->sendDataChanged();
+}
+
+bool QAction::isEnabled() const
+{
+ Q_D(const QAction);
+ return d->enabled;
+}
+
+/*!
+ \property QAction::visible
+ \brief whether the action can be seen (e.g. in menus and toolbars)
+
+ If \e visible is true the action can be seen (e.g. in menus and
+ toolbars) and chosen by the user; if \e visible is false the
+ action cannot be seen or chosen by the user.
+
+ Actions which are not visible are \e not grayed out; they do not
+ appear at all.
+
+ By default, this property is true (actions are visible).
+*/
+void QAction::setVisible(bool b)
+{
+ Q_D(QAction);
+ if (b == d->visible && b != d->forceInvisible)
+ return;
+ QAPP_CHECK("setVisible");
+ d->forceInvisible = !b;
+ d->visible = b;
+ d->enabled = b && !d->forceDisabled && (!d->group || d->group->isEnabled()) ;
+#ifndef QT_NO_SHORTCUT
+ d->setShortcutEnabled(d->enabled, qApp->d_func()->shortcutMap);
+#endif
+ d->sendDataChanged();
+}
+
+
+bool QAction::isVisible() const
+{
+ Q_D(const QAction);
+ return d->visible;
+}
+
+/*!
+ \reimp
+*/
+bool
+QAction::event(QEvent *e)
+{
+#ifndef QT_NO_SHORTCUT
+ if (e->type() == QEvent::Shortcut) {
+ QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
+ Q_ASSERT_X(se->key() == d_func()->shortcut || d_func()->alternateShortcuts.contains(se->key()),
+ "QAction::event",
+ "Received shortcut event from incorrect shortcut");
+ if (se->isAmbiguous())
+ qWarning("QAction::eventFilter: Ambiguous shortcut overload: %s", QString(se->key()).toLatin1().constData());
+ else
+ activate(Trigger);
+ return true;
+ }
+#endif
+ return QObject::event(e);
+}
+
+/*!
+ Returns the user data as set in QAction::setData.
+
+ \sa setData()
+*/
+QVariant
+QAction::data() const
+{
+ Q_D(const QAction);
+ return d->userData;
+}
+
+/*!
+ \fn void QAction::setData(const QVariant &userData)
+
+ Sets the action's internal data to the given \a userData.
+
+ \sa data()
+*/
+void
+QAction::setData(const QVariant &data)
+{
+ Q_D(QAction);
+ d->userData = data;
+ d->sendDataChanged();
+}
+
+
+/*!
+ Updates the relevant status bar for the \a widget specified by sending a
+ QStatusTipEvent to its parent widget. Returns true if an event was sent;
+ otherwise returns false.
+
+ If a null widget is specified, the event is sent to the action's parent.
+
+ \sa statusTip
+*/
+bool
+QAction::showStatusText(QWidget *widget)
+{
+ return d_func()->showStatusText(widget, statusTip());
+}
+
+/*!
+ Sends the relevant signals for ActionEvent \a event.
+
+ Action based widgets use this API to cause the QAction
+ to emit signals as well as emitting their own.
+*/
+void QAction::activate(ActionEvent event)
+{
+ Q_D(QAction);
+ if(event == Trigger) {
+ QObject *guard = this;
+ QMetaObject::addGuard(&guard);
+ if(d->checkable) {
+ // the checked action of an exclusive group cannot be unchecked
+ if (d->checked && (d->group && d->group->isExclusive()
+ && d->group->checkedAction() == this)) {
+ if (guard)
+ emit triggered(true);
+ QMetaObject::removeGuard(&guard);
+ return;
+ }
+ setChecked(!d->checked);
+ }
+ if (guard)
+ emit triggered(d->checked);
+#ifdef QT3_SUPPORT
+ if (guard)
+ emit activated(d->param);
+#endif
+ QMetaObject::removeGuard(&guard);
+ } else if(event == Hover) {
+ emit hovered();
+ }
+}
+
+/*!
+ \fn void QAction::triggered(bool checked)
+
+ This signal is emitted when an action is activated by the user;
+ for example, when the user clicks a menu option, toolbar button,
+ or presses an action's shortcut key combination, or when trigger()
+ was called. Notably, it is \e not emitted when setChecked() or
+ toggle() is called.
+
+ If the action is checkable, \a checked is true if the action is
+ checked, or false if the action is unchecked.
+
+ \sa QAction::activate(), QAction::toggled(), checked
+*/
+
+/*!
+ \fn void QAction::toggled(bool checked)
+
+ This signal is emitted whenever a checkable action changes its
+ isChecked() status. This can be the result of a user interaction,
+ or because setChecked() was called.
+
+ \a checked is true if the action is checked, or false if the
+ action is unchecked.
+
+ \sa QAction::activate(), QAction::triggered(), checked
+*/
+
+/*!
+ \fn void QAction::hovered()
+
+ This signal is emitted when an action is highlighted by the user;
+ for example, when the user pauses with the cursor over a menu option,
+ toolbar button, or presses an action's shortcut key combination.
+
+ \sa QAction::activate()
+*/
+
+/*!
+ \fn void QAction::changed()
+
+ This signal is emitted when an action has changed. If you
+ are only interested in actions in a given widget, you can
+ watch for QWidget::actionEvent() sent with an
+ QEvent::ActionChanged.
+
+ \sa QWidget::actionEvent()
+*/
+
+/*!
+ \enum QAction::ActionEvent
+
+ This enum type is used when calling QAction::activate()
+
+ \value Trigger this will cause the QAction::triggered() signal to be emitted.
+
+ \value Hover this will cause the QAction::hovered() signal to be emitted.
+*/
+
+/*!
+ \fn void QAction::setMenuText(const QString &text)
+
+ Use setText() instead.
+*/
+
+/*!
+ \fn QString QAction::menuText() const
+
+ Use text() instead.
+*/
+
+/*!
+ \fn bool QAction::isOn() const
+
+ Use isChecked() instead.
+*/
+
+/*!
+ \fn void QAction::setOn(bool b)
+
+ Use setChecked() instead.
+*/
+
+/*!
+ \fn bool QAction::isToggleAction() const
+
+ Use isCheckable() instead.
+*/
+
+/*!
+ \fn void QAction::setToggleAction(bool b)
+
+ Use setCheckable() instead.
+*/
+
+/*!
+ \fn void QAction::setIconSet(const QIcon &i)
+
+ Use setIcon() instead.
+*/
+
+/*!
+ \fn bool QAction::addTo(QWidget *w)
+
+ Use QWidget::addAction() instead.
+
+ \oldcode
+ action->addTo(widget);
+ \newcode
+ widget->addAction(action);
+ \endcode
+*/
+
+/*!
+ \fn bool QAction::removeFrom(QWidget *w)
+
+ Use QWidget::removeAction() instead.
+
+ \oldcode
+ action->removeFrom(widget);
+ \newcode
+ widget->removeAction(action);
+ \endcode
+*/
+
+/*!
+ \fn void QAction::setAccel(const QKeySequence &shortcut)
+
+ Use setShortcut() instead.
+*/
+
+/*!
+ \fn QIcon QAction::iconSet() const
+
+ Use icon() instead.
+*/
+
+/*!
+ \fn QKeySequence QAction::accel() const
+
+ Use shortcut() instead.
+*/
+
+/*!
+ \fn void QAction::activated(int i);
+
+ Use triggered() instead.
+*/
+
+
+/*!
+ \property QAction::menuRole
+ \brief the action's menu role
+ \since 4.2
+
+ This indicates what role the action serves in the application menu on Mac
+ OS X. By default all action have the TextHeuristicRole, which means that
+ the action is added based on its text (see QMenuBar for more information).
+
+ The menu role can only be changed before the actions are put into the menu
+ bar in Mac OS X (usually just before the first application window is
+ shown).
+*/
+void QAction::setMenuRole(MenuRole menuRole)
+{
+ Q_D(QAction);
+ if (d->menuRole == menuRole)
+ return;
+
+ d->menuRole = menuRole;
+ d->sendDataChanged();
+}
+
+QAction::MenuRole QAction::menuRole() const
+{
+ Q_D(const QAction);
+ return d->menuRole;
+}
+
+/*!
+ \property QAction::softKeyRole
+ \brief the action's softkey role
+ \since 4.6
+
+ This indicates what type of role this action describes in the softkey framework
+ on platforms where such a framework is supported. Currently this is only
+ supported on the Symbian platform.
+
+ The softkey role can be changed any time.
+*/
+void QAction::setSoftKeyRole(SoftKeyRole softKeyRole)
+{
+ Q_D(QAction);
+ if (d->softKeyRole == softKeyRole)
+ return;
+
+ d->softKeyRole = softKeyRole;
+ d->sendDataChanged();
+}
+
+QAction::SoftKeyRole QAction::softKeyRole() const
+{
+ Q_D(const QAction);
+ return d->softKeyRole;
+}
+
+/*!
+ \property QAction::iconVisibleInMenu
+ \brief Whether or not an action should show an icon in a menu
+ \since 4.4
+
+ In some applications, it may make sense to have actions with icons in the
+ toolbar, but not in menus. If true, the icon (if valid) is shown in the menu, when it
+ is false, it is not shown.
+
+ The default is to follow whether the Qt::AA_DontShowIconsInMenus attribute
+ is set for the application. Explicitly settings this property overrides
+ the presence (or abscence) of the attribute.
+
+ For example:
+ \snippet doc/src/snippets/code/src_gui_kernel_qaction.cpp 0
+
+ \sa QAction::icon QApplication::setAttribute()
+*/
+void QAction::setIconVisibleInMenu(bool visible)
+{
+ Q_D(QAction);
+ if (d->iconVisibleInMenu == -1 || visible != bool(d->iconVisibleInMenu)) {
+ int oldValue = d->iconVisibleInMenu;
+ d->iconVisibleInMenu = visible;
+ // Only send data changed if we really need to.
+ if (oldValue != -1
+ || (oldValue == -1
+ && visible == !QApplication::instance()->testAttribute(Qt::AA_DontShowIconsInMenus))) {
+ d->sendDataChanged();
+ }
+ }
+}
+
+bool QAction::isIconVisibleInMenu() const
+{
+ Q_D(const QAction);
+ if (d->iconVisibleInMenu == -1) {
+ return !QApplication::instance()->testAttribute(Qt::AA_DontShowIconsInMenus);
+ }
+ return d->iconVisibleInMenu;
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qaction.cpp"
+
+#endif // QT_NO_ACTION
diff --git a/src/gui/kernel/qaction.h b/src/gui/kernel/qaction.h
new file mode 100644
index 0000000000..856fd92f10
--- /dev/null
+++ b/src/gui/kernel/qaction.h
@@ -0,0 +1,264 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QACTION_H
+#define QACTION_H
+
+#include <QtGui/qkeysequence.h>
+#include <QtCore/qstring.h>
+#include <QtGui/qwidget.h>
+#include <QtCore/qvariant.h>
+#include <QtGui/qicon.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Gui)
+
+#ifndef QT_NO_ACTION
+
+class QMenu;
+class QActionGroup;
+class QActionPrivate;
+class QGraphicsWidget;
+
+class Q_GUI_EXPORT QAction : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QAction)
+
+ Q_ENUMS(MenuRole)
+ Q_ENUMS(SoftKeyRole)
+ Q_ENUMS(Priority)
+ Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable NOTIFY changed)
+ Q_PROPERTY(bool checked READ isChecked WRITE setChecked DESIGNABLE isCheckable NOTIFY toggled)
+ Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY changed)
+ Q_PROPERTY(QIcon icon READ icon WRITE setIcon NOTIFY changed)
+ Q_PROPERTY(QString text READ text WRITE setText NOTIFY changed)
+ Q_PROPERTY(QString iconText READ iconText WRITE setIconText NOTIFY changed)
+ Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip NOTIFY changed)
+ Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip NOTIFY changed)
+ Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis NOTIFY changed)
+ Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY changed)
+#ifndef QT_NO_SHORTCUT
+ Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut NOTIFY changed)
+ Q_PROPERTY(Qt::ShortcutContext shortcutContext READ shortcutContext WRITE setShortcutContext NOTIFY changed)
+ Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat NOTIFY changed)
+#endif
+ Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY changed)
+ Q_PROPERTY(MenuRole menuRole READ menuRole WRITE setMenuRole NOTIFY changed)
+ Q_PROPERTY(SoftKeyRole softKeyRole READ softKeyRole WRITE setSoftKeyRole NOTIFY changed)
+ Q_PROPERTY(bool iconVisibleInMenu READ isIconVisibleInMenu WRITE setIconVisibleInMenu NOTIFY changed)
+ Q_PROPERTY(Priority priority READ priority WRITE setPriority)
+
+public:
+ enum MenuRole { NoRole, TextHeuristicRole, ApplicationSpecificRole, AboutQtRole,
+ AboutRole, PreferencesRole, QuitRole };
+ enum SoftKeyRole {
+ NoSoftKey, PositiveSoftKey, NegativeSoftKey, SelectSoftKey };
+ enum Priority { LowPriority = 0,
+ NormalPriority = 128,
+ HighPriority = 256};
+ explicit QAction(QObject* parent);
+ QAction(const QString &text, QObject* parent);
+ QAction(const QIcon &icon, const QString &text, QObject* parent);
+
+#ifdef QT3_SUPPORT
+ QT3_SUPPORT_CONSTRUCTOR QAction(QObject* parent, const char* name);
+ QT3_SUPPORT_CONSTRUCTOR QAction(const QString &text, const QKeySequence &shortcut,
+ QObject* parent, const char* name);
+ QT3_SUPPORT_CONSTRUCTOR QAction(const QIcon &icon, const QString &text,
+ const QKeySequence &shortcut,
+ QObject* parent, const char* name);
+#endif
+ ~QAction();
+
+ void setActionGroup(QActionGroup *group);
+ QActionGroup *actionGroup() const;
+ void setIcon(const QIcon &icon);
+ QIcon icon() const;
+
+ void setText(const QString &text);
+ QString text() const;
+
+ void setIconText(const QString &text);
+ QString iconText() const;
+
+ void setToolTip(const QString &tip);
+ QString toolTip() const;
+
+ void setStatusTip(const QString &statusTip);
+ QString statusTip() const;
+
+ void setWhatsThis(const QString &what);
+ QString whatsThis() const;
+
+ void setPriority(Priority priority);
+ Priority priority() const;
+
+#ifndef QT_NO_MENU
+ QMenu *menu() const;
+ void setMenu(QMenu *menu);
+#endif
+
+ void setSeparator(bool b);
+ bool isSeparator() const;
+
+#ifndef QT_NO_SHORTCUT
+ void setShortcut(const QKeySequence &shortcut);
+ QKeySequence shortcut() const;
+
+ void setShortcuts(const QList<QKeySequence> &shortcuts);
+ void setShortcuts(QKeySequence::StandardKey);
+ QList<QKeySequence> shortcuts() const;
+
+ void setShortcutContext(Qt::ShortcutContext context);
+ Qt::ShortcutContext shortcutContext() const;
+
+ void setAutoRepeat(bool);
+ bool autoRepeat() const;
+#endif
+
+ void setFont(const QFont &font);
+ QFont font() const;
+
+ void setCheckable(bool);
+ bool isCheckable() const;
+
+ QVariant data() const;
+ void setData(const QVariant &var);
+
+ bool isChecked() const;
+
+ bool isEnabled() const;
+
+ bool isVisible() const;
+
+ enum ActionEvent { Trigger, Hover };
+ void activate(ActionEvent event);
+ bool showStatusText(QWidget *widget=0);
+
+ void setMenuRole(MenuRole menuRole);
+ MenuRole menuRole() const;
+
+ void setSoftKeyRole(SoftKeyRole softKeyRole);
+ SoftKeyRole softKeyRole() const;
+
+ void setIconVisibleInMenu(bool visible);
+ bool isIconVisibleInMenu() const;
+
+#ifdef QT3_SUPPORT
+ inline QT3_SUPPORT void setMenuText(const QString &text) { setText(text); }
+ inline QT3_SUPPORT QString menuText() const { return text(); }
+ inline QT3_SUPPORT bool isOn() const { return isChecked(); }
+ inline QT3_SUPPORT bool isToggleAction() const { return isCheckable(); }
+ inline QT3_SUPPORT void setToggleAction(bool b) { setCheckable(b); }
+ inline QT3_SUPPORT void setIconSet(const QIcon &i) { setIcon(i); }
+ inline QT3_SUPPORT QIcon iconSet() const { return icon(); }
+ inline QT3_SUPPORT bool addTo(QWidget *w) { w->addAction(this); return true; }
+ inline QT3_SUPPORT bool removeFrom(QWidget *w) { w->removeAction(this); return true; }
+ inline QT3_SUPPORT void setAccel(const QKeySequence &shortcut) { setShortcut(shortcut); }
+ inline QT3_SUPPORT QKeySequence accel() const { return shortcut(); }
+#endif
+
+ QWidget *parentWidget() const;
+
+ QList<QWidget *> associatedWidgets() const;
+#ifndef QT_NO_GRAPHICSVIEW
+ QList<QGraphicsWidget *> associatedGraphicsWidgets() const; // ### suboptimal
+#endif
+
+protected:
+ bool event(QEvent *);
+ QAction(QActionPrivate &dd, QObject *parent);
+
+public Q_SLOTS:
+#ifdef QT3_SUPPORT
+ inline QT_MOC_COMPAT void setOn(bool b) { setChecked(b); }
+#endif
+ void trigger() { activate(Trigger); }
+ void hover() { activate(Hover); }
+ void setChecked(bool);
+ void toggle();
+ void setEnabled(bool);
+ inline void setDisabled(bool b) { setEnabled(!b); }
+ void setVisible(bool);
+
+Q_SIGNALS:
+ void changed();
+ void triggered(bool checked = false);
+ void hovered();
+ void toggled(bool);
+#ifdef QT3_SUPPORT
+ QT_MOC_COMPAT void activated(int = 0);
+#endif
+
+private:
+ Q_DISABLE_COPY(QAction)
+
+#ifdef QT3_SUPPORT
+ friend class QMenuItem;
+#endif
+ friend class QGraphicsWidget;
+ friend class QWidget;
+ friend class QActionGroup;
+ friend class QMenu;
+ friend class QMenuPrivate;
+ friend class QMenuBar;
+ friend class QShortcutMap;
+ friend class QToolButton;
+#ifdef Q_WS_MAC
+ friend void qt_mac_clear_status_text(QAction *action);
+#endif
+};
+
+QT_BEGIN_INCLUDE_NAMESPACE
+#include <QtGui/qactiongroup.h>
+QT_END_INCLUDE_NAMESPACE
+
+#endif // QT_NO_ACTION
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QACTION_H
diff --git a/src/gui/kernel/qaction_p.h b/src/gui/kernel/qaction_p.h
new file mode 100644
index 0000000000..f3154f90c1
--- /dev/null
+++ b/src/gui/kernel/qaction_p.h
@@ -0,0 +1,144 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QACTION_P_H
+#define QACTION_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of other Qt classes. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "QtGui/qaction.h"
+#include "QtGui/qmenu.h"
+#include "private/qgraphicswidget_p.h"
+#include "private/qobject_p.h"
+
+QT_BEGIN_NAMESPACE
+
+#ifndef QT_NO_ACTION
+
+#ifdef QT3_SUPPORT
+class QMenuItemEmitter;
+#endif
+
+class QShortcutMap;
+
+class Q_AUTOTEST_EXPORT QActionPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QAction)
+public:
+ QActionPrivate();
+ ~QActionPrivate();
+
+ static QActionPrivate *get(QAction *q)
+ {
+ return q->d_func();
+ }
+
+ bool showStatusText(QWidget *w, const QString &str);
+
+ QPointer<QActionGroup> group;
+ QString text;
+ QString iconText;
+ QIcon icon;
+ QString tooltip;
+ QString statustip;
+ QString whatsthis;
+#ifndef QT_NO_SHORTCUT
+ QKeySequence shortcut;
+ QList<QKeySequence> alternateShortcuts;
+#endif
+ QVariant userData;
+#ifndef QT_NO_SHORTCUT
+ int shortcutId;
+ QList<int> alternateShortcutIds;
+ Qt::ShortcutContext shortcutContext;
+ uint autorepeat : 1;
+#endif
+ QFont font;
+ QPointer<QMenu> menu;
+ uint enabled : 1, forceDisabled : 1;
+ uint visible : 1, forceInvisible : 1;
+ uint checkable : 1;
+ uint checked : 1;
+ uint separator : 1;
+ uint fontSet : 1;
+
+ //for soft keys management
+ uint forceEnabledInSoftkeys : 1;
+ uint menuActionSoftkeys : 1;
+ int iconVisibleInMenu : 3; // Only has values -1, 0, and 1
+
+ QAction::MenuRole menuRole;
+ QAction::SoftKeyRole softKeyRole;
+ QAction::Priority priority;
+
+ QList<QWidget *> widgets;
+#ifndef QT_NO_GRAPHICSVIEW
+ QList<QGraphicsWidget *> graphicsWidgets;
+#endif
+#ifndef QT_NO_SHORTCUT
+ void redoGrab(QShortcutMap &map);
+ void redoGrabAlternate(QShortcutMap &map);
+ void setShortcutEnabled(bool enable, QShortcutMap &map);
+
+ static QShortcutMap *globalMap;
+#endif // QT_NO_SHORTCUT
+
+#ifdef QT3_SUPPORT //for menubar/menu compat
+ QMenuItemEmitter *act_signal;
+ int id, param;
+#endif
+ void sendDataChanged();
+};
+
+#endif // QT_NO_ACTION
+
+QT_END_NAMESPACE
+
+#endif // QACTION_P_H
diff --git a/src/gui/kernel/qactiongroup.cpp b/src/gui/kernel/qactiongroup.cpp
new file mode 100644
index 0000000000..95ea8afab7
--- /dev/null
+++ b/src/gui/kernel/qactiongroup.cpp
@@ -0,0 +1,422 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qactiongroup.h"
+
+#ifndef QT_NO_ACTION
+
+#include "qaction_p.h"
+#include "qapplication.h"
+#include "qevent.h"
+#include "qlist.h"
+
+QT_BEGIN_NAMESPACE
+
+class QActionGroupPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QActionGroup)
+public:
+ QActionGroupPrivate() : exclusive(1), enabled(1), visible(1) { }
+ QList<QAction *> actions;
+ QPointer<QAction> current;
+ uint exclusive : 1;
+ uint enabled : 1;
+ uint visible : 1;
+
+private:
+ void _q_actionTriggered(); //private slot
+ void _q_actionChanged(); //private slot
+ void _q_actionHovered(); //private slot
+};
+
+void QActionGroupPrivate::_q_actionChanged()
+{
+ Q_Q(QActionGroup);
+ QAction *action = qobject_cast<QAction*>(q->sender());
+ Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionChanged", "internal error");
+ if(exclusive) {
+ if (action->isChecked()) {
+ if (action != current) {
+ if(current)
+ current->setChecked(false);
+ current = action;
+ }
+ } else if (action == current) {
+ current = 0;
+ }
+ }
+}
+
+void QActionGroupPrivate::_q_actionTriggered()
+{
+ Q_Q(QActionGroup);
+ QAction *action = qobject_cast<QAction*>(q->sender());
+ Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionTriggered", "internal error");
+ emit q->triggered(action);
+ emit q->selected(action);
+}
+
+void QActionGroupPrivate::_q_actionHovered()
+{
+ Q_Q(QActionGroup);
+ QAction *action = qobject_cast<QAction*>(q->sender());
+ Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionHovered", "internal error");
+ emit q->hovered(action);
+}
+
+/*!
+ \class QActionGroup
+ \brief The QActionGroup class groups actions together.
+
+ \ingroup mainwindow-classes
+
+ In some situations it is useful to group actions together. For
+ example, if you have a \gui{Left Align} action, a \gui{Right
+ Align} action, a \gui{Justify} action, and a \gui{Center} action,
+ only one of these actions should be active at any one time. One
+ simple way of achieving this is to group the actions together in
+ an action group.
+
+ Here's a example (from the \l{mainwindows/menus}{Menus} example):
+
+ \snippet examples/mainwindows/menus/mainwindow.cpp 6
+
+ Here we create a new action group. Since the action group is
+ exclusive by default, only one of the actions in the group is
+ checked at any one time.
+
+ \img qactiongroup-align.png Alignment options in a QMenu
+
+ A QActionGroup emits an triggered() signal when one of its
+ actions is chosen. Each action in an action group emits its
+ triggered() signal as usual.
+
+ As stated above, an action group is \l exclusive by default; it
+ ensures that only one checkable action is active at any one time.
+ If you want to group checkable actions without making them
+ exclusive, you can turn of exclusiveness by calling
+ setExclusive(false).
+
+ Actions can be added to an action group using addAction(), but it
+ is usually more convenient to specify a group when creating
+ actions; this ensures that actions are automatically created with
+ a parent. Actions can be visually separated from each other by
+ adding a separator action to the group; create an action and use
+ QAction's \l {QAction::}{setSeparator()} function to make it
+ considered a separator. Action groups are added to widgets with
+ the QWidget::addActions() function.
+
+ \sa QAction
+*/
+
+/*!
+ Constructs an action group for the \a parent object.
+
+ The action group is exclusive by default. Call setExclusive(false)
+ to make the action group non-exclusive.
+*/
+QActionGroup::QActionGroup(QObject* parent) : QObject(*new QActionGroupPrivate, parent)
+{
+}
+
+/*!
+ Destroys the action group.
+*/
+QActionGroup::~QActionGroup()
+{
+}
+
+/*!
+ \fn QAction *QActionGroup::addAction(QAction *action)
+
+ Adds the \a action to this group, and returns it.
+
+ Normally an action is added to a group by creating it with the
+ group as its parent, so this function is not usually used.
+
+ \sa QAction::setActionGroup()
+*/
+QAction *QActionGroup::addAction(QAction* a)
+{
+ Q_D(QActionGroup);
+ if(!d->actions.contains(a)) {
+ d->actions.append(a);
+ QObject::connect(a, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
+ QObject::connect(a, SIGNAL(changed()), this, SLOT(_q_actionChanged()));
+ QObject::connect(a, SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
+ }
+ if(!a->d_func()->forceDisabled) {
+ a->setEnabled(d->enabled);
+ a->d_func()->forceDisabled = false;
+ }
+ if(!a->d_func()->forceInvisible) {
+ a->setVisible(d->visible);
+ a->d_func()->forceInvisible = false;
+ }
+ if(a->isChecked())
+ d->current = a;
+ QActionGroup *oldGroup = a->d_func()->group;
+ if(oldGroup != this) {
+ if (oldGroup)
+ oldGroup->removeAction(a);
+ a->d_func()->group = this;
+ }
+ return a;
+}
+
+/*!
+ Creates and returns an action with \a text. The newly created
+ action is a child of this action group.
+
+ Normally an action is added to a group by creating it with the
+ group as parent, so this function is not usually used.
+
+ \sa QAction::setActionGroup()
+*/
+QAction *QActionGroup::addAction(const QString &text)
+{
+ return new QAction(text, this);
+}
+
+/*!
+ Creates and returns an action with \a text and an \a icon. The
+ newly created action is a child of this action group.
+
+ Normally an action is added to a group by creating it with the
+ group as its parent, so this function is not usually used.
+
+ \sa QAction::setActionGroup()
+*/
+QAction *QActionGroup::addAction(const QIcon &icon, const QString &text)
+{
+ return new QAction(icon, text, this);
+}
+
+/*!
+ Removes the \a action from this group. The action will have no
+ parent as a result.
+
+ \sa QAction::setActionGroup()
+*/
+void QActionGroup::removeAction(QAction *action)
+{
+ Q_D(QActionGroup);
+ if (d->actions.removeAll(action)) {
+ if (action == d->current)
+ d->current = 0;
+ QObject::disconnect(action, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
+ QObject::disconnect(action, SIGNAL(changed()), this, SLOT(_q_actionChanged()));
+ QObject::disconnect(action, SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
+ action->d_func()->group = 0;
+ }
+}
+
+/*!
+ Returns the list of this groups's actions. This may be empty.
+*/
+QList<QAction*> QActionGroup::actions() const
+{
+ Q_D(const QActionGroup);
+ return d->actions;
+}
+
+/*!
+ \property QActionGroup::exclusive
+ \brief whether the action group does exclusive checking
+
+ If exclusive is true, only one checkable action in the action group
+ can ever be active at any time. If the user chooses another
+ checkable action in the group, the one they chose becomes active and
+ the one that was active becomes inactive.
+
+ \sa QAction::checkable
+*/
+void QActionGroup::setExclusive(bool b)
+{
+ Q_D(QActionGroup);
+ d->exclusive = b;
+}
+
+bool QActionGroup::isExclusive() const
+{
+ Q_D(const QActionGroup);
+ return d->exclusive;
+}
+
+/*!
+ \fn void QActionGroup::setDisabled(bool b)
+
+ This is a convenience function for the \l enabled property, that
+ is useful for signals--slots connections. If \a b is true the
+ action group is disabled; otherwise it is enabled.
+*/
+
+/*!
+ \property QActionGroup::enabled
+ \brief whether the action group is enabled
+
+ Each action in the group will be enabled or disabled unless it
+ has been explicitly disabled.
+
+ \sa QAction::setEnabled()
+*/
+void QActionGroup::setEnabled(bool b)
+{
+ Q_D(QActionGroup);
+ d->enabled = b;
+ for(QList<QAction*>::const_iterator it = d->actions.constBegin(); it != d->actions.constEnd(); ++it) {
+ if(!(*it)->d_func()->forceDisabled) {
+ (*it)->setEnabled(b);
+ (*it)->d_func()->forceDisabled = false;
+ }
+ }
+}
+
+bool QActionGroup::isEnabled() const
+{
+ Q_D(const QActionGroup);
+ return d->enabled;
+}
+
+/*!
+ Returns the currently checked action in the group, or 0 if none
+ are checked.
+*/
+QAction *QActionGroup::checkedAction() const
+{
+ Q_D(const QActionGroup);
+ return d->current;
+}
+
+/*!
+ \property QActionGroup::visible
+ \brief whether the action group is visible
+
+ Each action in the action group will match the visible state of
+ this group unless it has been explicitly hidden.
+
+ \sa QAction::setEnabled()
+*/
+void QActionGroup::setVisible(bool b)
+{
+ Q_D(QActionGroup);
+ d->visible = b;
+ for(QList<QAction*>::Iterator it = d->actions.begin(); it != d->actions.end(); ++it) {
+ if(!(*it)->d_func()->forceInvisible) {
+ (*it)->setVisible(b);
+ (*it)->d_func()->forceInvisible = false;
+ }
+ }
+}
+
+bool QActionGroup::isVisible() const
+{
+ Q_D(const QActionGroup);
+ return d->visible;
+}
+
+/*!
+ \fn void QActionGroup::triggered(QAction *action)
+
+ This signal is emitted when the given \a action in the action
+ group is activated by the user; for example, when the user clicks
+ a menu option, toolbar button, or presses an action's shortcut key
+ combination.
+
+ Connect to this signal for command actions.
+
+ \sa QAction::activate()
+*/
+
+/*!
+ \fn void QActionGroup::hovered(QAction *action)
+
+ This signal is emitted when the given \a action in the action
+ group is highlighted by the user; for example, when the user
+ pauses with the cursor over a menu option, toolbar button, or
+ presses an action's shortcut key combination.
+
+ \sa QAction::activate()
+*/
+
+/*!
+ \fn void QActionGroup::add(QAction* a)
+
+ Use addAction() instead.
+*/
+
+/*!
+ \fn void QActionGroup::addSeparator()
+
+ Normally you add a separator to the menus or widgets to which
+ actions are added, so this function is very rarely needed.
+
+ \oldcode
+ actionGroup->addSeparator();
+ \newcode
+ QAction *separator = new QAction(this);
+ separator->setSeparator(true);
+ actionGroup->addAction(separator);
+ \endcode
+*/
+
+/*!
+ \fn bool QActionGroup::addTo(QWidget *widget)
+
+ \oldcode
+ actionGroup->addTo(widget);
+ \newcode
+ widget->addActions(actionGroup->actions());
+ \endcode
+*/
+
+/*!
+ \fn void QActionGroup::selected(QAction *action);
+
+ Use triggered() instead.
+
+*/
+
+QT_END_NAMESPACE
+
+#include "moc_qactiongroup.cpp"
+
+#endif // QT_NO_ACTION
diff --git a/src/gui/kernel/qactiongroup.h b/src/gui/kernel/qactiongroup.h
new file mode 100644
index 0000000000..88f4fe8eac
--- /dev/null
+++ b/src/gui/kernel/qactiongroup.h
@@ -0,0 +1,112 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QACTIONGROUP_H
+#define QACTIONGROUP_H
+
+#include <QtGui/qaction.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Gui)
+
+#ifndef QT_NO_ACTION
+
+class QActionGroupPrivate;
+
+class Q_GUI_EXPORT QActionGroup : public QObject
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QActionGroup)
+
+ Q_PROPERTY(bool exclusive READ isExclusive WRITE setExclusive)
+ Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
+ Q_PROPERTY(bool visible READ isVisible WRITE setVisible)
+
+public:
+ explicit QActionGroup(QObject* parent);
+ ~QActionGroup();
+
+ QAction *addAction(QAction* a);
+ QAction *addAction(const QString &text);
+ QAction *addAction(const QIcon &icon, const QString &text);
+ void removeAction(QAction *a);
+ QList<QAction*> actions() const;
+
+ QAction *checkedAction() const;
+ bool isExclusive() const;
+ bool isEnabled() const;
+ bool isVisible() const;
+
+#ifdef QT3_SUPPORT
+ inline QT3_SUPPORT void add(QAction* a) { addAction(a); }
+ inline QT3_SUPPORT void addSeparator()
+ { QAction *act = new QAction(this); act->setSeparator(true); addAction(act); }
+ inline QT3_SUPPORT bool addTo(QWidget *w) { w->addActions(actions()); return true; }
+#endif
+
+public Q_SLOTS:
+ void setEnabled(bool);
+ inline void setDisabled(bool b) { setEnabled(!b); }
+ void setVisible(bool);
+ void setExclusive(bool);
+
+Q_SIGNALS:
+ void triggered(QAction *);
+ QT_MOC_COMPAT void selected(QAction *);
+ void hovered(QAction *);
+
+private:
+ Q_DISABLE_COPY(QActionGroup)
+ Q_PRIVATE_SLOT(d_func(), void _q_actionTriggered())
+ Q_PRIVATE_SLOT(d_func(), void _q_actionChanged())
+ Q_PRIVATE_SLOT(d_func(), void _q_actionHovered())
+};
+
+#endif // QT_NO_ACTION
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QACTIONGROUP_H
diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp
new file mode 100644
index 0000000000..4096bf378b
--- /dev/null
+++ b/src/gui/kernel/qapplication.cpp
@@ -0,0 +1,6139 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qplatformdefs.h"
+#include "qabstracteventdispatcher.h"
+#include "qaccessible.h"
+#include "qapplication.h"
+#include "qclipboard.h"
+#include "qcursor.h"
+#include "qdesktopwidget.h"
+#include "qdir.h"
+#include "qevent.h"
+#include "qfile.h"
+#include "qfileinfo.h"
+#include "qgraphicsscene.h"
+#include "qhash.h"
+#include "qset.h"
+#include "qlayout.h"
+#include "qsessionmanager.h"
+#include "qstyle.h"
+#include "qstylefactory.h"
+#include "qtextcodec.h"
+#include "qtranslator.h"
+#include "qvariant.h"
+#include "qwidget.h"
+#include "qdnd_p.h"
+#include "qcolormap.h"
+#include "qdebug.h"
+#include "private/qgraphicssystemfactory_p.h"
+#include "private/qgraphicssystem_p.h"
+#include "private/qstylesheetstyle_p.h"
+#include "private/qstyle_p.h"
+#include "qmessagebox.h"
+#include <QtGui/qgraphicsproxywidget.h>
+
+#ifdef QT_GRAPHICSSYSTEM_RUNTIME
+#include "private/qgraphicssystem_runtime_p.h"
+#endif
+
+#include "qinputcontext.h"
+#include "qkeymapper_p.h"
+
+#ifdef Q_WS_X11
+#include <private/qt_x11_p.h>
+#endif
+
+#if defined(Q_WS_X11) || defined(Q_OS_SYMBIAN)
+#include "qinputcontextfactory.h"
+#endif
+
+#include "qguiplatformplugin_p.h"
+
+#include <qthread.h>
+#include <private/qthread_p.h>
+
+#include <private/qfont_p.h>
+
+#include <stdlib.h>
+
+#if defined(Q_WS_X11) && !defined(QT_NO_EGL)
+#include <link.h>
+#endif
+
+#include "qapplication_p.h"
+#include "qevent_p.h"
+#include "qwidget_p.h"
+
+#include "qapplication.h"
+
+#include "qgesture.h"
+#include "private/qgesturemanager_p.h"
+
+#ifndef QT_NO_LIBRARY
+#include "qlibrary.h"
+#endif
+
+#ifdef Q_WS_WINCE
+#include "qdatetime.h"
+#include "qguifunctions_wince.h"
+extern bool qt_wince_is_smartphone(); //qguifunctions_wince.cpp
+extern bool qt_wince_is_mobile(); //qguifunctions_wince.cpp
+extern bool qt_wince_is_pocket_pc(); //qguifunctions_wince.cpp
+#endif
+
+#include "qdatetime.h"
+
+#ifdef QT_MAC_USE_COCOA
+#include <private/qt_cocoa_helpers_mac_p.h>
+#endif
+
+//#define ALIEN_DEBUG
+
+#if defined(Q_OS_SYMBIAN)
+#include "qt_s60_p.h"
+#endif
+
+static void initResources()
+{
+#if defined(Q_WS_WINCE)
+ Q_INIT_RESOURCE_EXTERN(qstyle_wince)
+ Q_INIT_RESOURCE(qstyle_wince);
+#elif defined(Q_OS_SYMBIAN)
+ Q_INIT_RESOURCE_EXTERN(qstyle_s60)
+ Q_INIT_RESOURCE(qstyle_s60);
+#else
+ Q_INIT_RESOURCE_EXTERN(qstyle)
+ Q_INIT_RESOURCE(qstyle);
+#endif
+ Q_INIT_RESOURCE_EXTERN(qmessagebox)
+ Q_INIT_RESOURCE(qmessagebox);
+#if !defined(QT_NO_PRINTDIALOG)
+ Q_INIT_RESOURCE_EXTERN(qprintdialog)
+ Q_INIT_RESOURCE(qprintdialog);
+#endif
+
+}
+
+QT_BEGIN_NAMESPACE
+
+Q_CORE_EXPORT void qt_call_post_routines();
+
+QApplication::Type qt_appType=QApplication::Tty;
+QApplicationPrivate *QApplicationPrivate::self = 0;
+
+QInputContext *QApplicationPrivate::inputContext = 0;
+
+bool QApplicationPrivate::quitOnLastWindowClosed = true;
+
+#ifdef Q_WS_WINCE
+int QApplicationPrivate::autoMaximizeThreshold = -1;
+bool QApplicationPrivate::autoSipEnabled = false;
+#else
+bool QApplicationPrivate::autoSipEnabled = true;
+#endif
+
+QApplicationPrivate::QApplicationPrivate(int &argc, char **argv, QApplication::Type type, int flags)
+ : QCoreApplicationPrivate(argc, argv, flags)
+{
+ application_type = type;
+ qt_appType = type;
+
+#ifndef QT_NO_SESSIONMANAGER
+ is_session_restored = false;
+#endif
+
+ quitOnLastWindowClosed = true;
+
+#ifdef QT3_SUPPORT
+ qt_compat_used = 0;
+ qt_compat_resolved = 0;
+ qt_tryAccelEvent = 0;
+ qt_tryComposeUnicode = 0;
+ qt_dispatchAccelEvent = 0;
+#endif
+#if defined(Q_WS_QWS) && !defined(QT_NO_DIRECTPAINTER)
+ directPainters = 0;
+#endif
+
+#ifndef QT_NO_GESTURES
+ gestureManager = 0;
+ gestureWidget = 0;
+#endif // QT_NO_GESTURES
+
+#if defined(Q_WS_X11) || defined(Q_WS_WIN)
+ move_cursor = 0;
+ copy_cursor = 0;
+ link_cursor = 0;
+#endif
+#if defined(Q_WS_WIN)
+ ignore_cursor = 0;
+#endif
+
+ if (!self)
+ self = this;
+}
+
+QApplicationPrivate::~QApplicationPrivate()
+{
+ if (self == this)
+ self = 0;
+}
+
+/*!
+ \class QApplication
+ \brief The QApplication class manages the GUI application's control
+ flow and main settings.
+
+ QApplication contains the main event loop, where all events from the window
+ system and other sources are processed and dispatched. It also handles the
+ application's initialization, finalization, and provides session
+ management. In addition, QApplication handles most of the system-wide and
+ application-wide settings.
+
+ For any GUI application using Qt, there is precisely \bold one QApplication
+ object, no matter whether the application has 0, 1, 2 or more windows at
+ any given time. For non-GUI Qt applications, use QCoreApplication instead,
+ as it does not depend on the \l QtGui library.
+
+ The QApplication object is accessible through the instance() function that
+ returns a pointer equivalent to the global qApp pointer.
+
+ QApplication's main areas of responsibility are:
+ \list
+ \o It initializes the application with the user's desktop settings
+ such as palette(), font() and doubleClickInterval(). It keeps
+ track of these properties in case the user changes the desktop
+ globally, for example through some kind of control panel.
+
+ \o It performs event handling, meaning that it receives events
+ from the underlying window system and dispatches them to the
+ relevant widgets. By using sendEvent() and postEvent() you can
+ send your own events to widgets.
+
+ \o It parses common command line arguments and sets its internal
+ state accordingly. See the \l{QApplication::QApplication()}
+ {constructor documentation} below for more details.
+
+ \o It defines the application's look and feel, which is
+ encapsulated in a QStyle object. This can be changed at runtime
+ with setStyle().
+
+ \o It specifies how the application is to allocate colors. See
+ setColorSpec() for details.
+
+ \o It provides localization of strings that are visible to the
+ user via translate().
+
+ \o It provides some magical objects like the desktop() and the
+ clipboard().
+
+ \o It knows about the application's windows. You can ask which
+ widget is at a certain position using widgetAt(), get a list of
+ topLevelWidgets() and closeAllWindows(), etc.
+
+ \o It manages the application's mouse cursor handling, see
+ setOverrideCursor()
+
+ \o On the X window system, it provides functions to flush and sync
+ the communication stream, see flushX() and syncX().
+
+ \o It provides support for sophisticated \l{Session Management}
+ {session management}. This makes it possible for applications
+ to terminate gracefully when the user logs out, to cancel a
+ shutdown process if termination isn't possible and even to
+ preserve the entire application's state for a future session.
+ See isSessionRestored(), sessionId() and commitData() and
+ saveState() for details.
+ \endlist
+
+ Since the QApplication object does so much initialization, it \e{must} be
+ created before any other objects related to the user interface are created.
+ QApplication also deals with common command line arguments. Hence, it is
+ usually a good idea to create it \e before any interpretation or
+ modification of \c argv is done in the application itself.
+
+ \table
+ \header
+ \o{2,1} Groups of functions
+
+ \row
+ \o System settings
+ \o desktopSettingsAware(),
+ setDesktopSettingsAware(),
+ cursorFlashTime(),
+ setCursorFlashTime(),
+ doubleClickInterval(),
+ setDoubleClickInterval(),
+ setKeyboardInputInterval(),
+ wheelScrollLines(),
+ setWheelScrollLines(),
+ palette(),
+ setPalette(),
+ font(),
+ setFont(),
+ fontMetrics().
+
+ \row
+ \o Event handling
+ \o exec(),
+ processEvents(),
+ exit(),
+ quit().
+ sendEvent(),
+ postEvent(),
+ sendPostedEvents(),
+ removePostedEvents(),
+ hasPendingEvents(),
+ notify(),
+ macEventFilter(),
+ qwsEventFilter(),
+ x11EventFilter(),
+ x11ProcessEvent(),
+ winEventFilter().
+
+ \row
+ \o GUI Styles
+ \o style(),
+ setStyle().
+
+ \row
+ \o Color usage
+ \o colorSpec(),
+ setColorSpec(),
+ qwsSetCustomColors().
+
+ \row
+ \o Text handling
+ \o installTranslator(),
+ removeTranslator()
+ translate().
+
+ \row
+ \o Widgets
+ \o allWidgets(),
+ topLevelWidgets(),
+ desktop(),
+ activePopupWidget(),
+ activeModalWidget(),
+ clipboard(),
+ focusWidget(),
+ activeWindow(),
+ widgetAt().
+
+ \row
+ \o Advanced cursor handling
+ \o overrideCursor(),
+ setOverrideCursor(),
+ restoreOverrideCursor().
+
+ \row
+ \o X Window System synchronization
+ \o flushX(),
+ syncX().
+
+ \row
+ \o Session management
+ \o isSessionRestored(),
+ sessionId(),
+ commitData(),
+ saveState().
+
+ \row
+ \o Miscellaneous
+ \o closeAllWindows(),
+ startingUp(),
+ closingDown(),
+ type().
+ \endtable
+
+ \sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
+*/
+
+/*!
+ \enum QApplication::Type
+
+ \value Tty a console application
+ \value GuiClient a GUI client application
+ \value GuiServer a GUI server application (for Qt for Embedded Linux)
+*/
+
+/*!
+ \enum QApplication::ColorSpec
+
+ \value NormalColor the default color allocation policy
+ \value CustomColor the same as NormalColor for X11; allocates colors
+ to a palette on demand under Windows
+ \value ManyColor the right choice for applications that use thousands of
+ colors
+
+ See setColorSpec() for full details.
+*/
+
+/*!
+ \fn QWidget *QApplication::topLevelAt(const QPoint &point)
+
+ Returns the top-level widget at the given \a point; returns 0 if
+ there is no such widget.
+*/
+
+/*!
+ \fn QWidget *QApplication::topLevelAt(int x, int y)
+
+ \overload
+
+ Returns the top-level widget at the point (\a{x}, \a{y}); returns
+ 0 if there is no such widget.
+*/
+
+
+/*
+ The qt_init() and qt_cleanup() functions are implemented in the
+ qapplication_xyz.cpp file.
+*/
+
+void qt_init(QApplicationPrivate *priv, int type
+#ifdef Q_WS_X11
+ , Display *display = 0, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0
+#endif
+ );
+void qt_cleanup();
+
+Qt::MouseButtons QApplicationPrivate::mouse_buttons = Qt::NoButton;
+Qt::KeyboardModifiers QApplicationPrivate::modifier_buttons = Qt::NoModifier;
+
+QStyle *QApplicationPrivate::app_style = 0; // default application style
+QString QApplicationPrivate::styleOverride; // style override
+
+#ifndef QT_NO_STYLE_STYLESHEET
+QString QApplicationPrivate::styleSheet; // default application stylesheet
+#endif
+QPointer<QWidget> QApplicationPrivate::leaveAfterRelease = 0;
+
+int QApplicationPrivate::app_cspec = QApplication::NormalColor;
+QPalette *QApplicationPrivate::app_pal = 0; // default application palette
+QPalette *QApplicationPrivate::sys_pal = 0; // default system palette
+QPalette *QApplicationPrivate::set_pal = 0; // default palette set by programmer
+
+QGraphicsSystem *QApplicationPrivate::graphics_system = 0; // default graphics system
+#if defined(Q_WS_QPA)
+QPlatformIntegration *QApplicationPrivate::platform_integration = 0;
+#endif
+QString QApplicationPrivate::graphics_system_name; // graphics system id - for delayed initialization
+bool QApplicationPrivate::runtime_graphics_system = false;
+
+Q_GLOBAL_STATIC(QMutex, applicationFontMutex)
+QFont *QApplicationPrivate::app_font = 0; // default application font
+QFont *QApplicationPrivate::sys_font = 0; // default system font
+QFont *QApplicationPrivate::set_font = 0; // default font set by programmer
+
+QIcon *QApplicationPrivate::app_icon = 0;
+QWidget *QApplicationPrivate::main_widget = 0; // main application widget
+QWidget *QApplicationPrivate::focus_widget = 0; // has keyboard input focus
+QWidget *QApplicationPrivate::hidden_focus_widget = 0; // will get keyboard input focus after show()
+QWidget *QApplicationPrivate::active_window = 0; // toplevel with keyboard focus
+bool QApplicationPrivate::obey_desktop_settings = true; // use winsys resources
+int QApplicationPrivate::cursor_flash_time = 1000; // text caret flash time
+int QApplicationPrivate::mouse_double_click_time = 400; // mouse dbl click limit
+int QApplicationPrivate::keyboard_input_time = 400; // keyboard input interval
+#ifndef QT_NO_WHEELEVENT
+int QApplicationPrivate::wheel_scroll_lines; // number of lines to scroll
+#endif
+bool qt_is_gui_used;
+bool Q_GUI_EXPORT qt_tab_all_widgets = true;
+bool qt_in_tab_key_event = false;
+int qt_antialiasing_threshold = -1;
+static int drag_time = 500;
+#ifndef QT_GUI_DRAG_DISTANCE
+#define QT_GUI_DRAG_DISTANCE 4
+#endif
+#ifdef Q_OS_SYMBIAN
+// The screens are a bit too small to for your thumb when using only 4 pixels drag distance.
+static int drag_distance = 12; //XXX move to qplatformdefs.h
+#else
+static int drag_distance = QT_GUI_DRAG_DISTANCE;
+#endif
+static Qt::LayoutDirection layout_direction = Qt::LeftToRight;
+QSize QApplicationPrivate::app_strut = QSize(0,0); // no default application strut
+bool QApplicationPrivate::animate_ui = true;
+bool QApplicationPrivate::animate_menu = false;
+bool QApplicationPrivate::fade_menu = false;
+bool QApplicationPrivate::animate_combo = false;
+bool QApplicationPrivate::animate_tooltip = false;
+bool QApplicationPrivate::fade_tooltip = false;
+bool QApplicationPrivate::animate_toolbox = false;
+bool QApplicationPrivate::widgetCount = false;
+bool QApplicationPrivate::load_testability = false;
+QString QApplicationPrivate::qmljs_debug_arguments;
+#ifdef QT_KEYPAD_NAVIGATION
+# ifdef Q_OS_SYMBIAN
+Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadDirectional;
+# else
+Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadTabOrder;
+# endif
+QWidget *QApplicationPrivate::oldEditFocus = 0;
+#endif
+
+bool qt_tabletChokeMouse = false;
+static bool force_reverse = false;
+
+inline bool QApplicationPrivate::isAlien(QWidget *widget)
+{
+ if (!widget)
+ return false;
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA)
+ return !widget->isWindow()
+# ifdef Q_BACKINGSTORE_SUBSURFACES
+ && !(widget->d_func()->maybeTopData() && widget->d_func()->maybeTopData()->windowSurface)
+# endif
+ ;
+#else
+ return !widget->internalWinId();
+#endif
+}
+
+// ######## move to QApplicationPrivate
+// Default application palettes and fonts (per widget type)
+Q_GLOBAL_STATIC(PaletteHash, app_palettes)
+PaletteHash *qt_app_palettes_hash()
+{
+ return app_palettes();
+}
+
+Q_GLOBAL_STATIC(FontHash, app_fonts)
+FontHash *qt_app_fonts_hash()
+{
+ return app_fonts();
+}
+
+QWidgetList *QApplicationPrivate::popupWidgets = 0; // has keyboard input focus
+
+QDesktopWidget *qt_desktopWidget = 0; // root window widgets
+#ifndef QT_NO_CLIPBOARD
+QClipboard *qt_clipboard = 0; // global clipboard object
+#endif
+QWidgetList * qt_modal_stack=0; // stack of modal widgets
+
+/*!
+ \internal
+*/
+void QApplicationPrivate::process_cmdline()
+{
+ // process platform-indep command line
+ if (!qt_is_gui_used || !argc)
+ return;
+
+ int i, j;
+
+ j = 1;
+ for (i=1; i<argc; i++) { // if you add anything here, modify QCoreApplication::arguments()
+ if (argv[i] && *argv[i] != '-') {
+ argv[j++] = argv[i];
+ continue;
+ }
+ QByteArray arg = argv[i];
+ arg = arg;
+ QString s;
+ if (arg == "-qdevel" || arg == "-qdebug") {
+ // obsolete argument
+ } else if (arg.indexOf("-qmljsdebugger=", 0) != -1) {
+ qmljs_debug_arguments = QString::fromLocal8Bit(arg.right(arg.length() - 15));
+ } else if (arg.indexOf("-style=", 0) != -1) {
+ s = QString::fromLocal8Bit(arg.right(arg.length() - 7).toLower());
+ } else if (arg == "-style" && i < argc-1) {
+ s = QString::fromLocal8Bit(argv[++i]).toLower();
+#ifndef QT_NO_SESSIONMANAGER
+ } else if (arg == "-session" && i < argc-1) {
+ ++i;
+ if (argv[i] && *argv[i]) {
+ session_id = QString::fromLatin1(argv[i]);
+ int p = session_id.indexOf(QLatin1Char('_'));
+ if (p >= 0) {
+ session_key = session_id.mid(p +1);
+ session_id = session_id.left(p);
+ }
+ is_session_restored = true;
+ }
+#endif
+#ifndef QT_NO_STYLE_STYLESHEET
+ } else if (arg == "-stylesheet" && i < argc -1) {
+ styleSheet = QLatin1String("file:///");
+ styleSheet.append(QString::fromLocal8Bit(argv[++i]));
+ } else if (arg.indexOf("-stylesheet=") != -1) {
+ styleSheet = QLatin1String("file:///");
+ styleSheet.append(QString::fromLocal8Bit(arg.right(arg.length() - 12)));
+#endif
+ } else if (qstrcmp(arg, "-reverse") == 0) {
+ force_reverse = true;
+ QApplication::setLayoutDirection(Qt::RightToLeft);
+ } else if (qstrcmp(arg, "-widgetcount") == 0) {
+ widgetCount = true;
+ } else if (qstrcmp(arg, "-testability") == 0) {
+ load_testability = true;
+ } else if (arg == "-graphicssystem" && i < argc-1) {
+ graphics_system_name = QString::fromLocal8Bit(argv[++i]);
+ } else {
+ argv[j++] = argv[i];
+ }
+ if (!s.isEmpty()) {
+ if (app_style) {
+ delete app_style;
+ app_style = 0;
+ }
+ styleOverride = s;
+ }
+ }
+
+ if(j < argc) {
+ argv[j] = 0;
+ argc = j;
+ }
+}
+
+/*!
+ Initializes the window system and constructs an application object with
+ \a argc command line arguments in \a argv.
+
+ \warning The data referred to by \a argc and \a argv must stay valid for
+ the entire lifetime of the QApplication object. In addition, \a argc must
+ be greater than zero and \a argv must contain at least one valid character
+ string.
+
+ The global \c qApp pointer refers to this application object. Only one
+ application object should be created.
+
+ This application object must be constructed before any \l{QPaintDevice}
+ {paint devices} (including widgets, pixmaps, bitmaps etc.).
+
+ \note \a argc and \a argv might be changed as Qt removes command line
+ arguments that it recognizes.
+
+ Qt debugging options (not available if Qt was compiled without the QT_DEBUG
+ flag defined):
+ \list
+ \o -nograb, tells Qt that it must never grab the mouse or the
+ keyboard.
+ \o -dograb (only under X11), running under a debugger can cause an
+ implicit -nograb, use -dograb to override.
+ \o -sync (only under X11), switches to synchronous mode for
+ debugging.
+ \endlist
+
+ See \l{Debugging Techniques} for a more detailed explanation.
+
+ All Qt programs automatically support the following command line options:
+ \list
+ \o -style= \e style, sets the application GUI style. Possible values
+ are \c motif, \c windows, and \c platinum. If you compiled Qt with
+ additional styles or have additional styles as plugins these will
+ be available to the \c -style command line option.
+ \o -style \e style, is the same as listed above.
+ \o -stylesheet= \e stylesheet, sets the application \l styleSheet. The
+ value must be a path to a file that contains the Style Sheet.
+ \note Relative URLs in the Style Sheet file are relative to the
+ Style Sheet file's path.
+ \o -stylesheet \e stylesheet, is the same as listed above.
+ \o -session= \e session, restores the application from an earlier
+ \l{Session Management}{session}.
+ \o -session \e session, is the same as listed above.
+ \o -widgetcount, prints debug message at the end about number of
+ widgets left undestroyed and maximum number of widgets existed at
+ the same time
+ \o -reverse, sets the application's layout direction to
+ Qt::RightToLeft
+ \o -graphicssystem, sets the backend to be used for on-screen widgets
+ and QPixmaps. Available options are \c{raster} and \c{opengl}.
+ \o -qmljsdebugger=, activates the QML/JS debugger with a specified port.
+ The value must be of format port:1234[,block], where block is optional
+ and will make the application wait until a debugger connects to it.
+ \endlist
+
+ The X11 version of Qt supports some traditional X11 command line options:
+ \list
+ \o -display \e display, sets the X display (default is $DISPLAY).
+ \o -geometry \e geometry, sets the client geometry of the first window
+ that is shown.
+ \o -fn or \c -font \e font, defines the application font. The font
+ should be specified using an X logical font description. Note that
+ this option is ignored when Qt is built with fontconfig support enabled.
+ \o -bg or \c -background \e color, sets the default background color
+ and an application palette (light and dark shades are calculated).
+ \o -fg or \c -foreground \e color, sets the default foreground color.
+ \o -btn or \c -button \e color, sets the default button color.
+ \o -name \e name, sets the application name.
+ \o -title \e title, sets the application title.
+ \o -visual \c TrueColor, forces the application to use a TrueColor
+ visual on an 8-bit display.
+ \o -ncols \e count, limits the number of colors allocated in the color
+ cube on an 8-bit display, if the application is using the
+ QApplication::ManyColor color specification. If \e count is 216
+ then a 6x6x6 color cube is used (i.e. 6 levels of red, 6 of green,
+ and 6 of blue); for other values, a cube approximately proportional
+ to a 2x3x1 cube is used.
+ \o -cmap, causes the application to install a private color map on an
+ 8-bit display.
+ \o -im, sets the input method server (equivalent to setting the
+ XMODIFIERS environment variable)
+ \o -inputstyle, defines how the input is inserted into the given
+ widget, e.g., \c onTheSpot makes the input appear directly in the
+ widget, while \c overTheSpot makes the input appear in a box
+ floating over the widget and is not inserted until the editing is
+ done.
+ \endlist
+
+ \section1 X11 Notes
+
+ If QApplication fails to open the X11 display, it will terminate
+ the process. This behavior is consistent with most X11
+ applications.
+
+ \sa arguments()
+*/
+
+QApplication::QApplication(int &argc, char **argv)
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, GuiClient, 0x040000))
+{ Q_D(QApplication); d->construct(); }
+
+QApplication::QApplication(int &argc, char **argv, int _internal)
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
+{ Q_D(QApplication); d->construct(); }
+
+
+/*!
+ Constructs an application object with \a argc command line arguments in
+ \a argv. If \a GUIenabled is true, a GUI application is constructed,
+ otherwise a non-GUI (console) application is created.
+
+ \warning The data referred to by \a argc and \a argv must stay valid for
+ the entire lifetime of the QApplication object. In addition, \a argc must
+ be greater than zero and \a argv must contain at least one valid character
+ string.
+
+ Set \a GUIenabled to false for programs without a graphical user interface
+ that should be able to run without a window system.
+
+ On X11, the window system is initialized if \a GUIenabled is true. If
+ \a GUIenabled is false, the application does not connect to the X server.
+ On Windows and Mac OS, currently the window system is always initialized,
+ regardless of the value of GUIenabled. This may change in future versions
+ of Qt.
+
+ The following example shows how to create an application that uses a
+ graphical interface when available.
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 0
+*/
+
+QApplication::QApplication(int &argc, char **argv, bool GUIenabled )
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, 0x040000))
+{ Q_D(QApplication); d->construct(); }
+
+QApplication::QApplication(int &argc, char **argv, bool GUIenabled , int _internal)
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, _internal))
+{ Q_D(QApplication); d->construct();}
+
+
+
+/*!
+ Constructs an application object with \a argc command line arguments in
+ \a argv.
+
+ \warning The data referred to by \a argc and \a argv must stay valid for
+ the entire lifetime of the QApplication object. In addition, \a argc must
+ be greater than zero and \a argv must contain at least one valid character
+ string.
+
+ With Qt for Embedded Linux, passing QApplication::GuiServer for \a type
+ makes this application the server (equivalent to running with the
+ \c -qws option).
+*/
+QApplication::QApplication(int &argc, char **argv, Type type)
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, type, 0x040000))
+{ Q_D(QApplication); d->construct(); }
+
+QApplication::QApplication(int &argc, char **argv, Type type , int _internal)
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, type, _internal))
+{ Q_D(QApplication); d->construct(); }
+
+#if defined(Q_WS_X11) && !defined(QT_NO_EGL)
+static int qt_matchLibraryName(dl_phdr_info *info, size_t, void *data)
+{
+ const char *name = static_cast<const char *>(data);
+ return strstr(info->dlpi_name, name) != 0;
+}
+#endif
+
+/*!
+ \internal
+*/
+void QApplicationPrivate::construct(
+#ifdef Q_WS_X11
+ Display *dpy, Qt::HANDLE visual, Qt::HANDLE cmap
+#endif
+ )
+{
+ initResources();
+
+ qt_is_gui_used = (qt_appType != QApplication::Tty);
+ process_cmdline();
+ // the environment variable has the lowest precedence of runtime graphicssystem switches
+ if (graphics_system_name.isEmpty())
+ graphics_system_name = QString::fromLocal8Bit(qgetenv("QT_GRAPHICSSYSTEM"));
+
+#if defined(Q_WS_X11) && !defined(QT_NO_EGL)
+ if (graphics_system_name.isEmpty()) {
+ bool linksWithMeeGoTouch = dl_iterate_phdr(qt_matchLibraryName, const_cast<char *>("libmeegotouchcore"));
+ bool linksWithMeeGoGraphicsSystemHelper = dl_iterate_phdr(qt_matchLibraryName, const_cast<char *>("libQtMeeGoGraphicsSystemHelper"));
+
+ if (linksWithMeeGoTouch && !linksWithMeeGoGraphicsSystemHelper) {
+ qWarning("Running non-meego graphics system enabled MeeGo touch, forcing native graphicssystem\n");
+ graphics_system_name = QLatin1String("native");
+ }
+ }
+#endif
+
+ // Must be called before initialize()
+ qt_init(this, qt_appType
+#ifdef Q_WS_X11
+ , dpy, visual, cmap
+#endif
+ );
+ initialize();
+ eventDispatcher->startingUp();
+
+#ifdef QT_EVAL
+ extern void qt_gui_eval_init(uint);
+ qt_gui_eval_init(application_type);
+#endif
+
+#if defined(Q_OS_SYMBIAN) && !defined(QT_NO_SYSTEMLOCALE)
+ symbianInit();
+#endif
+
+#ifndef QT_NO_LIBRARY
+ if(load_testability) {
+ QLibrary testLib(QLatin1String("qttestability"));
+ if (testLib.load()) {
+ typedef void (*TasInitialize)(void);
+ TasInitialize initFunction = (TasInitialize)testLib.resolve("qt_testability_init");
+#ifdef Q_OS_SYMBIAN
+ // resolving method by name does not work on Symbian OS so need to use ordinal
+ if(!initFunction) {
+ initFunction = (TasInitialize)testLib.resolve("1");
+ }
+#endif
+ if (initFunction) {
+ initFunction();
+ } else {
+ qCritical("Library qttestability resolve failed!");
+ }
+ } else {
+ qCritical("Library qttestability load failed!");
+ }
+ }
+
+ //make sure the plugin is loaded
+ if (qt_is_gui_used)
+ qt_guiPlatformPlugin();
+#endif
+}
+
+#if defined(Q_WS_X11)
+// ### a string literal is a cont char*
+// ### using it as a char* is wrong and could lead to segfaults
+// ### if aargv is modified someday
+// ########## make it work with argc == argv == 0
+static int aargc = 1;
+static char *aargv[] = { (char*)"unknown", 0 };
+
+/*!
+ \fn QApplication::QApplication(Display* display, Qt::HANDLE visual, Qt::HANDLE colormap)
+
+ Creates an application, given an already open display \a display. If
+ \a visual and \a colormap are non-zero, the application will use those
+ values as the default Visual and Colormap contexts.
+
+ \warning Qt only supports TrueColor visuals at depths higher than 8
+ bits-per-pixel.
+
+ This function is only available on X11.
+*/
+QApplication::QApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE colormap)
+ : QCoreApplication(*new QApplicationPrivate(aargc, aargv, GuiClient, 0x040000))
+{
+ if (! dpy)
+ qWarning("QApplication: Invalid Display* argument");
+ Q_D(QApplication);
+ d->construct(dpy, visual, colormap);
+}
+
+QApplication::QApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE colormap, int _internal)
+ : QCoreApplication(*new QApplicationPrivate(aargc, aargv, GuiClient, _internal))
+{
+ if (! dpy)
+ qWarning("QApplication: Invalid Display* argument");
+ Q_D(QApplication);
+ d->construct(dpy, visual, colormap);
+ QApplicationPrivate::app_compile_version = _internal;
+}
+
+/*!
+ \fn QApplication::QApplication(Display *display, int &argc, char **argv,
+ Qt::HANDLE visual, Qt::HANDLE colormap)
+
+ Creates an application, given an already open \a display and using \a argc
+ command line arguments in \a argv. If \a visual and \a colormap are
+ non-zero, the application will use those values as the default Visual
+ and Colormap contexts.
+
+ \warning Qt only supports TrueColor visuals at depths higher than 8
+ bits-per-pixel.
+
+ This function is only available on X11.
+*/
+QApplication::QApplication(Display *dpy, int &argc, char **argv,
+ Qt::HANDLE visual, Qt::HANDLE colormap)
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, GuiClient, 0x040000))
+{
+ if (! dpy)
+ qWarning("QApplication: Invalid Display* argument");
+ Q_D(QApplication);
+ d->construct(dpy, visual, colormap);
+}
+
+QApplication::QApplication(Display *dpy, int &argc, char **argv,
+ Qt::HANDLE visual, Qt::HANDLE colormap, int _internal)
+ : QCoreApplication(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
+{
+ if (! dpy)
+ qWarning("QApplication: Invalid Display* argument");
+ Q_D(QApplication);
+ d->construct(dpy, visual, colormap);
+ QApplicationPrivate::app_compile_version = _internal;
+}
+
+#endif // Q_WS_X11
+
+extern void qInitDrawhelperAsm();
+extern void qInitImageConversions();
+extern int qRegisterGuiVariant();
+extern int qUnregisterGuiVariant();
+#ifndef QT_NO_STATEMACHINE
+extern int qRegisterGuiStateMachine();
+extern int qUnregisterGuiStateMachine();
+#endif
+
+/*!
+ \fn void QApplicationPrivate::initialize()
+
+ Initializes the QApplication object, called from the constructors.
+*/
+void QApplicationPrivate::initialize()
+{
+ QWidgetPrivate::mapper = new QWidgetMapper;
+ QWidgetPrivate::allWidgets = new QWidgetSet;
+
+#if !defined(Q_WS_X11) && !defined(Q_WS_QWS) && !defined(Q_WS_QPA)
+ // initialize the graphics system - on X11 this is initialized inside
+ // qt_init() in qapplication_x11.cpp because of several reasons.
+ // On QWS, the graphics system is set by the QScreen plugin.
+ // We don't use graphics systems in Qt QPA
+ graphics_system = QGraphicsSystemFactory::create(graphics_system_name);
+#endif
+
+ if (qt_appType != QApplication::Tty)
+ (void) QApplication::style(); // trigger creation of application style
+ // trigger registering of QVariant's GUI types
+ qRegisterGuiVariant();
+#ifndef QT_NO_STATEMACHINE
+ // trigger registering of QStateMachine's GUI types
+ qRegisterGuiStateMachine();
+#endif
+
+ is_app_running = true; // no longer starting up
+
+ Q_Q(QApplication);
+#ifndef QT_NO_SESSIONMANAGER
+ // connect to the session manager
+ session_manager = new QSessionManager(q, session_id, session_key);
+#endif
+
+ if (qgetenv("QT_USE_NATIVE_WINDOWS").toInt() > 0)
+ q->setAttribute(Qt::AA_NativeWindows);
+
+#ifdef Q_WS_WINCE
+#ifdef QT_AUTO_MAXIMIZE_THRESHOLD
+ autoMaximizeThreshold = QT_AUTO_MAXIMIZE_THRESHOLD;
+#else
+ if (qt_wince_is_mobile())
+ autoMaximizeThreshold = 50;
+ else
+ autoMaximizeThreshold = -1;
+#endif //QT_AUTO_MAXIMIZE_THRESHOLD
+#endif //Q_WS_WINCE
+
+ // Set up which span functions should be used in raster engine...
+ qInitDrawhelperAsm();
+ // and QImage conversion functions
+ qInitImageConversions();
+
+#ifndef QT_NO_WHEELEVENT
+ QApplicationPrivate::wheel_scroll_lines = 3;
+#endif
+
+ if (qt_is_gui_used)
+ initializeMultitouch();
+}
+
+/*!
+ Returns the type of application (\l Tty, GuiClient, or
+ GuiServer). The type is set when constructing the QApplication
+ object.
+*/
+QApplication::Type QApplication::type()
+{
+ return qt_appType;
+}
+
+/*****************************************************************************
+ Functions returning the active popup and modal widgets.
+ *****************************************************************************/
+
+/*!
+ Returns the active popup widget.
+
+ A popup widget is a special top-level widget that sets the \c
+ Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application
+ opens a popup widget, all events are sent to the popup. Normal widgets and
+ modal widgets cannot be accessed before the popup widget is closed.
+
+ Only other popup widgets may be opened when a popup widget is shown. The
+ popup widgets are organized in a stack. This function returns the active
+ popup widget at the top of the stack.
+
+ \sa activeModalWidget(), topLevelWidgets()
+*/
+
+QWidget *QApplication::activePopupWidget()
+{
+ return QApplicationPrivate::popupWidgets && !QApplicationPrivate::popupWidgets->isEmpty() ?
+ QApplicationPrivate::popupWidgets->last() : 0;
+}
+
+
+/*!
+ Returns the active modal widget.
+
+ A modal widget is a special top-level widget which is a subclass of QDialog
+ that specifies the modal parameter of the constructor as true. A modal
+ widget must be closed before the user can continue with other parts of the
+ program.
+
+ Modal widgets are organized in a stack. This function returns the active
+ modal widget at the top of the stack.
+
+ \sa activePopupWidget(), topLevelWidgets()
+*/
+
+QWidget *QApplication::activeModalWidget()
+{
+ return qt_modal_stack && !qt_modal_stack->isEmpty() ? qt_modal_stack->first() : 0;
+}
+
+/*!
+ Cleans up any window system resources that were allocated by this
+ application. Sets the global variable \c qApp to 0.
+*/
+
+QApplication::~QApplication()
+{
+ Q_D(QApplication);
+
+#ifndef QT_NO_CLIPBOARD
+ // flush clipboard contents
+ if (qt_clipboard) {
+ QEvent event(QEvent::Clipboard);
+ QApplication::sendEvent(qt_clipboard, &event);
+ }
+#endif
+
+ //### this should probable be done even later
+ qt_call_post_routines();
+
+ // kill timers before closing down the dispatcher
+ d->toolTipWakeUp.stop();
+ d->toolTipFallAsleep.stop();
+
+ d->eventDispatcher->closingDown();
+ d->eventDispatcher = 0;
+ QApplicationPrivate::is_app_closing = true;
+ QApplicationPrivate::is_app_running = false;
+
+ delete QWidgetPrivate::mapper;
+ QWidgetPrivate::mapper = 0;
+
+ // delete all widgets
+ if (QWidgetPrivate::allWidgets) {
+ QWidgetSet *mySet = QWidgetPrivate::allWidgets;
+ QWidgetPrivate::allWidgets = 0;
+ for (QWidgetSet::ConstIterator it = mySet->constBegin(); it != mySet->constEnd(); ++it) {
+ register QWidget *w = *it;
+ if (!w->parent()) // window
+ w->destroy(true, true);
+ }
+ delete mySet;
+ }
+
+ delete qt_desktopWidget;
+ qt_desktopWidget = 0;
+
+#ifndef QT_NO_CLIPBOARD
+ delete qt_clipboard;
+ qt_clipboard = 0;
+#endif
+
+#if defined(Q_WS_X11) || defined(Q_WS_WIN)
+ delete d->move_cursor; d->move_cursor = 0;
+ delete d->copy_cursor; d->copy_cursor = 0;
+ delete d->link_cursor; d->link_cursor = 0;
+#endif
+#if defined(Q_WS_WIN)
+ delete d->ignore_cursor; d->ignore_cursor = 0;
+#endif
+
+ delete QApplicationPrivate::app_pal;
+ QApplicationPrivate::app_pal = 0;
+ delete QApplicationPrivate::sys_pal;
+ QApplicationPrivate::sys_pal = 0;
+ delete QApplicationPrivate::set_pal;
+ QApplicationPrivate::set_pal = 0;
+ app_palettes()->clear();
+
+ {
+ QMutexLocker locker(applicationFontMutex());
+ delete QApplicationPrivate::app_font;
+ QApplicationPrivate::app_font = 0;
+ }
+ delete QApplicationPrivate::sys_font;
+ QApplicationPrivate::sys_font = 0;
+ delete QApplicationPrivate::set_font;
+ QApplicationPrivate::set_font = 0;
+ app_fonts()->clear();
+
+ delete QApplicationPrivate::app_style;
+ QApplicationPrivate::app_style = 0;
+ delete QApplicationPrivate::app_icon;
+ QApplicationPrivate::app_icon = 0;
+ delete QApplicationPrivate::graphics_system;
+ QApplicationPrivate::graphics_system = 0;
+#ifndef QT_NO_CURSOR
+ d->cursor_list.clear();
+#endif
+
+#ifndef QT_NO_DRAGANDDROP
+ if (qt_is_gui_used)
+ delete QDragManager::self();
+#endif
+
+ d->cleanupMultitouch();
+
+ qt_cleanup();
+
+ if (QApplicationPrivate::widgetCount)
+ qDebug("Widgets left: %i Max widgets: %i \n", QWidgetPrivate::instanceCounter, QWidgetPrivate::maxInstances);
+#ifndef QT_NO_SESSIONMANAGER
+ delete d->session_manager;
+ d->session_manager = 0;
+#endif //QT_NO_SESSIONMANAGER
+
+ QApplicationPrivate::obey_desktop_settings = true;
+ QApplicationPrivate::cursor_flash_time = 1000;
+ QApplicationPrivate::mouse_double_click_time = 400;
+ QApplicationPrivate::keyboard_input_time = 400;
+
+ drag_time = 500;
+ drag_distance = 4;
+ layout_direction = Qt::LeftToRight;
+ QApplicationPrivate::app_strut = QSize(0, 0);
+ QApplicationPrivate::animate_ui = true;
+ QApplicationPrivate::animate_menu = false;
+ QApplicationPrivate::fade_menu = false;
+ QApplicationPrivate::animate_combo = false;
+ QApplicationPrivate::animate_tooltip = false;
+ QApplicationPrivate::fade_tooltip = false;
+ QApplicationPrivate::widgetCount = false;
+
+#ifndef QT_NO_STATEMACHINE
+ // trigger unregistering of QStateMachine's GUI types
+ qUnregisterGuiStateMachine();
+#endif
+ // trigger unregistering of QVariant's GUI types
+ qUnregisterGuiVariant();
+}
+
+
+/*!
+ \fn QWidget *QApplication::widgetAt(const QPoint &point)
+
+ Returns the widget at global screen position \a point, or 0 if there is no
+ Qt widget there.
+
+ This function can be slow.
+
+ \sa QCursor::pos(), QWidget::grabMouse(), QWidget::grabKeyboard()
+*/
+QWidget *QApplication::widgetAt(const QPoint &p)
+{
+ QWidget *window = QApplication::topLevelAt(p);
+ if (!window)
+ return 0;
+
+ QWidget *child = 0;
+
+ if (!window->testAttribute(Qt::WA_TransparentForMouseEvents))
+ child = window->childAt(window->mapFromGlobal(p));
+
+ if (child)
+ return child;
+
+ if (window->testAttribute(Qt::WA_TransparentForMouseEvents)) {
+ //shoot a hole in the widget and try once again,
+ //suboptimal on Qt for Embedded Linux where we do
+ //know the stacking order of the toplevels.
+ int x = p.x();
+ int y = p.y();
+ QRegion oldmask = window->mask();
+ QPoint wpoint = window->mapFromGlobal(QPoint(x, y));
+ QRegion newmask = (oldmask.isEmpty() ? QRegion(window->rect()) : oldmask)
+ - QRegion(wpoint.x(), wpoint.y(), 1, 1);
+ window->setMask(newmask);
+ QWidget *recurse = 0;
+ if (QApplication::topLevelAt(p) != window) // verify recursion will terminate
+ recurse = widgetAt(x, y);
+ if (oldmask.isEmpty())
+ window->clearMask();
+ else
+ window->setMask(oldmask);
+ return recurse;
+ }
+ return window;
+}
+
+/*!
+ \fn QWidget *QApplication::widgetAt(int x, int y)
+
+ \overload
+
+ Returns the widget at global screen position (\a x, \a y), or 0 if there is
+ no Qt widget there.
+*/
+
+/*!
+ \fn void QApplication::setArgs(int argc, char **argv)
+ \internal
+*/
+
+
+
+/*!
+ \internal
+*/
+bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
+{
+ if ((event->type() == QEvent::UpdateRequest
+#ifdef QT3_SUPPORT
+ || event->type() == QEvent::LayoutHint
+#endif
+ || event->type() == QEvent::LayoutRequest
+ || event->type() == QEvent::Resize
+ || event->type() == QEvent::Move
+ || event->type() == QEvent::LanguageChange
+ || event->type() == QEvent::UpdateSoftKeys
+ || event->type() == QEvent::InputMethod)) {
+ for (int i = 0; i < postedEvents->size(); ++i) {
+ const QPostEvent &cur = postedEvents->at(i);
+ if (cur.receiver != receiver || cur.event == 0 || cur.event->type() != event->type())
+ continue;
+ if (cur.event->type() == QEvent::LayoutRequest
+#ifdef QT3_SUPPORT
+ || cur.event->type() == QEvent::LayoutHint
+#endif
+ || cur.event->type() == QEvent::UpdateRequest) {
+ ;
+ } else if (cur.event->type() == QEvent::Resize) {
+ ((QResizeEvent *)(cur.event))->s = ((QResizeEvent *)event)->s;
+ } else if (cur.event->type() == QEvent::Move) {
+ ((QMoveEvent *)(cur.event))->p = ((QMoveEvent *)event)->p;
+ } else if (cur.event->type() == QEvent::LanguageChange) {
+ ;
+ } else if (cur.event->type() == QEvent::UpdateSoftKeys) {
+ ;
+ } else if ( cur.event->type() == QEvent::InputMethod ) {
+ *(QInputMethodEvent *)(cur.event) = *(QInputMethodEvent *)event;
+ } else {
+ continue;
+ }
+ delete event;
+ return true;
+ }
+ return false;
+ }
+ return QCoreApplication::compressEvent(event, receiver, postedEvents);
+}
+
+/*!
+ \property QApplication::styleSheet
+ \brief the application style sheet
+ \since 4.2
+
+ By default, this property returns an empty string unless the user specifies
+ the \c{-stylesheet} option on the command line when running the application.
+
+ \sa QWidget::setStyle(), {Qt Style Sheets}
+*/
+
+/*!
+ \property QApplication::autoMaximizeThreshold
+ \since 4.4
+ \brief defines a threshold for auto maximizing widgets
+
+ \bold{The auto maximize threshold is only available as part of Qt for
+ Windows CE.}
+
+ This property defines a threshold for the size of a window as a percentage
+ of the screen size. If the minimum size hint of a window exceeds the
+ threshold, calling show() will cause the window to be maximized
+ automatically.
+
+ Setting the threshold to 100 or greater means that the widget will always
+ be maximized. Alternatively, setting the threshold to 50 means that the
+ widget will be maximized only if the vertical minimum size hint is at least
+ 50% of the vertical screen size.
+
+ Setting the threshold to -1 disables the feature.
+
+ On Windows CE the default is -1 (i.e., it is disabled).
+ On Windows Mobile the default is 40.
+*/
+
+/*!
+ \property QApplication::autoSipEnabled
+ \since 4.5
+ \brief toggles automatic SIP (software input panel) visibility
+
+ Set this property to \c true to automatically display the SIP when entering
+ widgets that accept keyboard input. This property only affects widgets with
+ the WA_InputMethodEnabled attribute set, and is typically used to launch
+ a virtual keyboard on devices which have very few or no keys.
+
+ \bold{ The property only has an effect on platforms which use software input
+ panels, such as Windows CE and Symbian.}
+
+ The default is platform dependent.
+*/
+
+#ifdef Q_WS_WINCE
+void QApplication::setAutoMaximizeThreshold(const int threshold)
+{
+ QApplicationPrivate::autoMaximizeThreshold = threshold;
+}
+
+int QApplication::autoMaximizeThreshold() const
+{
+ return QApplicationPrivate::autoMaximizeThreshold;
+}
+#endif
+
+void QApplication::setAutoSipEnabled(const bool enabled)
+{
+ QApplicationPrivate::autoSipEnabled = enabled;
+}
+
+bool QApplication::autoSipEnabled() const
+{
+ return QApplicationPrivate::autoSipEnabled;
+}
+
+#ifndef QT_NO_STYLE_STYLESHEET
+
+QString QApplication::styleSheet() const
+{
+ return QApplicationPrivate::styleSheet;
+}
+
+void QApplication::setStyleSheet(const QString& styleSheet)
+{
+ QApplicationPrivate::styleSheet = styleSheet;
+ QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle*>(QApplicationPrivate::app_style);
+ if (styleSheet.isEmpty()) { // application style sheet removed
+ if (!proxy)
+ return; // there was no stylesheet before
+ setStyle(proxy->base);
+ } else if (proxy) { // style sheet update, just repolish
+ proxy->repolish(qApp);
+ } else { // stylesheet set the first time
+ QStyleSheetStyle *newProxy = new QStyleSheetStyle(QApplicationPrivate::app_style);
+ QApplicationPrivate::app_style->setParent(newProxy);
+ setStyle(newProxy);
+ }
+}
+
+#endif // QT_NO_STYLE_STYLESHEET
+
+/*!
+ Returns the application's style object.
+
+ \sa setStyle(), QStyle
+*/
+QStyle *QApplication::style()
+{
+ if (QApplicationPrivate::app_style)
+ return QApplicationPrivate::app_style;
+ if (!qt_is_gui_used) {
+ Q_ASSERT(!"No style available in non-gui applications!");
+ return 0;
+ }
+
+ if (!QApplicationPrivate::app_style) {
+ // Compile-time search for default style
+ //
+ QString style;
+#ifdef QT_BUILD_INTERNAL
+ QString envStyle = QString::fromLocal8Bit(qgetenv("QT_STYLE_OVERRIDE"));
+#else
+ QString envStyle;
+#endif
+ if (!QApplicationPrivate::styleOverride.isEmpty()) {
+ style = QApplicationPrivate::styleOverride;
+ } else if (!envStyle.isEmpty()) {
+ style = envStyle;
+ } else {
+ style = QApplicationPrivate::desktopStyleKey();
+ }
+
+ QStyle *&app_style = QApplicationPrivate::app_style;
+ app_style = QStyleFactory::create(style);
+ if (!app_style) {
+ QStringList styles = QStyleFactory::keys();
+ for (int i = 0; i < styles.size(); ++i) {
+ if ((app_style = QStyleFactory::create(styles.at(i))))
+ break;
+ }
+ }
+ if (!app_style) {
+ Q_ASSERT(!"No styles available!");
+ return 0;
+ }
+ }
+ // take ownership of the style
+ QApplicationPrivate::app_style->setParent(qApp);
+
+ if (!QApplicationPrivate::sys_pal)
+ QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
+ if (QApplicationPrivate::set_pal) // repolish set palette with the new style
+ QApplication::setPalette(*QApplicationPrivate::set_pal);
+
+#ifndef QT_NO_STYLE_STYLESHEET
+ if (!QApplicationPrivate::styleSheet.isEmpty()) {
+ qApp->setStyleSheet(QApplicationPrivate::styleSheet);
+ } else
+#endif
+ QApplicationPrivate::app_style->polish(qApp);
+
+ return QApplicationPrivate::app_style;
+}
+
+/*!
+ Sets the application's GUI style to \a style. Ownership of the style object
+ is transferred to QApplication, so QApplication will delete the style
+ object on application exit or when a new style is set and the old style is
+ still the parent of the application object.
+
+ Example usage:
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 1
+
+ When switching application styles, the color palette is set back to the
+ initial colors or the system defaults. This is necessary since certain
+ styles have to adapt the color palette to be fully style-guide compliant.
+
+ Setting the style before a palette has been se, i.e., before creating
+ QApplication, will cause the application to use QStyle::standardPalette()
+ for the palette.
+
+ \warning Qt style sheets are currently not supported for custom QStyle
+ subclasses. We plan to address this in some future release.
+
+ \sa style(), QStyle, setPalette(), desktopSettingsAware()
+*/
+void QApplication::setStyle(QStyle *style)
+{
+ if (!style || style == QApplicationPrivate::app_style)
+ return;
+
+ QWidgetList all = allWidgets();
+
+ // clean up the old style
+ if (QApplicationPrivate::app_style) {
+ if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
+ for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
+ register QWidget *w = *it;
+ if (!(w->windowType() == Qt::Desktop) && // except desktop
+ w->testAttribute(Qt::WA_WState_Polished)) { // has been polished
+ QApplicationPrivate::app_style->unpolish(w);
+ }
+ }
+ }
+ QApplicationPrivate::app_style->unpolish(qApp);
+ }
+
+ QStyle *old = QApplicationPrivate::app_style; // save
+
+#ifndef QT_NO_STYLE_STYLESHEET
+ if (!QApplicationPrivate::styleSheet.isEmpty() && !qobject_cast<QStyleSheetStyle *>(style)) {
+ // we have a stylesheet already and a new style is being set
+ QStyleSheetStyle *newProxy = new QStyleSheetStyle(style);
+ style->setParent(newProxy);
+ QApplicationPrivate::app_style = newProxy;
+ } else
+#endif // QT_NO_STYLE_STYLESHEET
+ QApplicationPrivate::app_style = style;
+ QApplicationPrivate::app_style->setParent(qApp); // take ownership
+
+ // take care of possible palette requirements of certain gui
+ // styles. Do it before polishing the application since the style
+ // might call QApplication::setPalette() itself
+ if (QApplicationPrivate::set_pal) {
+ QApplication::setPalette(*QApplicationPrivate::set_pal);
+ } else if (QApplicationPrivate::sys_pal) {
+ QApplicationPrivate::initializeWidgetPaletteHash();
+ QApplicationPrivate::setPalette_helper(*QApplicationPrivate::sys_pal, /*className=*/0, /*clearWidgetPaletteHash=*/false);
+ } else if (!QApplicationPrivate::sys_pal) {
+ // Initialize the sys_pal if it hasn't happened yet...
+ QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
+ }
+
+ // initialize the application with the new style
+ QApplicationPrivate::app_style->polish(qApp);
+
+ // re-polish existing widgets if necessary
+ if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
+ for (QWidgetList::ConstIterator it1 = all.constBegin(); it1 != all.constEnd(); ++it1) {
+ register QWidget *w = *it1;
+ if (w->windowType() != Qt::Desktop && w->testAttribute(Qt::WA_WState_Polished)) {
+ if (w->style() == QApplicationPrivate::app_style)
+ QApplicationPrivate::app_style->polish(w); // repolish
+#ifndef QT_NO_STYLE_STYLESHEET
+ else
+ w->setStyleSheet(w->styleSheet()); // touch
+#endif
+ }
+ }
+
+ for (QWidgetList::ConstIterator it2 = all.constBegin(); it2 != all.constEnd(); ++it2) {
+ register QWidget *w = *it2;
+ if (w->windowType() != Qt::Desktop && !w->testAttribute(Qt::WA_SetStyle)) {
+ QEvent e(QEvent::StyleChange);
+ QApplication::sendEvent(w, &e);
+#ifdef QT3_SUPPORT
+ if (old)
+ w->styleChange(*old);
+#endif
+ w->update();
+ }
+ }
+ }
+
+#ifndef QT_NO_STYLE_STYLESHEET
+ if (QStyleSheetStyle *oldProxy = qobject_cast<QStyleSheetStyle *>(old)) {
+ oldProxy->deref();
+ } else
+#endif
+ if (old && old->parent() == qApp) {
+ delete old;
+ }
+
+ if (QApplicationPrivate::focus_widget) {
+ QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
+ QApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
+ QApplicationPrivate::focus_widget->update();
+ }
+}
+
+/*!
+ \overload
+
+ Requests a QStyle object for \a style from the QStyleFactory.
+
+ The string must be one of the QStyleFactory::keys(), typically one of
+ "windows", "motif", "cde", "plastique", "windowsxp", or "macintosh". Style
+ names are case insensitive.
+
+ Returns 0 if an unknown \a style is passed, otherwise the QStyle object
+ returned is set as the application's GUI style.
+
+ \warning To ensure that the application's style is set correctly, it is
+ best to call this function before the QApplication constructor, if
+ possible.
+*/
+QStyle* QApplication::setStyle(const QString& style)
+{
+ QStyle *s = QStyleFactory::create(style);
+ if (!s)
+ return 0;
+
+ setStyle(s);
+ return s;
+}
+
+/*!
+ \since 4.5
+
+ Sets the default graphics backend to \a system, which will be used for
+ on-screen widgets and QPixmaps. The available systems are \c{"native"},
+ \c{"raster"} and \c{"opengl"}.
+
+ There are several ways to set the graphics backend, in order of decreasing
+ precedence:
+ \list
+ \o the application commandline \c{-graphicssystem} switch
+ \o QApplication::setGraphicsSystem()
+ \o the QT_GRAPHICSSYSTEM environment variable
+ \o the Qt configure \c{-graphicssystem} switch
+ \endlist
+ If the highest precedence switch sets an invalid name, the error will be
+ ignored and the default backend will be used.
+
+ \warning This function is only effective before the QApplication constructor
+ is called.
+
+ \note The \c{"opengl"} option is currently experimental.
+*/
+
+void QApplication::setGraphicsSystem(const QString &system)
+{
+#ifdef Q_WS_QPA
+ Q_UNUSED(system);
+#else
+# ifdef QT_GRAPHICSSYSTEM_RUNTIME
+ if (QApplicationPrivate::graphics_system_name == QLatin1String("runtime")) {
+ QRuntimeGraphicsSystem *r =
+ static_cast<QRuntimeGraphicsSystem *>(QApplicationPrivate::graphics_system);
+ r->setGraphicsSystem(system);
+ } else
+# endif
+ QApplicationPrivate::graphics_system_name = system;
+#endif
+}
+
+/*!
+ Returns the color specification.
+
+ \sa QApplication::setColorSpec()
+*/
+
+int QApplication::colorSpec()
+{
+ return QApplicationPrivate::app_cspec;
+}
+
+/*!
+ Sets the color specification for the application to \a spec.
+
+ The color specification controls how the application allocates colors when
+ run on a display with a limited amount of colors, e.g. 8 bit / 256 color
+ displays.
+
+ The color specification must be set before you create the QApplication
+ object.
+
+ The options are:
+ \list
+ \o QApplication::NormalColor. This is the default color allocation
+ strategy. Use this option if your application uses buttons, menus,
+ texts and pixmaps with few colors. With this option, the
+ application uses system global colors. This works fine for most
+ applications under X11, but on the Windows platform, it may cause
+ dithering of non-standard colors.
+ \o QApplication::CustomColor. Use this option if your application
+ needs a small number of custom colors. On X11, this option is the
+ same as NormalColor. On Windows, Qt creates a Windows palette, and
+ allocates colors to it on demand.
+ \o QApplication::ManyColor. Use this option if your application is
+ very color hungry, e.g., it requires thousands of colors. \br
+ Under X11 the effect is:
+ \list
+ \o For 256-color displays which have at best a 256 color true
+ color visual, the default visual is used, and colors are
+ allocated from a color cube. The color cube is the 6x6x6
+ (216 color) "Web palette" (the red, green, and blue
+ components always have one of the following values: 0x00,
+ 0x33, 0x66, 0x99, 0xCC, or 0xFF), but the number of colors
+ can be changed by the \e -ncols option. The user can force
+ the application to use the true color visual with the
+ \l{QApplication::QApplication()}{-visual} option.
+ \o For 256-color displays which have a true color visual with
+ more than 256 colors, use that visual. Silicon Graphics X
+ servers this feature, for example. They provide an 8 bit
+ visual by default but can deliver true color when asked.
+ \endlist
+ On Windows, Qt creates a Windows palette, and fills it with a color
+ cube.
+ \endlist
+
+ Be aware that the CustomColor and ManyColor choices may lead to colormap
+ flashing: The foreground application gets (most) of the available colors,
+ while the background windows will look less attractive.
+
+ Example:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 2
+
+ \sa colorSpec()
+*/
+
+void QApplication::setColorSpec(int spec)
+{
+ if (qApp)
+ qWarning("QApplication::setColorSpec: This function must be "
+ "called before the QApplication object is created");
+ QApplicationPrivate::app_cspec = spec;
+}
+
+/*!
+ \property QApplication::globalStrut
+ \brief the minimum size that any GUI element that the user can interact
+ with should have
+
+ For example, no button should be resized to be smaller than the global
+ strut size. The strut size should be considered when reimplementing GUI
+ controls that may be used on touch-screens or similar I/O devices.
+
+ Example:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 3
+
+ By default, this property contains a QSize object with zero width and height.
+*/
+QSize QApplication::globalStrut()
+{
+ return QApplicationPrivate::app_strut;
+}
+
+void QApplication::setGlobalStrut(const QSize& strut)
+{
+ QApplicationPrivate::app_strut = strut;
+}
+
+/*!
+ Returns the application palette.
+
+ \sa setPalette(), QWidget::palette()
+*/
+QPalette QApplication::palette()
+{
+ if (!QApplicationPrivate::app_pal)
+ QApplicationPrivate::app_pal = new QPalette(Qt::black);
+ return *QApplicationPrivate::app_pal;
+}
+
+/*!
+ \fn QPalette QApplication::palette(const QWidget* widget)
+ \overload
+
+ If a \a widget is passed, the default palette for the widget's class is
+ returned. This may or may not be the application palette. In most cases
+ there is no special palette for certain types of widgets, but one notable
+ exception is the popup menu under Windows, if the user has defined a
+ special background color for menus in the display settings.
+
+ \sa setPalette(), QWidget::palette()
+*/
+QPalette QApplication::palette(const QWidget* w)
+{
+ PaletteHash *hash = app_palettes();
+ if (w && hash && hash->size()) {
+ QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(w->metaObject()->className());
+ if (it != hash->constEnd())
+ return *it;
+ for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
+ if (w->inherits(it.key()))
+ return it.value();
+ }
+ }
+ return palette();
+}
+
+/*!
+ \overload
+
+ Returns the palette for widgets of the given \a className.
+
+ \sa setPalette(), QWidget::palette()
+*/
+QPalette QApplication::palette(const char *className)
+{
+ if (!QApplicationPrivate::app_pal)
+ palette();
+ PaletteHash *hash = app_palettes();
+ if (className && hash && hash->size()) {
+ QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(className);
+ if (it != hash->constEnd())
+ return *it;
+ }
+ return *QApplicationPrivate::app_pal;
+}
+
+void QApplicationPrivate::setPalette_helper(const QPalette &palette, const char* className, bool clearWidgetPaletteHash)
+{
+ QPalette pal = palette;
+
+ if (QApplicationPrivate::app_style)
+ QApplicationPrivate::app_style->polish(pal); // NB: non-const reference
+
+ bool all = false;
+ PaletteHash *hash = app_palettes();
+ if (!className) {
+ if (QApplicationPrivate::app_pal && pal.isCopyOf(*QApplicationPrivate::app_pal))
+ return;
+ if (!QApplicationPrivate::app_pal)
+ QApplicationPrivate::app_pal = new QPalette(pal);
+ else
+ *QApplicationPrivate::app_pal = pal;
+ if (hash && hash->size()) {
+ all = true;
+ if (clearWidgetPaletteHash)
+ hash->clear();
+ }
+ } else if (hash) {
+ hash->insert(className, pal);
+ }
+
+ if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
+ // Send ApplicationPaletteChange to qApp itself, and to the widgets.
+ QEvent e(QEvent::ApplicationPaletteChange);
+ QApplication::sendEvent(QApplication::instance(), &e);
+
+ QWidgetList wids = QApplication::allWidgets();
+ for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
+ register QWidget *w = *it;
+ if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
+ QApplication::sendEvent(w, &e);
+ }
+
+ // Send to all scenes as well.
+#ifndef QT_NO_GRAPHICSVIEW
+ QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
+ for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
+ it != scenes.constEnd(); ++it) {
+ QApplication::sendEvent(*it, &e);
+ }
+#endif //QT_NO_GRAPHICSVIEW
+ }
+ if (!className && (!QApplicationPrivate::sys_pal || !palette.isCopyOf(*QApplicationPrivate::sys_pal))) {
+ if (!QApplicationPrivate::set_pal)
+ QApplicationPrivate::set_pal = new QPalette(palette);
+ else
+ *QApplicationPrivate::set_pal = palette;
+ }
+}
+
+/*!
+ Changes the default application palette to \a palette.
+
+ If \a className is passed, the change applies only to widgets that inherit
+ \a className (as reported by QObject::inherits()). If \a className is left
+ 0, the change affects all widgets, thus overriding any previously set class
+ specific palettes.
+
+ The palette may be changed according to the current GUI style in
+ QStyle::polish().
+
+ \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
+ When using style sheets, the palette of a widget can be customized using
+ the "color", "background-color", "selection-color",
+ "selection-background-color" and "alternate-background-color".
+
+ \note Some styles do not use the palette for all drawing, for instance, if
+ they make use of native theme engines. This is the case for the Windows XP,
+ Windows Vista, and Mac OS X styles.
+
+ \sa QWidget::setPalette(), palette(), QStyle::polish()
+*/
+
+void QApplication::setPalette(const QPalette &palette, const char* className)
+{
+ QApplicationPrivate::setPalette_helper(palette, className, /*clearWidgetPaletteHash=*/ true);
+}
+
+
+
+void QApplicationPrivate::setSystemPalette(const QPalette &pal)
+{
+ QPalette adjusted;
+
+#if 0
+ // adjust the system palette to avoid dithering
+ QColormap cmap = QColormap::instance();
+ if (cmap.depths() > 4 && cmap.depths() < 24) {
+ for (int g = 0; g < QPalette::NColorGroups; g++)
+ for (int i = 0; i < QPalette::NColorRoles; i++) {
+ QColor color = pal.color((QPalette::ColorGroup)g, (QPalette::ColorRole)i);
+ color = cmap.colorAt(cmap.pixel(color));
+ adjusted.setColor((QPalette::ColorGroup)g, (QPalette::ColorRole) i, color);
+ }
+ }
+#else
+ adjusted = pal;
+#endif
+
+ if (!sys_pal)
+ sys_pal = new QPalette(adjusted);
+ else
+ *sys_pal = adjusted;
+
+
+ if (!QApplicationPrivate::set_pal)
+ QApplication::setPalette(*sys_pal);
+}
+
+/*!
+ Returns the default application font.
+
+ \sa fontMetrics(), QWidget::font()
+*/
+QFont QApplication::font()
+{
+ QMutexLocker locker(applicationFontMutex());
+ if (!QApplicationPrivate::app_font)
+ QApplicationPrivate::app_font = new QFont(QLatin1String("Helvetica"));
+ return *QApplicationPrivate::app_font;
+}
+
+/*!
+ \overload
+
+ Returns the default font for the \a widget.
+
+ \sa fontMetrics(), QWidget::setFont()
+*/
+
+QFont QApplication::font(const QWidget *widget)
+{
+ FontHash *hash = app_fonts();
+
+#ifdef Q_WS_MAC
+ // short circuit for small and mini controls
+ if (widget->testAttribute(Qt::WA_MacSmallSize)) {
+ return hash->value("QSmallFont");
+ } else if (widget->testAttribute(Qt::WA_MacMiniSize)) {
+ return hash->value("QMiniFont");
+ }
+#endif
+ if (widget && hash && hash->size()) {
+ QHash<QByteArray, QFont>::ConstIterator it =
+ hash->constFind(widget->metaObject()->className());
+ if (it != hash->constEnd())
+ return it.value();
+ for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
+ if (widget->inherits(it.key()))
+ return it.value();
+ }
+ }
+ return font();
+}
+
+/*!
+ \overload
+
+ Returns the font for widgets of the given \a className.
+
+ \sa setFont(), QWidget::font()
+*/
+QFont QApplication::font(const char *className)
+{
+ FontHash *hash = app_fonts();
+ if (className && hash && hash->size()) {
+ QHash<QByteArray, QFont>::ConstIterator it = hash->constFind(className);
+ if (it != hash->constEnd())
+ return *it;
+ }
+ return font();
+}
+
+
+/*!
+ Changes the default application font to \a font. If \a className is passed,
+ the change applies only to classes that inherit \a className (as reported
+ by QObject::inherits()).
+
+ On application start-up, the default font depends on the window system. It
+ can vary depending on both the window system version and the locale. This
+ function lets you override the default font; but overriding may be a bad
+ idea because, for example, some locales need extra large fonts to support
+ their special characters.
+
+ \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
+ The font of an application can be customized using the "font" style sheet
+ property. To set a bold font for all QPushButtons, set the application
+ styleSheet() as "QPushButton { font: bold }"
+
+ \sa font(), fontMetrics(), QWidget::setFont()
+*/
+
+void QApplication::setFont(const QFont &font, const char *className)
+{
+ bool all = false;
+ FontHash *hash = app_fonts();
+ if (!className) {
+ QMutexLocker locker(applicationFontMutex());
+ if (!QApplicationPrivate::app_font)
+ QApplicationPrivate::app_font = new QFont(font);
+ else
+ *QApplicationPrivate::app_font = font;
+ if (hash && hash->size()) {
+ all = true;
+ hash->clear();
+ }
+ } else if (hash) {
+ hash->insert(className, font);
+ }
+ if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
+ // Send ApplicationFontChange to qApp itself, and to the widgets.
+ QEvent e(QEvent::ApplicationFontChange);
+ QApplication::sendEvent(QApplication::instance(), &e);
+
+ QWidgetList wids = QApplication::allWidgets();
+ for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
+ register QWidget *w = *it;
+ if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
+ sendEvent(w, &e);
+ }
+
+#ifndef QT_NO_GRAPHICSVIEW
+ // Send to all scenes as well.
+ QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
+ for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
+ it != scenes.constEnd(); ++it) {
+ QApplication::sendEvent(*it, &e);
+ }
+#endif //QT_NO_GRAPHICSVIEW
+ }
+ if (!className && (!QApplicationPrivate::sys_font || !font.isCopyOf(*QApplicationPrivate::sys_font))) {
+ if (!QApplicationPrivate::set_font)
+ QApplicationPrivate::set_font = new QFont(font);
+ else
+ *QApplicationPrivate::set_font = font;
+ }
+}
+
+/*! \internal
+*/
+void QApplicationPrivate::setSystemFont(const QFont &font)
+{
+ if (!sys_font)
+ sys_font = new QFont(font);
+ else
+ *sys_font = font;
+
+ if (!QApplicationPrivate::set_font)
+ QApplication::setFont(*sys_font);
+}
+
+/*! \internal
+*/
+QString QApplicationPrivate::desktopStyleKey()
+{
+ return qt_guiPlatformPlugin()->styleName();
+}
+
+/*!
+ \property QApplication::windowIcon
+ \brief the default window icon
+
+ \sa QWidget::setWindowIcon(), {Setting the Application Icon}
+*/
+QIcon QApplication::windowIcon()
+{
+ return QApplicationPrivate::app_icon ? *QApplicationPrivate::app_icon : QIcon();
+}
+
+void QApplication::setWindowIcon(const QIcon &icon)
+{
+ if (!QApplicationPrivate::app_icon)
+ QApplicationPrivate::app_icon = new QIcon();
+ *QApplicationPrivate::app_icon = icon;
+ if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
+#ifdef Q_WS_MAC
+ void qt_mac_set_app_icon(const QPixmap &); //qapplication_mac.cpp
+ QSize size = QApplicationPrivate::app_icon->actualSize(QSize(128, 128));
+ qt_mac_set_app_icon(QApplicationPrivate::app_icon->pixmap(size));
+#endif
+ QEvent e(QEvent::ApplicationWindowIconChange);
+ QWidgetList all = QApplication::allWidgets();
+ for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
+ register QWidget *w = *it;
+ if (w->isWindow())
+ sendEvent(w, &e);
+ }
+ }
+}
+
+/*!
+ Returns a list of the top-level widgets (windows) in the application.
+
+ \note Some of the top-level widgets may be hidden, for example a tooltip if
+ no tooltip is currently shown.
+
+ Example:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 4
+
+ \sa allWidgets(), QWidget::isWindow(), QWidget::isHidden()
+*/
+QWidgetList QApplication::topLevelWidgets()
+{
+ QWidgetList list;
+ QWidgetList all = allWidgets();
+
+ for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
+ QWidget *w = *it;
+ if (w->isWindow() && w->windowType() != Qt::Desktop)
+ list.append(w);
+ }
+ return list;
+}
+
+/*!
+ Returns a list of all the widgets in the application.
+
+ The list is empty (QList::isEmpty()) if there are no widgets.
+
+ \note Some of the widgets may be hidden.
+
+ Example:
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 5
+
+ \sa topLevelWidgets(), QWidget::isVisible()
+*/
+
+QWidgetList QApplication::allWidgets()
+{
+ if (QWidgetPrivate::allWidgets)
+ return QWidgetPrivate::allWidgets->toList();
+ return QWidgetList();
+}
+
+/*!
+ Returns the application widget that has the keyboard input focus, or 0 if
+ no widget in this application has the focus.
+
+ \sa QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), focusChanged()
+*/
+
+QWidget *QApplication::focusWidget()
+{
+ return QApplicationPrivate::focus_widget;
+}
+
+void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
+{
+#ifndef QT_NO_GRAPHICSVIEW
+ if (focus && focus->window()->graphicsProxyWidget())
+ return;
+#endif
+
+ hidden_focus_widget = 0;
+
+ if (focus != focus_widget) {
+ if (focus && focus->isHidden()) {
+ hidden_focus_widget = focus;
+ return;
+ }
+
+ if (focus && (reason == Qt::BacktabFocusReason || reason == Qt::TabFocusReason)
+ && qt_in_tab_key_event)
+ focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
+ else if (focus && reason == Qt::ShortcutFocusReason) {
+ focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
+ }
+ QWidget *prev = focus_widget;
+ focus_widget = focus;
+#ifndef QT_NO_IM
+ if (prev && ((reason != Qt::PopupFocusReason && reason != Qt::MenuBarFocusReason
+ && prev->testAttribute(Qt::WA_InputMethodEnabled))
+ // Do reset the input context, in case the new focus widget won't accept keyboard input
+ // or it is not created fully yet.
+ || (focus_widget && (!focus_widget->testAttribute(Qt::WA_InputMethodEnabled)
+ || !focus_widget->testAttribute(Qt::WA_WState_Created))))) {
+ QInputContext *qic = prev->inputContext();
+ if(qic) {
+ qic->reset();
+ qic->setFocusWidget(0);
+ }
+ }
+#endif //QT_NO_IM
+
+ if(focus_widget)
+ focus_widget->d_func()->setFocus_sys();
+
+ if (reason != Qt::NoFocusReason) {
+
+ //send events
+ if (prev) {
+#ifdef QT_KEYPAD_NAVIGATION
+ if (QApplication::keypadNavigationEnabled()) {
+ if (prev->hasEditFocus() && reason != Qt::PopupFocusReason
+#ifdef Q_OS_SYMBIAN
+ && reason != Qt::ActiveWindowFocusReason
+#endif
+ )
+ prev->setEditFocus(false);
+ }
+#endif
+#ifndef QT_NO_IM
+ if (focus) {
+ QInputContext *prevIc;
+ prevIc = prev->inputContext();
+ if (prevIc && prevIc != focus->inputContext()) {
+ QEvent closeSIPEvent(QEvent::CloseSoftwareInputPanel);
+ QApplication::sendEvent(prev, &closeSIPEvent);
+ }
+ }
+#endif
+ QFocusEvent out(QEvent::FocusOut, reason);
+ QPointer<QWidget> that = prev;
+ QApplication::sendEvent(prev, &out);
+ if (that)
+ QApplication::sendEvent(that->style(), &out);
+ }
+ if(focus && QApplicationPrivate::focus_widget == focus) {
+#ifndef QT_NO_IM
+ if (focus->testAttribute(Qt::WA_InputMethodEnabled)) {
+ QInputContext *qic = focus->inputContext();
+ if (qic && focus->testAttribute(Qt::WA_WState_Created)
+ && focus->isEnabled())
+ qic->setFocusWidget(focus);
+ }
+#endif //QT_NO_IM
+ QFocusEvent in(QEvent::FocusIn, reason);
+ QPointer<QWidget> that = focus;
+ QApplication::sendEvent(focus, &in);
+ if (that)
+ QApplication::sendEvent(that->style(), &in);
+ }
+ emit qApp->focusChanged(prev, focus_widget);
+ }
+ }
+}
+
+
+/*!
+ Returns the application top-level window that has the keyboard input focus,
+ or 0 if no application window has the focus. There might be an
+ activeWindow() even if there is no focusWidget(), for example if no widget
+ in that window accepts key events.
+
+ \sa QWidget::setFocus(), QWidget::hasFocus(), focusWidget()
+*/
+
+QWidget *QApplication::activeWindow()
+{
+ return QApplicationPrivate::active_window;
+}
+
+/*!
+ Returns display (screen) font metrics for the application font.
+
+ \sa font(), setFont(), QWidget::fontMetrics(), QPainter::fontMetrics()
+*/
+
+QFontMetrics QApplication::fontMetrics()
+{
+ return desktop()->fontMetrics();
+}
+
+
+/*!
+ Closes all top-level windows.
+
+ This function is particularly useful for applications with many top-level
+ windows. It could, for example, be connected to a \gui{Exit} entry in the
+ \gui{File} menu:
+
+ \snippet examples/mainwindows/mdi/mainwindow.cpp 0
+
+ The windows are closed in random order, until one window does not accept
+ the close event. The application quits when the last window was
+ successfully closed; this can be turned off by setting
+ \l quitOnLastWindowClosed to false.
+
+ \sa quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(),
+ QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(),
+ QWidget::isWindow()
+*/
+void QApplication::closeAllWindows()
+{
+ bool did_close = true;
+ QWidget *w;
+ while ((w = activeModalWidget()) && did_close) {
+ if (!w->isVisible() || w->data->is_closing)
+ break;
+ did_close = w->close();
+ }
+ QWidgetList list = QApplication::topLevelWidgets();
+ for (int i = 0; did_close && i < list.size(); ++i) {
+ w = list.at(i);
+ if (w->isVisible()
+ && w->windowType() != Qt::Desktop
+ && !w->data->is_closing) {
+ did_close = w->close();
+ list = QApplication::topLevelWidgets();
+ i = -1;
+ }
+ }
+}
+
+/*!
+ Displays a simple message box about Qt. The message includes the version
+ number of Qt being used by the application.
+
+ This is useful for inclusion in the \gui Help menu of an application, as
+ shown in the \l{mainwindows/menus}{Menus} example.
+
+ This function is a convenience slot for QMessageBox::aboutQt().
+*/
+void QApplication::aboutQt()
+{
+#ifndef QT_NO_MESSAGEBOX
+ QMessageBox::aboutQt(
+#ifdef Q_WS_MAC
+ 0
+#else
+ activeWindow()
+#endif // Q_WS_MAC
+ );
+#endif // QT_NO_MESSAGEBOX
+}
+
+
+/*!
+ \fn void QApplication::lastWindowClosed()
+
+ This signal is emitted from QApplication::exec() when the last visible
+ primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose
+ attribute set is closed.
+
+ By default,
+
+ \list
+ \o this attribute is set for all widgets except transient windows such
+ as splash screens, tool windows, and popup menus
+
+ \o QApplication implicitly quits when this signal is emitted.
+ \endlist
+
+ This feature can be turned off by setting \l quitOnLastWindowClosed to
+ false.
+
+ \sa QWidget::close()
+*/
+
+/*!
+ \since 4.1
+ \fn void QApplication::focusChanged(QWidget *old, QWidget *now)
+
+ This signal is emitted when the widget that has keyboard focus changed from
+ \a old to \a now, i.e., because the user pressed the tab-key, clicked into
+ a widget or changed the active window. Both \a old and \a now can be the
+ null-pointer.
+
+ The signal is emitted after both widget have been notified about the change
+ through QFocusEvent.
+
+ \sa QWidget::setFocus(), QWidget::clearFocus(), Qt::FocusReason
+*/
+
+/*!
+ \since 4.5
+ \fn void QApplication::fontDatabaseChanged()
+
+ This signal is emitted when application fonts are loaded or removed.
+
+ \sa QFontDatabase::addApplicationFont(),
+ QFontDatabase::addApplicationFontFromData(),
+ QFontDatabase::removeAllApplicationFonts(),
+ QFontDatabase::removeApplicationFont()
+*/
+
+#ifndef QT_NO_TRANSLATION
+static bool qt_detectRTLLanguage()
+{
+ return force_reverse ^
+ (QApplication::tr("QT_LAYOUT_DIRECTION",
+ "Translate this string to the string 'LTR' in left-to-right"
+ " languages or to 'RTL' in right-to-left languages (such as Hebrew"
+ " and Arabic) to get proper widget layout.") == QLatin1String("RTL"));
+}
+#if defined(Q_WS_MAC)
+static const char *application_menu_strings[] = {
+ QT_TRANSLATE_NOOP("MAC_APPLICATION_MENU","Services"),
+ QT_TRANSLATE_NOOP("MAC_APPLICATION_MENU","Hide %1"),
+ QT_TRANSLATE_NOOP("MAC_APPLICATION_MENU","Hide Others"),
+ QT_TRANSLATE_NOOP("MAC_APPLICATION_MENU","Show All"),
+ QT_TRANSLATE_NOOP("MAC_APPLICATION_MENU","Preferences..."),
+ QT_TRANSLATE_NOOP("MAC_APPLICATION_MENU","Quit %1"),
+ QT_TRANSLATE_NOOP("MAC_APPLICATION_MENU","About %1")
+ };
+QString qt_mac_applicationmenu_string(int type)
+{
+ QString menuString = QString::fromLatin1(application_menu_strings[type]);
+ QString translated = qApp->translate("QMenuBar", application_menu_strings[type]);
+ if (translated != menuString)
+ return translated;
+ else
+ return qApp->translate("MAC_APPLICATION_MENU",
+ application_menu_strings[type]);
+}
+#endif
+#endif
+
+/*!\reimp
+
+*/
+bool QApplication::event(QEvent *e)
+{
+ Q_D(QApplication);
+ if(e->type() == QEvent::Close) {
+#if defined(Q_OS_SYMBIAN)
+ // In order to have proper application-exit effects on Symbian, certain
+ // native APIs have to be called _before_ closing/destroying the widgets.
+ bool effectStarted = qt_beginFullScreenEffect();
+#endif
+ QCloseEvent *ce = static_cast<QCloseEvent*>(e);
+ ce->accept();
+ closeAllWindows();
+
+ QWidgetList list = topLevelWidgets();
+ for (int i = 0; i < list.size(); ++i) {
+ QWidget *w = list.at(i);
+ if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
+ (!(w->windowType() == Qt::Dialog) || !w->parentWidget())) {
+ ce->ignore();
+ break;
+ }
+ }
+ if (ce->isAccepted()) {
+ return true;
+ } else {
+#if defined(Q_OS_SYMBIAN)
+ if (effectStarted)
+ qt_abortFullScreenEffect();
+#endif
+ }
+ } else if(e->type() == QEvent::LanguageChange) {
+#ifndef QT_NO_TRANSLATION
+ setLayoutDirection(qt_detectRTLLanguage()?Qt::RightToLeft:Qt::LeftToRight);
+#endif
+#if defined(QT_MAC_USE_COCOA)
+ qt_mac_post_retranslateAppMenu();
+#endif
+ QWidgetList list = topLevelWidgets();
+ for (int i = 0; i < list.size(); ++i) {
+ QWidget *w = list.at(i);
+ if (!(w->windowType() == Qt::Desktop))
+ postEvent(w, new QEvent(QEvent::LanguageChange));
+ }
+#ifndef Q_OS_WIN
+ } else if (e->type() == QEvent::LocaleChange) {
+ // on Windows the event propagation is taken care by the
+ // WM_SETTINGCHANGE event handler.
+ QWidgetList list = topLevelWidgets();
+ for (int i = 0; i < list.size(); ++i) {
+ QWidget *w = list.at(i);
+ if (!(w->windowType() == Qt::Desktop)) {
+ if (!w->testAttribute(Qt::WA_SetLocale))
+ w->d_func()->setLocale_helper(QLocale(), true);
+ }
+ }
+#endif
+ } else if (e->type() == QEvent::Timer) {
+ QTimerEvent *te = static_cast<QTimerEvent*>(e);
+ Q_ASSERT(te != 0);
+ if (te->timerId() == d->toolTipWakeUp.timerId()) {
+ d->toolTipWakeUp.stop();
+ if (d->toolTipWidget) {
+ QWidget *w = d->toolTipWidget->window();
+ // show tooltip if WA_AlwaysShowToolTips is set, or if
+ // any ancestor of d->toolTipWidget is the active
+ // window
+ bool showToolTip = w->testAttribute(Qt::WA_AlwaysShowToolTips);
+ while (w && !showToolTip) {
+ showToolTip = w->isActiveWindow();
+ w = w->parentWidget();
+ w = w ? w->window() : 0;
+ }
+ if (showToolTip) {
+ QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
+ QApplication::sendEvent(d->toolTipWidget, &e);
+ if (e.isAccepted())
+ d->toolTipFallAsleep.start(2000, this);
+ }
+ }
+ } else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
+ d->toolTipFallAsleep.stop();
+ }
+ }
+ return QCoreApplication::event(e);
+}
+#if !defined(Q_WS_X11)
+
+// The doc and X implementation of this function is in qapplication_x11.cpp
+
+void QApplication::syncX() {} // do nothing
+
+#endif
+
+/*!
+ \fn Qt::WindowsVersion QApplication::winVersion()
+
+ Use \l QSysInfo::WindowsVersion instead.
+*/
+
+/*!
+ \fn void QApplication::setActiveWindow(QWidget* active)
+
+ Sets the active window to the \a active widget in response to a system
+ event. The function is called from the platform specific event handlers.
+
+ \warning This function does \e not set the keyboard focus to the active
+ widget. Call QWidget::activateWindow() instead.
+
+ It sets the activeWindow() and focusWidget() attributes and sends proper
+ \l{QEvent::WindowActivate}{WindowActivate}/\l{QEvent::WindowDeactivate}
+ {WindowDeactivate} and \l{QEvent::FocusIn}{FocusIn}/\l{QEvent::FocusOut}
+ {FocusOut} events to all appropriate widgets. The window will then be
+ painted in active state (e.g. cursors in line edits will blink), and it
+ will have tool tips enabled.
+
+ \sa activeWindow(), QWidget::activateWindow()
+*/
+void QApplication::setActiveWindow(QWidget* act)
+{
+ QWidget* window = act?act->window():0;
+
+ if (QApplicationPrivate::active_window == window)
+ return;
+
+#ifndef QT_NO_GRAPHICSVIEW
+ if (window && window->graphicsProxyWidget()) {
+ // Activate the proxy's view->viewport() ?
+ return;
+ }
+#endif
+
+ QWidgetList toBeActivated;
+ QWidgetList toBeDeactivated;
+
+ if (QApplicationPrivate::active_window) {
+ if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
+ QWidgetList list = topLevelWidgets();
+ for (int i = 0; i < list.size(); ++i) {
+ QWidget *w = list.at(i);
+ if (w->isVisible() && w->isActiveWindow())
+ toBeDeactivated.append(w);
+ }
+ } else {
+ toBeDeactivated.append(QApplicationPrivate::active_window);
+ }
+ }
+
+#if !defined(Q_WS_MAC)
+ QWidget *previousActiveWindow = QApplicationPrivate::active_window;
+#endif
+ QApplicationPrivate::active_window = window;
+
+ if (QApplicationPrivate::active_window) {
+ if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
+ QWidgetList list = topLevelWidgets();
+ for (int i = 0; i < list.size(); ++i) {
+ QWidget *w = list.at(i);
+ if (w->isVisible() && w->isActiveWindow())
+ toBeActivated.append(w);
+ }
+ } else {
+ toBeActivated.append(QApplicationPrivate::active_window);
+ }
+
+ }
+
+ // first the activation/deactivation events
+ QEvent activationChange(QEvent::ActivationChange);
+ QEvent windowActivate(QEvent::WindowActivate);
+ QEvent windowDeactivate(QEvent::WindowDeactivate);
+
+#if !defined(Q_WS_MAC)
+ if (!previousActiveWindow) {
+ QEvent appActivate(QEvent::ApplicationActivate);
+ sendSpontaneousEvent(qApp, &appActivate);
+ }
+#endif
+
+ for (int i = 0; i < toBeActivated.size(); ++i) {
+ QWidget *w = toBeActivated.at(i);
+ sendSpontaneousEvent(w, &windowActivate);
+ sendSpontaneousEvent(w, &activationChange);
+ }
+
+#ifdef QT_MAC_USE_COCOA
+ // In case the user clicked on a child window, we need to
+ // reestablish the stacking order of the window so
+ // it pops in front of other child windows in cocoa:
+ qt_cocoaStackChildWindowOnTopOfOtherChildren(window);
+#endif
+
+ for(int i = 0; i < toBeDeactivated.size(); ++i) {
+ QWidget *w = toBeDeactivated.at(i);
+ sendSpontaneousEvent(w, &windowDeactivate);
+ sendSpontaneousEvent(w, &activationChange);
+ }
+
+#if !defined(Q_WS_MAC)
+ if (!QApplicationPrivate::active_window) {
+ QEvent appDeactivate(QEvent::ApplicationDeactivate);
+ sendSpontaneousEvent(qApp, &appDeactivate);
+ }
+#endif
+
+ if (QApplicationPrivate::popupWidgets == 0) { // !inPopupMode()
+ // then focus events
+ if (!QApplicationPrivate::active_window && QApplicationPrivate::focus_widget) {
+ QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
+ } else if (QApplicationPrivate::active_window) {
+ QWidget *w = QApplicationPrivate::active_window->focusWidget();
+ if (w && w->isVisible() /*&& w->focusPolicy() != QWidget::NoFocus*/)
+ w->setFocus(Qt::ActiveWindowFocusReason);
+ else {
+ w = QApplicationPrivate::focusNextPrevChild_helper(QApplicationPrivate::active_window, true);
+ if (w) {
+ w->setFocus(Qt::ActiveWindowFocusReason);
+ } else {
+ // If the focus widget is not in the activate_window, clear the focus
+ w = QApplicationPrivate::focus_widget;
+ if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus)
+ QApplicationPrivate::setFocusWidget(QApplicationPrivate::active_window, Qt::ActiveWindowFocusReason);
+ else if (!QApplicationPrivate::active_window->isAncestorOf(w))
+ QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
+ }
+ }
+ }
+ }
+}
+
+/*!internal
+ * Helper function that returns the new focus widget, but does not set the focus reason.
+ * Returns 0 if a new focus widget could not be found.
+ * Shared with QGraphicsProxyWidgetPrivate::findFocusChild()
+*/
+QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool next)
+{
+ uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
+
+ QWidget *f = toplevel->focusWidget();
+ if (!f)
+ f = toplevel;
+
+ QWidget *w = f;
+ QWidget *test = f->d_func()->focus_next;
+ while (test && test != f) {
+ if ((test->focusPolicy() & focus_flag) == focus_flag
+ && !(test->d_func()->extra && test->d_func()->extra->focus_proxy)
+ && test->isVisibleTo(toplevel) && test->isEnabled()
+ && !(w->windowType() == Qt::SubWindow && !w->isAncestorOf(test))
+ && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))) {
+ w = test;
+ if (next)
+ break;
+ }
+ test = test->d_func()->focus_next;
+ }
+ if (w == f) {
+ if (qt_in_tab_key_event) {
+ w->window()->setAttribute(Qt::WA_KeyboardFocusChange);
+ w->update();
+ }
+ return 0;
+ }
+ return w;
+}
+
+/*!
+ \fn void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave)
+ \internal
+
+ Creates the proper Enter/Leave event when widget \a enter is entered and
+ widget \a leave is left.
+ */
+void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave) {
+#if 0
+ if (leave) {
+ QEvent e(QEvent::Leave);
+ QApplication::sendEvent(leave, & e);
+ }
+ if (enter) {
+ QEvent e(QEvent::Enter);
+ QApplication::sendEvent(enter, & e);
+ }
+ return;
+#endif
+
+ QWidget* w ;
+ if ((!enter && !leave) || (enter == leave))
+ return;
+#ifdef ALIEN_DEBUG
+ qDebug() << "QApplicationPrivate::dispatchEnterLeave, ENTER:" << enter << "LEAVE:" << leave;
+#endif
+ QWidgetList leaveList;
+ QWidgetList enterList;
+
+ bool sameWindow = leave && enter && leave->window() == enter->window();
+ if (leave && !sameWindow) {
+ w = leave;
+ do {
+ leaveList.append(w);
+ } while (!w->isWindow() && (w = w->parentWidget()));
+ }
+ if (enter && !sameWindow) {
+ w = enter;
+ do {
+ enterList.prepend(w);
+ } while (!w->isWindow() && (w = w->parentWidget()));
+ }
+ if (sameWindow) {
+ int enterDepth = 0;
+ int leaveDepth = 0;
+ w = enter;
+ while (!w->isWindow() && (w = w->parentWidget()))
+ enterDepth++;
+ w = leave;
+ while (!w->isWindow() && (w = w->parentWidget()))
+ leaveDepth++;
+ QWidget* wenter = enter;
+ QWidget* wleave = leave;
+ while (enterDepth > leaveDepth) {
+ wenter = wenter->parentWidget();
+ enterDepth--;
+ }
+ while (leaveDepth > enterDepth) {
+ wleave = wleave->parentWidget();
+ leaveDepth--;
+ }
+ while (!wenter->isWindow() && wenter != wleave) {
+ wenter = wenter->parentWidget();
+ wleave = wleave->parentWidget();
+ }
+
+ w = leave;
+ while (w != wleave) {
+ leaveList.append(w);
+ w = w->parentWidget();
+ }
+ w = enter;
+ while (w != wenter) {
+ enterList.prepend(w);
+ w = w->parentWidget();
+ }
+ }
+
+ QEvent leaveEvent(QEvent::Leave);
+ for (int i = 0; i < leaveList.size(); ++i) {
+ w = leaveList.at(i);
+ if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
+#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
+ if (leaveAfterRelease == w)
+ leaveAfterRelease = 0;
+#endif
+ QApplication::sendEvent(w, &leaveEvent);
+ if (w->testAttribute(Qt::WA_Hover) &&
+ (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
+ Q_ASSERT(instance());
+ QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos));
+ qApp->d_func()->notify_helper(w, &he);
+ }
+ }
+ }
+ QPoint posEnter = QCursor::pos();
+ QEvent enterEvent(QEvent::Enter);
+ for (int i = 0; i < enterList.size(); ++i) {
+ w = enterList.at(i);
+ if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
+ QApplication::sendEvent(w, &enterEvent);
+ if (w->testAttribute(Qt::WA_Hover) &&
+ (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
+ QHoverEvent he(QEvent::HoverEnter, w->mapFromGlobal(posEnter), QPoint(-1, -1));
+ qApp->d_func()->notify_helper(w, &he);
+ }
+ }
+ }
+
+#ifndef QT_NO_CURSOR
+ // Update cursor for alien/graphics widgets.
+
+ const bool enterOnAlien = (enter && (isAlien(enter) || enter->testAttribute(Qt::WA_DontShowOnScreen)));
+#if defined(Q_WS_X11) || defined(Q_WS_QPA)
+ //Whenever we leave an alien widget on X11, we need to reset its nativeParentWidget()'s cursor.
+ // This is not required on Windows as the cursor is reset on every single mouse move.
+ QWidget *parentOfLeavingCursor = 0;
+ for (int i = 0; i < leaveList.size(); ++i) {
+ w = leaveList.at(i);
+ if (!isAlien(w))
+ break;
+ if (w->testAttribute(Qt::WA_SetCursor)) {
+ QWidget *parent = w->parentWidget();
+ while (parent && parent->d_func()->data.in_destructor)
+ parent = parent->parentWidget();
+ parentOfLeavingCursor = parent;
+ //continue looping, we need to find the downest alien widget with a cursor.
+ // (downest on the screen)
+ }
+ }
+ //check that we will not call qt_x11_enforce_cursor twice with the same native widget
+ if (parentOfLeavingCursor && (!enterOnAlien
+ || parentOfLeavingCursor->effectiveWinId() != enter->effectiveWinId())) {
+#ifndef QT_NO_GRAPHICSVIEW
+ if (!parentOfLeavingCursor->window()->graphicsProxyWidget())
+#endif
+ {
+#if defined(Q_WS_X11)
+ qt_x11_enforce_cursor(parentOfLeavingCursor,true);
+#elif defined(Q_WS_QPA)
+ if (enter == QApplication::desktop()) {
+ qt_qpa_set_cursor(enter, true);
+ } else {
+ qt_qpa_set_cursor(parentOfLeavingCursor, true);
+ }
+#endif
+ }
+ }
+#endif
+ if (enterOnAlien) {
+ QWidget *cursorWidget = enter;
+ while (!cursorWidget->isWindow() && !cursorWidget->isEnabled())
+ cursorWidget = cursorWidget->parentWidget();
+
+ if (!cursorWidget)
+ return;
+
+#ifndef QT_NO_GRAPHICSVIEW
+ if (cursorWidget->window()->graphicsProxyWidget()) {
+ QWidgetPrivate::nearestGraphicsProxyWidget(cursorWidget)->setCursor(cursorWidget->cursor());
+ } else
+#endif
+ {
+#if defined(Q_WS_WIN)
+ qt_win_set_cursor(cursorWidget, true);
+#elif defined(Q_WS_X11)
+ qt_x11_enforce_cursor(cursorWidget, true);
+#elif defined(Q_OS_SYMBIAN)
+ qt_symbian_set_cursor(cursorWidget, true);
+#elif defined(Q_WS_QPA)
+ qt_qpa_set_cursor(cursorWidget, true);
+#endif
+ }
+ }
+#endif
+}
+
+/* exported for the benefit of testing tools */
+Q_GUI_EXPORT bool qt_tryModalHelper(QWidget *widget, QWidget **rettop)
+{
+ return QApplicationPrivate::tryModalHelper(widget, rettop);
+}
+
+/*! \internal
+ Returns true if \a widget is blocked by a modal window.
+ */
+bool QApplicationPrivate::isBlockedByModal(QWidget *widget)
+{
+ widget = widget->window();
+ if (!modalState())
+ return false;
+ if (QApplication::activePopupWidget() == widget)
+ return false;
+
+ for (int i = 0; i < qt_modal_stack->size(); ++i) {
+ QWidget *modalWidget = qt_modal_stack->at(i);
+
+ {
+ // check if the active modal widget is our widget or a parent of our widget
+ QWidget *w = widget;
+ while (w) {
+ if (w == modalWidget)
+ return false;
+ w = w->parentWidget();
+ }
+#ifdef Q_WS_WIN
+ if ((widget->testAttribute(Qt::WA_WState_Created) || widget->data->winid)
+ && (modalWidget->testAttribute(Qt::WA_WState_Created) || modalWidget->data->winid)
+ && IsChild(modalWidget->data->winid, widget->data->winid))
+ return false;
+#endif
+ }
+
+ Qt::WindowModality windowModality = modalWidget->windowModality();
+ if (windowModality == Qt::NonModal) {
+ // determine the modality type if it hasn't been set on the
+ // modalWidget, this normally happens when waiting for a
+ // native dialog. use WindowModal if we are the child of a
+ // group leader; otherwise use ApplicationModal.
+ QWidget *m = modalWidget;
+ while (m && !m->testAttribute(Qt::WA_GroupLeader)) {
+ m = m->parentWidget();
+ if (m)
+ m = m->window();
+ }
+ windowModality = (m && m->testAttribute(Qt::WA_GroupLeader))
+ ? Qt::WindowModal
+ : Qt::ApplicationModal;
+ }
+
+ switch (windowModality) {
+ case Qt::ApplicationModal:
+ {
+ QWidget *groupLeaderForWidget = widget;
+ while (groupLeaderForWidget && !groupLeaderForWidget->testAttribute(Qt::WA_GroupLeader))
+ groupLeaderForWidget = groupLeaderForWidget->parentWidget();
+
+ if (groupLeaderForWidget) {
+ // if \a widget has WA_GroupLeader, it can only be blocked by ApplicationModal children
+ QWidget *m = modalWidget;
+ while (m && m != groupLeaderForWidget && !m->testAttribute(Qt::WA_GroupLeader))
+ m = m->parentWidget();
+ if (m == groupLeaderForWidget)
+ return true;
+ } else if (modalWidget != widget) {
+ return true;
+ }
+ break;
+ }
+ case Qt::WindowModal:
+ {
+ QWidget *w = widget;
+ do {
+ QWidget *m = modalWidget;
+ do {
+ if (m == w)
+ return true;
+ m = m->parentWidget();
+ if (m)
+ m = m->window();
+ } while (m);
+ w = w->parentWidget();
+ if (w)
+ w = w->window();
+ } while (w);
+ break;
+ }
+ default:
+ Q_ASSERT_X(false, "QApplication", "internal error, a modal widget cannot be modeless");
+ break;
+ }
+ }
+ return false;
+}
+
+/*!\internal
+ */
+void QApplicationPrivate::enterModal(QWidget *widget)
+{
+ QSet<QWidget*> blocked;
+ QList<QWidget*> windows = QApplication::topLevelWidgets();
+ for (int i = 0; i < windows.count(); ++i) {
+ QWidget *window = windows.at(i);
+ if (window->windowType() != Qt::Tool && isBlockedByModal(window))
+ blocked.insert(window);
+ }
+
+ enterModal_sys(widget);
+
+ windows = QApplication::topLevelWidgets();
+ QEvent e(QEvent::WindowBlocked);
+ for (int i = 0; i < windows.count(); ++i) {
+ QWidget *window = windows.at(i);
+ if (!blocked.contains(window) && window->windowType() != Qt::Tool && isBlockedByModal(window))
+ QApplication::sendEvent(window, &e);
+ }
+}
+
+/*!\internal
+ */
+void QApplicationPrivate::leaveModal(QWidget *widget)
+{
+ QSet<QWidget*> blocked;
+ QList<QWidget*> windows = QApplication::topLevelWidgets();
+ for (int i = 0; i < windows.count(); ++i) {
+ QWidget *window = windows.at(i);
+ if (window->windowType() != Qt::Tool && isBlockedByModal(window))
+ blocked.insert(window);
+ }
+
+ leaveModal_sys(widget);
+
+ windows = QApplication::topLevelWidgets();
+ QEvent e(QEvent::WindowUnblocked);
+ for (int i = 0; i < windows.count(); ++i) {
+ QWidget *window = windows.at(i);
+ if(blocked.contains(window) && window->windowType() != Qt::Tool && !isBlockedByModal(window))
+ QApplication::sendEvent(window, &e);
+ }
+}
+
+
+
+/*!\internal
+
+ Called from qapplication_\e{platform}.cpp, returns true
+ if the widget should accept the event.
+ */
+bool QApplicationPrivate::tryModalHelper(QWidget *widget, QWidget **rettop)
+{
+ QWidget *top = QApplication::activeModalWidget();
+ if (rettop)
+ *rettop = top;
+
+ // the active popup widget always gets the input event
+ if (QApplication::activePopupWidget())
+ return true;
+
+#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
+ top = QApplicationPrivate::tryModalHelper_sys(top);
+ if (rettop)
+ *rettop = top;
+#endif
+
+ return !isBlockedByModal(widget->window());
+}
+
+/*
+ \internal
+*/
+QWidget *QApplicationPrivate::pickMouseReceiver(QWidget *candidate, const QPoint &globalPos,
+ QPoint &pos, QEvent::Type type,
+ Qt::MouseButtons buttons, QWidget *buttonDown,
+ QWidget *alienWidget)
+{
+ Q_ASSERT(candidate);
+
+ QWidget *mouseGrabber = QWidget::mouseGrabber();
+ if (((type == QEvent::MouseMove && buttons) || (type == QEvent::MouseButtonRelease))
+ && !buttonDown && !mouseGrabber) {
+ return 0;
+ }
+
+ if (alienWidget && alienWidget->internalWinId())
+ alienWidget = 0;
+
+ QWidget *receiver = candidate;
+
+ if (!mouseGrabber)
+ mouseGrabber = (buttonDown && !isBlockedByModal(buttonDown)) ? buttonDown : alienWidget;
+
+ if (mouseGrabber && mouseGrabber != candidate) {
+ receiver = mouseGrabber;
+ pos = receiver->mapFromGlobal(globalPos);
+#ifdef ALIEN_DEBUG
+ qDebug() << " ** receiver adjusted to:" << receiver << "pos:" << pos;
+#endif
+ }
+
+ return receiver;
+
+}
+
+/*
+ \internal
+*/
+bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
+ QWidget *alienWidget, QWidget *nativeWidget,
+ QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
+ bool spontaneous)
+{
+ Q_ASSERT(receiver);
+ Q_ASSERT(event);
+ Q_ASSERT(nativeWidget);
+ Q_ASSERT(buttonDown);
+
+ if (alienWidget && !isAlien(alienWidget))
+ alienWidget = 0;
+
+ QPointer<QWidget> receiverGuard = receiver;
+ QPointer<QWidget> nativeGuard = nativeWidget;
+ QPointer<QWidget> alienGuard = alienWidget;
+ QPointer<QWidget> activePopupWidget = QApplication::activePopupWidget();
+
+ const bool graphicsWidget = nativeWidget->testAttribute(Qt::WA_DontShowOnScreen);
+
+ if (*buttonDown) {
+ if (!graphicsWidget) {
+ // Register the widget that shall receive a leave event
+ // after the last button is released.
+ if ((alienWidget || !receiver->internalWinId()) && !leaveAfterRelease && !QWidget::mouseGrabber())
+ leaveAfterRelease = *buttonDown;
+ if (event->type() == QEvent::MouseButtonRelease && !event->buttons())
+ *buttonDown = 0;
+ }
+ } else if (lastMouseReceiver) {
+ // Dispatch enter/leave if we move:
+ // 1) from an alien widget to another alien widget or
+ // from a native widget to an alien widget (first OR case)
+ // 2) from an alien widget to a native widget (second OR case)
+ if ((alienWidget && alienWidget != lastMouseReceiver)
+ || (isAlien(lastMouseReceiver) && !alienWidget)) {
+ if (activePopupWidget) {
+ if (!QWidget::mouseGrabber())
+ dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver);
+ } else {
+ dispatchEnterLeave(receiver, lastMouseReceiver);
+ }
+
+ }
+ }
+
+#ifdef ALIEN_DEBUG
+ qDebug() << "QApplicationPrivate::sendMouseEvent: receiver:" << receiver
+ << "pos:" << event->pos() << "alien" << alienWidget << "button down"
+ << *buttonDown << "last" << lastMouseReceiver << "leave after release"
+ << leaveAfterRelease;
+#endif
+
+ // We need this quard in case someone opens a modal dialog / popup. If that's the case
+ // leaveAfterRelease is set to null, but we shall not update lastMouseReceiver.
+ const bool wasLeaveAfterRelease = leaveAfterRelease != 0;
+ bool result;
+ if (spontaneous)
+ result = QApplication::sendSpontaneousEvent(receiver, event);
+ else
+ result = QApplication::sendEvent(receiver, event);
+
+ if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease
+ && !event->buttons() && QWidget::mouseGrabber() != leaveAfterRelease) {
+ // Dispatch enter/leave if:
+ // 1) the mouse grabber is an alien widget
+ // 2) the button is released on an alien widget
+ QWidget *enter = 0;
+ if (nativeGuard)
+ enter = alienGuard ? alienWidget : nativeWidget;
+ else // The receiver is typically deleted on mouse release with drag'n'drop.
+ enter = QApplication::widgetAt(event->globalPos());
+ dispatchEnterLeave(enter, leaveAfterRelease);
+ leaveAfterRelease = 0;
+ lastMouseReceiver = enter;
+ } else if (!wasLeaveAfterRelease) {
+ if (activePopupWidget) {
+ if (!QWidget::mouseGrabber())
+ lastMouseReceiver = alienGuard ? alienWidget : (nativeGuard ? nativeWidget : 0);
+ } else {
+ lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPos());
+ }
+ }
+
+ return result;
+}
+
+#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
+/*
+ This function should only be called when the widget changes visibility, i.e.
+ when the \a widget is shown, hidden or deleted. This function does nothing
+ if the widget is a top-level or native, i.e. not an alien widget. In that
+ case enter/leave events are genereated by the underlying windowing system.
+*/
+extern QPointer<QWidget> qt_last_mouse_receiver;
+extern QWidget *qt_button_down;
+void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
+{
+#ifndef QT_NO_CURSOR
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA)
+ if (!widget || widget->isWindow())
+ return;
+#else
+ if (!widget || widget->internalWinId() || widget->isWindow())
+ return;
+#endif
+ const bool widgetInShow = widget->isVisible() && !widget->data->in_destructor;
+ if (!widgetInShow && widget != qt_last_mouse_receiver)
+ return; // Widget was not under the cursor when it was hidden/deleted.
+
+ if (widgetInShow && widget->parentWidget()->data->in_show)
+ return; // Ingore recursive show.
+
+ QWidget *mouseGrabber = QWidget::mouseGrabber();
+ if (mouseGrabber && mouseGrabber != widget)
+ return; // Someone else has the grab; enter/leave should not occur.
+
+ QWidget *tlw = widget->window();
+ if (tlw->data->in_destructor || tlw->data->is_closing)
+ return; // Closing down the business.
+
+ if (widgetInShow && (!qt_last_mouse_receiver || qt_last_mouse_receiver->window() != tlw))
+ return; // Mouse cursor not inside the widget's top-level.
+
+ const QPoint globalPos(QCursor::pos());
+ QPoint pos = tlw->mapFromGlobal(globalPos);
+
+ // Find the current widget under the mouse. If this function was called from
+ // the widget's destructor, we have to make sure childAt() doesn't take into
+ // account widgets that are about to be destructed.
+ QWidget *widgetUnderCursor = tlw->d_func()->childAt_helper(pos, widget->data->in_destructor);
+ if (!widgetUnderCursor)
+ widgetUnderCursor = tlw;
+ else
+ pos = widgetUnderCursor->mapFrom(tlw, pos);
+
+ if (widgetInShow && widgetUnderCursor != widget && !widget->isAncestorOf(widgetUnderCursor))
+ return; // Mouse cursor not inside the widget or any of its children.
+
+ if (widget->data->in_destructor && qt_button_down == widget)
+ qt_button_down = 0;
+
+ // Send enter/leave events followed by a mouse move on the entered widget.
+ QMouseEvent e(QEvent::MouseMove, pos, globalPos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
+ sendMouseEvent(widgetUnderCursor, &e, widgetUnderCursor, tlw, &qt_button_down, qt_last_mouse_receiver);
+#endif // QT_NO_CURSOR
+}
+#endif // Q_WS_WIN || Q_WS_X11 || Q_WS_MAC
+
+/*!
+ Returns the desktop widget (also called the root window).
+
+ The desktop may be composed of multiple screens, so it would be incorrect,
+ for example, to attempt to \e center some widget in the desktop's geometry.
+ QDesktopWidget has various functions for obtaining useful geometries upon
+ the desktop, such as QDesktopWidget::screenGeometry() and
+ QDesktopWidget::availableGeometry().
+
+ On X11, it is also possible to draw on the desktop.
+*/
+QDesktopWidget *QApplication::desktop()
+{
+ if (!qt_desktopWidget || // not created yet
+ !(qt_desktopWidget->windowType() == Qt::Desktop)) { // reparented away
+ qt_desktopWidget = new QDesktopWidget();
+ }
+ return qt_desktopWidget;
+}
+
+#ifndef QT_NO_CLIPBOARD
+/*!
+ Returns a pointer to the application global clipboard.
+
+ \note The QApplication object should already be constructed before
+ accessing the clipboard.
+*/
+QClipboard *QApplication::clipboard()
+{
+ if (qt_clipboard == 0) {
+ if (!qApp) {
+ qWarning("QApplication: Must construct a QApplication before accessing a QClipboard");
+ return 0;
+ }
+ qt_clipboard = new QClipboard(0);
+ }
+ return qt_clipboard;
+}
+#endif // QT_NO_CLIPBOARD
+
+/*!
+ Sets whether Qt should use the system's standard colors, fonts, etc., to
+ \a on. By default, this is true.
+
+ This function must be called before creating the QApplication object, like
+ this:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 6
+
+ \sa desktopSettingsAware()
+*/
+void QApplication::setDesktopSettingsAware(bool on)
+{
+ QApplicationPrivate::obey_desktop_settings = on;
+}
+
+/*!
+ Returns true if Qt is set to use the system's standard colors, fonts, etc.;
+ otherwise returns false. The default is true.
+
+ \sa setDesktopSettingsAware()
+*/
+bool QApplication::desktopSettingsAware()
+{
+ return QApplicationPrivate::obey_desktop_settings;
+}
+
+/*!
+ Returns the current state of the modifier keys on the keyboard. The current
+ state is updated sychronously as the event queue is emptied of events that
+ will spontaneously change the keyboard state (QEvent::KeyPress and
+ QEvent::KeyRelease events).
+
+ It should be noted this may not reflect the actual keys held on the input
+ device at the time of calling but rather the modifiers as last reported in
+ one of the above events. If no keys are being held Qt::NoModifier is
+ returned.
+
+ \sa mouseButtons()
+*/
+
+Qt::KeyboardModifiers QApplication::keyboardModifiers()
+{
+ return QApplicationPrivate::modifier_buttons;
+}
+
+/*!
+ Returns the current state of the buttons on the mouse. The current state is
+ updated syncronously as the event queue is emptied of events that will
+ spontaneously change the mouse state (QEvent::MouseButtonPress and
+ QEvent::MouseButtonRelease events).
+
+ It should be noted this may not reflect the actual buttons held on the
+ input device at the time of calling but rather the mouse buttons as last
+ reported in one of the above events. If no mouse buttons are being held
+ Qt::NoButton is returned.
+
+ \sa keyboardModifiers()
+*/
+
+Qt::MouseButtons QApplication::mouseButtons()
+{
+ return QApplicationPrivate::mouse_buttons;
+}
+
+/*!
+ \fn bool QApplication::isSessionRestored() const
+
+ Returns true if the application has been restored from an earlier
+ \l{Session Management}{session}; otherwise returns false.
+
+ \sa sessionId(), commitData(), saveState()
+*/
+
+
+/*!
+ \fn QString QApplication::sessionId() const
+
+ Returns the current \l{Session Management}{session's} identifier.
+
+ If the application has been restored from an earlier session, this
+ identifier is the same as it was in that previous session. The session
+ identifier is guaranteed to be unique both for different applications
+ and for different instances of the same application.
+
+ \sa isSessionRestored(), sessionKey(), commitData(), saveState()
+*/
+
+/*!
+ \fn QString QApplication::sessionKey() const
+
+ Returns the session key in the current \l{Session Management}{session}.
+
+ If the application has been restored from an earlier session, this key is
+ the same as it was when the previous session ended.
+
+ The session key changes with every call of commitData() or saveState().
+
+ \sa isSessionRestored(), sessionId(), commitData(), saveState()
+*/
+#ifndef QT_NO_SESSIONMANAGER
+bool QApplication::isSessionRestored() const
+{
+ Q_D(const QApplication);
+ return d->is_session_restored;
+}
+
+QString QApplication::sessionId() const
+{
+ Q_D(const QApplication);
+ return d->session_id;
+}
+
+QString QApplication::sessionKey() const
+{
+ Q_D(const QApplication);
+ return d->session_key;
+}
+#endif
+
+
+
+/*!
+ \since 4.2
+ \fn void QApplication::commitDataRequest(QSessionManager &manager)
+
+ This signal deals with \l{Session Management}{session management}. It is
+ emitted when the QSessionManager wants the application to commit all its
+ data.
+
+ Usually this means saving all open files, after getting permission from
+ the user. Furthermore you may want to provide a means by which the user
+ can cancel the shutdown.
+
+ You should not exit the application within this signal. Instead,
+ the session manager may or may not do this afterwards, depending on the
+ context.
+
+ \warning Within this signal, no user interaction is possible, \e
+ unless you ask the \a manager for explicit permission. See
+ QSessionManager::allowsInteraction() and
+ QSessionManager::allowsErrorInteraction() for details and example
+ usage.
+
+ \note You should use Qt::DirectConnection when connecting to this signal.
+
+ \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
+*/
+
+/*!
+ This function deals with \l{Session Management}{session management}. It is
+ invoked when the QSessionManager wants the application to commit all its
+ data.
+
+ Usually this means saving all open files, after getting permission from the
+ user. Furthermore you may want to provide a means by which the user can
+ cancel the shutdown.
+
+ You should not exit the application within this function. Instead, the
+ session manager may or may not do this afterwards, depending on the
+ context.
+
+ \warning Within this function, no user interaction is possible, \e
+ unless you ask the \a manager for explicit permission. See
+ QSessionManager::allowsInteraction() and
+ QSessionManager::allowsErrorInteraction() for details and example
+ usage.
+
+ The default implementation requests interaction and sends a close event to
+ all visible top-level widgets. If any event was rejected, the shutdown is
+ canceled.
+
+ \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
+*/
+#ifndef QT_NO_SESSIONMANAGER
+void QApplication::commitData(QSessionManager& manager )
+{
+ emit commitDataRequest(manager);
+ if (manager.allowsInteraction()) {
+ QWidgetList done;
+ QWidgetList list = QApplication::topLevelWidgets();
+ bool cancelled = false;
+ for (int i = 0; !cancelled && i < list.size(); ++i) {
+ QWidget* w = list.at(i);
+ if (w->isVisible() && !done.contains(w)) {
+ cancelled = !w->close();
+ if (!cancelled)
+ done.append(w);
+ list = QApplication::topLevelWidgets();
+ i = -1;
+ }
+ }
+ if (cancelled)
+ manager.cancel();
+ }
+}
+
+/*!
+ \since 4.2
+ \fn void QApplication::saveStateRequest(QSessionManager &manager)
+
+ This signal deals with \l{Session Management}{session management}. It is
+ invoked when the \l{QSessionManager}{session manager} wants the application
+ to preserve its state for a future session.
+
+ For example, a text editor would create a temporary file that includes the
+ current contents of its edit buffers, the location of the cursor and other
+ aspects of the current editing session.
+
+ You should never exit the application within this signal. Instead, the
+ session manager may or may not do this afterwards, depending on the
+ context. Futhermore, most session managers will very likely request a saved
+ state immediately after the application has been started. This permits the
+ session manager to learn about the application's restart policy.
+
+ \warning Within this function, no user interaction is possible, \e
+ unless you ask the \a manager for explicit permission. See
+ QSessionManager::allowsInteraction() and
+ QSessionManager::allowsErrorInteraction() for details.
+
+ \note You should use Qt::DirectConnection when connecting to this signal.
+
+ \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
+*/
+
+/*!
+ This function deals with \l{Session Management}{session management}. It is
+ invoked when the \l{QSessionManager}{session manager} wants the application
+ to preserve its state for a future session.
+
+ For example, a text editor would create a temporary file that includes the
+ current contents of its edit buffers, the location of the cursor and other
+ aspects of the current editing session.
+
+ You should never exit the application within this function. Instead, the
+ session manager may or may not do this afterwards, depending on the
+ context. Futhermore, most session managers will very likely request a saved
+ state immediately after the application has been started. This permits the
+ session manager to learn about the application's restart policy.
+
+ \warning Within this function, no user interaction is possible, \e
+ unless you ask the \a manager for explicit permission. See
+ QSessionManager::allowsInteraction() and
+ QSessionManager::allowsErrorInteraction() for details.
+
+ \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
+*/
+
+void QApplication::saveState(QSessionManager &manager)
+{
+ emit saveStateRequest(manager);
+}
+#endif //QT_NO_SESSIONMANAGER
+/*
+ Sets the time after which a drag should start to \a ms ms.
+
+ \sa startDragTime()
+*/
+
+void QApplication::setStartDragTime(int ms)
+{
+ drag_time = ms;
+}
+
+/*!
+ \property QApplication::startDragTime
+ \brief the time in milliseconds that a mouse button must be held down
+ before a drag and drop operation will begin
+
+ If you support drag and drop in your application, and want to start a drag
+ and drop operation after the user has held down a mouse button for a
+ certain amount of time, you should use this property's value as the delay.
+
+ Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for
+ starting a drag.
+
+ The default value is 500 ms.
+
+ \sa startDragDistance(), {Drag and Drop}
+*/
+
+int QApplication::startDragTime()
+{
+ return drag_time;
+}
+
+/*
+ Sets the distance after which a drag should start to \a l pixels.
+
+ \sa startDragDistance()
+*/
+
+void QApplication::setStartDragDistance(int l)
+{
+ drag_distance = l;
+}
+
+/*!
+ \property QApplication::startDragDistance
+
+ If you support drag and drop in your application, and want to start a drag
+ and drop operation after the user has moved the cursor a certain distance
+ with a button held down, you should use this property's value as the
+ minimum distance required.
+
+ For example, if the mouse position of the click is stored in \c startPos
+ and the current position (e.g. in the mouse move event) is \c currentPos,
+ you can find out if a drag should be started with code like this:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 7
+
+ Qt uses this value internally, e.g. in QFileDialog.
+
+ The default value is 4 pixels.
+
+ \sa startDragTime() QPoint::manhattanLength() {Drag and Drop}
+*/
+
+int QApplication::startDragDistance()
+{
+ return drag_distance;
+}
+
+/*!
+ \fn void QApplication::setReverseLayout(bool reverse)
+
+ Use setLayoutDirection() instead.
+*/
+
+/*!
+ \fn void QApplication::reverseLayout()
+
+ Use layoutDirection() instead.
+*/
+
+/*!
+ \fn bool QApplication::isRightToLeft()
+
+ Returns true if the application's layout direction is
+ Qt::RightToLeft; otherwise returns false.
+
+ \sa layoutDirection(), isLeftToRight()
+*/
+
+/*!
+ \fn bool QApplication::isLeftToRight()
+
+ Returns true if the application's layout direction is
+ Qt::LeftToRight; otherwise returns false.
+
+ \sa layoutDirection(), isRightToLeft()
+*/
+
+/*!
+ \property QApplication::layoutDirection
+ \brief the default layout direction for this application
+
+ On system start-up, the default layout direction depends on the
+ application's language.
+
+ \sa QWidget::layoutDirection, isLeftToRight(), isRightToLeft()
+ */
+
+void QApplication::setLayoutDirection(Qt::LayoutDirection direction)
+{
+ if (layout_direction == direction || direction == Qt::LayoutDirectionAuto)
+ return;
+
+ layout_direction = direction;
+
+ QWidgetList list = topLevelWidgets();
+ for (int i = 0; i < list.size(); ++i) {
+ QWidget *w = list.at(i);
+ QEvent ev(QEvent::ApplicationLayoutDirectionChange);
+ sendEvent(w, &ev);
+ }
+}
+
+Qt::LayoutDirection QApplication::layoutDirection()
+{
+ return layout_direction;
+}
+
+
+/*!
+ \obsolete
+
+ Strips out vertical alignment flags and transforms an alignment \a align
+ of Qt::AlignLeft into Qt::AlignLeft or Qt::AlignRight according to the
+ language used.
+*/
+
+#ifdef QT3_SUPPORT
+Qt::Alignment QApplication::horizontalAlignment(Qt::Alignment align)
+{
+ return QStyle::visualAlignment(layoutDirection(), align);
+}
+#endif
+
+
+/*!
+ \fn QCursor *QApplication::overrideCursor()
+
+ Returns the active application override cursor.
+
+ This function returns 0 if no application cursor has been defined (i.e. the
+ internal cursor stack is empty).
+
+ \sa setOverrideCursor(), restoreOverrideCursor()
+*/
+#ifndef QT_NO_CURSOR
+QCursor *QApplication::overrideCursor()
+{
+ return qApp->d_func()->cursor_list.isEmpty() ? 0 : &qApp->d_func()->cursor_list.first();
+}
+
+/*!
+ Changes the currently active application override cursor to \a cursor.
+
+ This function has no effect if setOverrideCursor() was not called.
+
+ \sa setOverrideCursor(), overrideCursor(), restoreOverrideCursor(),
+ QWidget::setCursor()
+ */
+void QApplication::changeOverrideCursor(const QCursor &cursor)
+{
+ if (qApp->d_func()->cursor_list.isEmpty())
+ return;
+ qApp->d_func()->cursor_list.removeFirst();
+ setOverrideCursor(cursor);
+}
+#endif
+
+/*!
+ \fn void QApplication::setOverrideCursor(const QCursor &cursor, bool replace)
+
+ Use changeOverrideCursor(\a cursor) (if \a replace is true) or
+ setOverrideCursor(\a cursor) (if \a replace is false).
+*/
+
+/*!
+ Enters the main event loop and waits until exit() is called, then returns
+ the value that was set to exit() (which is 0 if exit() is called via
+ quit()).
+
+ It is necessary to call this function to start event handling. The main
+ event loop receives events from the window system and dispatches these to
+ the application widgets.
+
+ Generally, no user interaction can take place before calling exec(). As a
+ special case, modal widgets like QMessageBox can be used before calling
+ exec(), because modal widgets call exec() to start a local event loop.
+
+ To make your application perform idle processing, i.e., executing a special
+ function whenever there are no pending events, use a QTimer with 0 timeout.
+ More advanced idle processing schemes can be achieved using processEvents().
+
+ We recommend that you connect clean-up code to the
+ \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
+ application's \c{main()} function. This is because, on some platforms the
+ QApplication::exec() call may not return. For example, on the Windows
+ platform, when the user logs off, the system terminates the process after Qt
+ closes all top-level windows. Hence, there is \e{no guarantee} that the
+ application will have time to exit its event loop and execute code at the
+ end of the \c{main()} function, after the QApplication::exec() call.
+
+ \sa quitOnLastWindowClosed, quit(), exit(), processEvents(),
+ QCoreApplication::exec()
+*/
+int QApplication::exec()
+{
+#ifndef QT_NO_ACCESSIBILITY
+ QAccessible::setRootObject(qApp);
+#endif
+ return QCoreApplication::exec();
+}
+
+/*! \reimp
+ */
+bool QApplication::notify(QObject *receiver, QEvent *e)
+{
+ Q_D(QApplication);
+ // no events are delivered after ~QCoreApplication() has started
+ if (QApplicationPrivate::is_app_closing)
+ return true;
+
+ if (receiver == 0) { // serious error
+ qWarning("QApplication::notify: Unexpected null receiver");
+ return true;
+ }
+
+#ifndef QT_NO_DEBUG
+ d->checkReceiverThread(receiver);
+#endif
+
+ // capture the current mouse/keyboard state
+ if(e->spontaneous()) {
+ if (e->type() == QEvent::KeyPress
+ || e->type() == QEvent::KeyRelease) {
+ QKeyEvent *ke = static_cast<QKeyEvent*>(e);
+ QApplicationPrivate::modifier_buttons = ke->modifiers();
+ } else if(e->type() == QEvent::MouseButtonPress
+ || e->type() == QEvent::MouseButtonRelease) {
+ QMouseEvent *me = static_cast<QMouseEvent*>(e);
+ QApplicationPrivate::modifier_buttons = me->modifiers();
+ if(me->type() == QEvent::MouseButtonPress)
+ QApplicationPrivate::mouse_buttons |= me->button();
+ else
+ QApplicationPrivate::mouse_buttons &= ~me->button();
+ }
+#if !defined(QT_NO_WHEELEVENT) || !defined(QT_NO_TABLETEVENT)
+ else if (false
+# ifndef QT_NO_WHEELEVENT
+ || e->type() == QEvent::Wheel
+# endif
+# ifndef QT_NO_TABLETEVENT
+ || e->type() == QEvent::TabletMove
+ || e->type() == QEvent::TabletPress
+ || e->type() == QEvent::TabletRelease
+# endif
+ ) {
+ QInputEvent *ie = static_cast<QInputEvent*>(e);
+ QApplicationPrivate::modifier_buttons = ie->modifiers();
+ }
+#endif // !QT_NO_WHEELEVENT || !QT_NO_TABLETEVENT
+ }
+
+#ifndef QT_NO_GESTURES
+ // walk through parents and check for gestures
+ if (d->gestureManager) {
+ switch (e->type()) {
+ case QEvent::Paint:
+ case QEvent::MetaCall:
+ case QEvent::DeferredDelete:
+ case QEvent::DragEnter: case QEvent::DragMove: case QEvent::DragLeave:
+ case QEvent::Drop: case QEvent::DragResponse:
+ case QEvent::ChildAdded: case QEvent::ChildPolished:
+#ifdef QT3_SUPPORT
+ case QEvent::ChildInsertedRequest:
+ case QEvent::ChildInserted:
+ case QEvent::LayoutHint:
+#endif
+ case QEvent::ChildRemoved:
+ case QEvent::UpdateRequest:
+ case QEvent::UpdateLater:
+ case QEvent::AccessibilityPrepare:
+ case QEvent::LocaleChange:
+ case QEvent::Style:
+ case QEvent::IconDrag:
+ case QEvent::StyleChange:
+ case QEvent::AccessibilityHelp:
+ case QEvent::AccessibilityDescription:
+ case QEvent::GraphicsSceneDragEnter:
+ case QEvent::GraphicsSceneDragMove:
+ case QEvent::GraphicsSceneDragLeave:
+ case QEvent::GraphicsSceneDrop:
+ case QEvent::DynamicPropertyChange:
+ case QEvent::NetworkReplyUpdated:
+ break;
+ default:
+ if (receiver->isWidgetType()) {
+ if (d->gestureManager->filterEvent(static_cast<QWidget *>(receiver), e))
+ return true;
+ } else {
+ // a special case for events that go to QGesture objects.
+ // We pass the object to the gesture manager and it'll figure
+ // out if it's QGesture or not.
+ if (d->gestureManager->filterEvent(receiver, e))
+ return true;
+ }
+ }
+ }
+#endif // QT_NO_GESTURES
+
+ // User input and window activation makes tooltips sleep
+ switch (e->type()) {
+ case QEvent::Wheel:
+ case QEvent::ActivationChange:
+ case QEvent::KeyPress:
+ case QEvent::KeyRelease:
+ case QEvent::FocusOut:
+ case QEvent::FocusIn:
+ case QEvent::MouseButtonPress:
+ case QEvent::MouseButtonRelease:
+ case QEvent::MouseButtonDblClick:
+ d->toolTipFallAsleep.stop();
+ // fall-through
+ case QEvent::Leave:
+ d->toolTipWakeUp.stop();
+ default:
+ break;
+ }
+
+ bool res = false;
+ if (!receiver->isWidgetType()) {
+ res = d->notify_helper(receiver, e);
+ } else switch (e->type()) {
+#if defined QT3_SUPPORT && !defined(QT_NO_SHORTCUT)
+ case QEvent::Accel:
+ {
+ if (d->use_compat()) {
+ QKeyEvent* key = static_cast<QKeyEvent*>(e);
+ res = d->notify_helper(receiver, e);
+
+ if (!res && !key->isAccepted())
+ res = d->qt_dispatchAccelEvent(static_cast<QWidget *>(receiver), key);
+
+ // next lines are for compatibility with Qt <= 3.0.x: old
+ // QAccel was listening on toplevel widgets
+ if (!res && !key->isAccepted() && !static_cast<QWidget *>(receiver)->isWindow())
+ res = d->notify_helper(static_cast<QWidget *>(receiver)->window(), e);
+ }
+ break;
+ }
+#endif //QT3_SUPPORT && !QT_NO_SHORTCUT
+ case QEvent::ShortcutOverride:
+ case QEvent::KeyPress:
+ case QEvent::KeyRelease:
+ {
+ bool isWidget = receiver->isWidgetType();
+ bool isGraphicsWidget = false;
+#ifndef QT_NO_GRAPHICSVIEW
+ isGraphicsWidget = !isWidget && qobject_cast<QGraphicsWidget *>(receiver);
+#endif
+ if (!isWidget && !isGraphicsWidget) {
+ res = d->notify_helper(receiver, e);
+ break;
+ }
+
+ QKeyEvent* key = static_cast<QKeyEvent*>(e);
+#if defined QT3_SUPPORT && !defined(QT_NO_SHORTCUT)
+ if (d->use_compat() && d->qt_tryComposeUnicode(static_cast<QWidget*>(receiver), key))
+ break;
+#endif
+ if (key->type()==QEvent::KeyPress) {
+#ifndef QT_NO_SHORTCUT
+ // Try looking for a Shortcut before sending key events
+ if ((res = qApp->d_func()->shortcutMap.tryShortcutEvent(receiver, key)))
+ return res;
+#endif
+ qt_in_tab_key_event = (key->key() == Qt::Key_Backtab
+ || key->key() == Qt::Key_Tab
+ || key->key() == Qt::Key_Left
+ || key->key() == Qt::Key_Up
+ || key->key() == Qt::Key_Right
+ || key->key() == Qt::Key_Down);
+ }
+ bool def = key->isAccepted();
+ QPointer<QObject> pr = receiver;
+ while (receiver) {
+ if (def)
+ key->accept();
+ else
+ key->ignore();
+ res = d->notify_helper(receiver, e);
+ QWidget *w = isWidget ? static_cast<QWidget *>(receiver) : 0;
+#ifndef QT_NO_GRAPHICSVIEW
+ QGraphicsWidget *gw = isGraphicsWidget ? static_cast<QGraphicsWidget *>(receiver) : 0;
+#endif
+
+ if ((res && key->isAccepted())
+ /*
+ QLineEdit will emit a signal on Key_Return, but
+ ignore the event, and sometimes the connected
+ slot deletes the QLineEdit (common in itemview
+ delegates), so we have to check if the widget
+ was destroyed even if the event was ignored (to
+ prevent a crash)
+
+ note that we don't have to reset pw while
+ propagating (because the original receiver will
+ be destroyed if one of its ancestors is)
+ */
+ || !pr
+ || (isWidget && (w->isWindow() || !w->parentWidget()))
+#ifndef QT_NO_GRAPHICSVIEW
+ || (isGraphicsWidget && (gw->isWindow() || !gw->parentWidget()))
+#endif
+ ) {
+ break;
+ }
+
+#ifndef QT_NO_GRAPHICSVIEW
+ receiver = w ? (QObject *)w->parentWidget() : (QObject *)gw->parentWidget();
+#else
+ receiver = w->parentWidget();
+#endif
+ }
+ qt_in_tab_key_event = false;
+ }
+ break;
+ case QEvent::MouseButtonPress:
+ case QEvent::MouseButtonRelease:
+ case QEvent::MouseButtonDblClick:
+ case QEvent::MouseMove:
+ {
+ QWidget* w = static_cast<QWidget *>(receiver);
+
+ QMouseEvent* mouse = static_cast<QMouseEvent*>(e);
+ QPoint relpos = mouse->pos();
+
+ if (e->spontaneous()) {
+#ifndef QT_NO_IM
+ QInputContext *ic = w->inputContext();
+ if (ic
+ && w->testAttribute(Qt::WA_InputMethodEnabled)
+ && ic->filterEvent(mouse))
+ return true;
+#endif
+
+ if (e->type() == QEvent::MouseButtonPress) {
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
+ Qt::ClickFocus,
+ Qt::MouseFocusReason);
+ }
+
+ // ### Qt 5 These dynamic tool tips should be an OPT-IN feature. Some platforms
+ // like Mac OS X (probably others too), can optimize their views by not
+ // dispatching mouse move events. We have attributes to control hover,
+ // and mouse tracking, but as long as we are deciding to implement this
+ // feature without choice of opting-in or out, you ALWAYS have to have
+ // tracking enabled. Therefore, the other properties give a false sense of
+ // performance enhancement.
+ if (e->type() == QEvent::MouseMove && mouse->buttons() == 0) {
+ d->toolTipWidget = w;
+ d->toolTipPos = relpos;
+ d->toolTipGlobalPos = mouse->globalPos();
+ d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive()?20:700, this);
+ }
+ }
+
+ bool eventAccepted = mouse->isAccepted();
+
+ QPointer<QWidget> pw = w;
+ while (w) {
+ QMouseEvent me(mouse->type(), relpos, mouse->globalPos(), mouse->button(), mouse->buttons(),
+ mouse->modifiers());
+ me.spont = mouse->spontaneous();
+ // throw away any mouse-tracking-only mouse events
+ if (!w->hasMouseTracking()
+ && mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
+ // but still send them through all application event filters (normally done by notify_helper)
+ for (int i = 0; i < d->eventFilters.size(); ++i) {
+ register QObject *obj = d->eventFilters.at(i);
+ if (!obj)
+ continue;
+ if (obj->d_func()->threadData != w->d_func()->threadData) {
+ qWarning("QApplication: Object event filter cannot be in a different thread.");
+ continue;
+ }
+ if (obj->eventFilter(w, w == receiver ? mouse : &me))
+ break;
+ }
+ res = true;
+ } else {
+ w->setAttribute(Qt::WA_NoMouseReplay, false);
+ res = d->notify_helper(w, w == receiver ? mouse : &me);
+ e->spont = false;
+ }
+ eventAccepted = (w == receiver ? mouse : &me)->isAccepted();
+ if (res && eventAccepted)
+ break;
+ if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
+ break;
+ relpos += w->pos();
+ w = w->parentWidget();
+ }
+
+ mouse->setAccepted(eventAccepted);
+
+ if (e->type() == QEvent::MouseMove) {
+ if (!pw)
+ break;
+
+ w = static_cast<QWidget *>(receiver);
+ relpos = mouse->pos();
+ QPoint diff = relpos - w->mapFromGlobal(d->hoverGlobalPos);
+ while (w) {
+ if (w->testAttribute(Qt::WA_Hover) &&
+ (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
+ QHoverEvent he(QEvent::HoverMove, relpos, relpos - diff);
+ d->notify_helper(w, &he);
+ }
+ if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
+ break;
+ relpos += w->pos();
+ w = w->parentWidget();
+ }
+ }
+
+ d->hoverGlobalPos = mouse->globalPos();
+ }
+ break;
+#ifndef QT_NO_WHEELEVENT
+ case QEvent::Wheel:
+ {
+ QWidget* w = static_cast<QWidget *>(receiver);
+ QWheelEvent* wheel = static_cast<QWheelEvent*>(e);
+ QPoint relpos = wheel->pos();
+ bool eventAccepted = wheel->isAccepted();
+
+ if (e->spontaneous()) {
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
+ Qt::WheelFocus,
+ Qt::MouseFocusReason);
+ }
+
+ while (w) {
+ QWheelEvent we(relpos, wheel->globalPos(), wheel->delta(), wheel->buttons(),
+ wheel->modifiers(), wheel->orientation());
+ we.spont = wheel->spontaneous();
+ res = d->notify_helper(w, w == receiver ? wheel : &we);
+ eventAccepted = ((w == receiver) ? wheel : &we)->isAccepted();
+ e->spont = false;
+ if ((res && eventAccepted)
+ || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
+ break;
+
+ relpos += w->pos();
+ w = w->parentWidget();
+ }
+ wheel->setAccepted(eventAccepted);
+ }
+ break;
+#endif
+#ifndef QT_NO_CONTEXTMENU
+ case QEvent::ContextMenu:
+ {
+ QWidget* w = static_cast<QWidget *>(receiver);
+ QContextMenuEvent *context = static_cast<QContextMenuEvent*>(e);
+ QPoint relpos = context->pos();
+ bool eventAccepted = context->isAccepted();
+ while (w) {
+ QContextMenuEvent ce(context->reason(), relpos, context->globalPos(), context->modifiers());
+ ce.spont = e->spontaneous();
+ res = d->notify_helper(w, w == receiver ? context : &ce);
+ eventAccepted = ((w == receiver) ? context : &ce)->isAccepted();
+ e->spont = false;
+
+ if ((res && eventAccepted)
+ || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
+ break;
+
+ relpos += w->pos();
+ w = w->parentWidget();
+ }
+ context->setAccepted(eventAccepted);
+ }
+ break;
+#endif // QT_NO_CONTEXTMENU
+#ifndef QT_NO_TABLETEVENT
+ case QEvent::TabletMove:
+ case QEvent::TabletPress:
+ case QEvent::TabletRelease:
+ {
+ QWidget *w = static_cast<QWidget *>(receiver);
+ QTabletEvent *tablet = static_cast<QTabletEvent*>(e);
+ QPoint relpos = tablet->pos();
+ bool eventAccepted = tablet->isAccepted();
+ while (w) {
+ QTabletEvent te(tablet->type(), relpos, tablet->globalPos(),
+ tablet->hiResGlobalPos(), tablet->device(), tablet->pointerType(),
+ tablet->pressure(), tablet->xTilt(), tablet->yTilt(),
+ tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
+ tablet->modifiers(), tablet->uniqueId());
+ te.spont = e->spontaneous();
+ res = d->notify_helper(w, w == receiver ? tablet : &te);
+ eventAccepted = ((w == receiver) ? tablet : &te)->isAccepted();
+ e->spont = false;
+ if ((res && eventAccepted)
+ || w->isWindow()
+ || w->testAttribute(Qt::WA_NoMousePropagation))
+ break;
+
+ relpos += w->pos();
+ w = w->parentWidget();
+ }
+ tablet->setAccepted(eventAccepted);
+ qt_tabletChokeMouse = tablet->isAccepted();
+ }
+ break;
+#endif // QT_NO_TABLETEVENT
+
+#if !defined(QT_NO_TOOLTIP) || !defined(QT_NO_WHATSTHIS)
+ case QEvent::ToolTip:
+ case QEvent::WhatsThis:
+ case QEvent::QueryWhatsThis:
+ {
+ QWidget* w = static_cast<QWidget *>(receiver);
+ QHelpEvent *help = static_cast<QHelpEvent*>(e);
+ QPoint relpos = help->pos();
+ bool eventAccepted = help->isAccepted();
+ while (w) {
+ QHelpEvent he(help->type(), relpos, help->globalPos());
+ he.spont = e->spontaneous();
+ res = d->notify_helper(w, w == receiver ? help : &he);
+ e->spont = false;
+ eventAccepted = (w == receiver ? help : &he)->isAccepted();
+ if ((res && eventAccepted) || w->isWindow())
+ break;
+
+ relpos += w->pos();
+ w = w->parentWidget();
+ }
+ help->setAccepted(eventAccepted);
+ }
+ break;
+#endif
+#if !defined(QT_NO_STATUSTIP) || !defined(QT_NO_WHATSTHIS)
+ case QEvent::StatusTip:
+ case QEvent::WhatsThisClicked:
+ {
+ QWidget *w = static_cast<QWidget *>(receiver);
+ while (w) {
+ res = d->notify_helper(w, e);
+ if ((res && e->isAccepted()) || w->isWindow())
+ break;
+ w = w->parentWidget();
+ }
+ }
+ break;
+#endif
+
+#ifndef QT_NO_DRAGANDDROP
+ case QEvent::DragEnter: {
+ QWidget* w = static_cast<QWidget *>(receiver);
+ QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent *>(e);
+#ifdef Q_WS_MAC
+ // HIView has a slight difference in how it delivers events to children and parents
+ // It will not give a leave to a child's parent when it enters a child.
+ QWidget *currentTarget = QDragManager::self()->currentTarget();
+ if (currentTarget) {
+ // Assume currentTarget did not get a leave
+ QDragLeaveEvent event;
+ QApplication::sendEvent(currentTarget, &event);
+ }
+#endif
+#ifndef QT_NO_GRAPHICSVIEW
+ // QGraphicsProxyWidget handles its own propagation,
+ // and we must not change QDragManagers currentTarget.
+ QWExtra *extra = w->window()->d_func()->extra;
+ if (extra && extra->proxyWidget) {
+ res = d->notify_helper(w, dragEvent);
+ break;
+ }
+#endif
+ while (w) {
+ if (w->isEnabled() && w->acceptDrops()) {
+ res = d->notify_helper(w, dragEvent);
+ if (res && dragEvent->isAccepted()) {
+ QDragManager::self()->setCurrentTarget(w);
+ break;
+ }
+ }
+ if (w->isWindow())
+ break;
+ dragEvent->p = w->mapToParent(dragEvent->p);
+ w = w->parentWidget();
+ }
+ }
+ break;
+ case QEvent::DragMove:
+ case QEvent::Drop:
+ case QEvent::DragLeave: {
+ QWidget* w = static_cast<QWidget *>(receiver);
+#ifndef QT_NO_GRAPHICSVIEW
+ // QGraphicsProxyWidget handles its own propagation,
+ // and we must not change QDragManagers currentTarget.
+ QWExtra *extra = w->window()->d_func()->extra;
+ bool isProxyWidget = extra && extra->proxyWidget;
+ if (!isProxyWidget)
+#endif
+ w = QDragManager::self()->currentTarget();
+
+ if (!w) {
+#ifdef Q_WS_MAC
+ // HIView has a slight difference in how it delivers events to children and parents
+ // It will not give an enter to a child's parent when it leaves the child.
+ if (e->type() == QEvent::DragLeave)
+ break;
+ // Assume that w did not get an enter.
+ QDropEvent *dropEvent = static_cast<QDropEvent *>(e);
+ QDragEnterEvent dragEnterEvent(dropEvent->pos(), dropEvent->possibleActions(),
+ dropEvent->mimeData(), dropEvent->mouseButtons(),
+ dropEvent->keyboardModifiers());
+ QApplication::sendEvent(receiver, &dragEnterEvent);
+ w = QDragManager::self()->currentTarget();
+ if (!w)
+#endif
+ break;
+ }
+ if (e->type() == QEvent::DragMove || e->type() == QEvent::Drop) {
+ QDropEvent *dragEvent = static_cast<QDropEvent *>(e);
+ QWidget *origReciver = static_cast<QWidget *>(receiver);
+ while (origReciver && w != origReciver) {
+ dragEvent->p = origReciver->mapToParent(dragEvent->p);
+ origReciver = origReciver->parentWidget();
+ }
+ }
+ res = d->notify_helper(w, e);
+ if (e->type() != QEvent::DragMove
+#ifndef QT_NO_GRAPHICSVIEW
+ && !isProxyWidget
+#endif
+ )
+ QDragManager::self()->setCurrentTarget(0, e->type() == QEvent::Drop);
+ }
+ break;
+#endif
+ case QEvent::TouchBegin:
+ // Note: TouchUpdate and TouchEnd events are never propagated
+ {
+ QWidget *widget = static_cast<QWidget *>(receiver);
+ QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
+ bool eventAccepted = touchEvent->isAccepted();
+ if (widget->testAttribute(Qt::WA_AcceptTouchEvents) && e->spontaneous()) {
+ // give the widget focus if the focus policy allows it
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget,
+ Qt::ClickFocus,
+ Qt::MouseFocusReason);
+ }
+
+ while (widget) {
+ // first, try to deliver the touch event
+ bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
+ touchEvent->setWidget(widget);
+ touchEvent->setAccepted(acceptTouchEvents);
+ QWeakPointer<QWidget> p = widget;
+ res = acceptTouchEvents && d->notify_helper(widget, touchEvent);
+ eventAccepted = touchEvent->isAccepted();
+ if (p.isNull()) {
+ // widget was deleted
+ widget = 0;
+ } else {
+ widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
+ }
+ touchEvent->spont = false;
+ if (res && eventAccepted) {
+ // the first widget to accept the TouchBegin gets an implicit grab.
+ for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
+ const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i);
+ d->widgetForTouchPointId[touchPoint.id()] = widget;
+ }
+ break;
+ } else if (p.isNull() || widget->isWindow() || widget->testAttribute(Qt::WA_NoMousePropagation)) {
+ break;
+ }
+ QPoint offset = widget->pos();
+ widget = widget->parentWidget();
+ touchEvent->setWidget(widget);
+ for (int i = 0; i < touchEvent->_touchPoints.size(); ++i) {
+ QTouchEvent::TouchPoint &pt = touchEvent->_touchPoints[i];
+ QRectF rect = pt.rect();
+ rect.moveCenter(offset);
+ pt.d->rect = rect;
+ pt.d->startPos = pt.startPos() + offset;
+ pt.d->lastPos = pt.lastPos() + offset;
+ }
+ }
+
+ touchEvent->setAccepted(eventAccepted);
+ break;
+ }
+ case QEvent::RequestSoftwareInputPanel:
+ case QEvent::CloseSoftwareInputPanel:
+#ifndef QT_NO_IM
+ if (receiver->isWidgetType()) {
+ QWidget *w = static_cast<QWidget *>(receiver);
+ QInputContext *ic = w->inputContext();
+ if (ic && ic->filterEvent(e)) {
+ break;
+ }
+ }
+#endif
+ res = d->notify_helper(receiver, e);
+ break;
+
+#ifndef QT_NO_GESTURES
+ case QEvent::NativeGesture:
+ {
+ // only propagate the first gesture event (after the GID_BEGIN)
+ QWidget *w = static_cast<QWidget *>(receiver);
+ while (w) {
+ e->ignore();
+ res = d->notify_helper(w, e);
+ if ((res && e->isAccepted()) || w->isWindow())
+ break;
+ w = w->parentWidget();
+ }
+ break;
+ }
+ case QEvent::Gesture:
+ case QEvent::GestureOverride:
+ {
+ if (receiver->isWidgetType()) {
+ QWidget *w = static_cast<QWidget *>(receiver);
+ QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(e);
+ QList<QGesture *> allGestures = gestureEvent->gestures();
+
+ bool eventAccepted = gestureEvent->isAccepted();
+ bool wasAccepted = eventAccepted;
+ while (w) {
+ // send only gestures the widget expects
+ QList<QGesture *> gestures;
+ QWidgetPrivate *wd = w->d_func();
+ for (int i = 0; i < allGestures.size();) {
+ QGesture *g = allGestures.at(i);
+ Qt::GestureType type = g->gestureType();
+ QMap<Qt::GestureType, Qt::GestureFlags>::iterator contextit =
+ wd->gestureContext.find(type);
+ bool deliver = contextit != wd->gestureContext.end() &&
+ (g->state() == Qt::GestureStarted || w == receiver ||
+ (contextit.value() & Qt::ReceivePartialGestures));
+ if (deliver) {
+ allGestures.removeAt(i);
+ gestures.append(g);
+ } else {
+ ++i;
+ }
+ }
+ if (!gestures.isEmpty()) { // we have gestures for this w
+ QGestureEvent ge(gestures);
+ ge.t = gestureEvent->t;
+ ge.spont = gestureEvent->spont;
+ ge.m_accept = wasAccepted;
+ ge.d_func()->accepted = gestureEvent->d_func()->accepted;
+ res = d->notify_helper(w, &ge);
+ gestureEvent->spont = false;
+ eventAccepted = ge.isAccepted();
+ for (int i = 0; i < gestures.size(); ++i) {
+ QGesture *g = gestures.at(i);
+ // Ignore res [event return value] because handling of multiple gestures
+ // packed into a single QEvent depends on not consuming the event
+ if (eventAccepted || ge.isAccepted(g)) {
+ // if the gesture was accepted, mark the target widget for it
+ gestureEvent->d_func()->targetWidgets[g->gestureType()] = w;
+ gestureEvent->setAccepted(g, true);
+ } else {
+ // if the gesture was explicitly ignored by the application,
+ // put it back so a parent can get it
+ allGestures.append(g);
+ }
+ }
+ }
+ if (allGestures.isEmpty()) // everything delivered
+ break;
+ if (w->isWindow())
+ break;
+ w = w->parentWidget();
+ }
+ foreach (QGesture *g, allGestures)
+ gestureEvent->setAccepted(g, false);
+ gestureEvent->m_accept = false; // to make sure we check individual gestures
+ } else {
+ res = d->notify_helper(receiver, e);
+ }
+ break;
+ }
+#endif // QT_NO_GESTURES
+#ifdef QT_MAC_USE_COCOA
+ case QEvent::Enter:
+ if (receiver->isWidgetType()) {
+ QWidget *w = static_cast<QWidget *>(receiver);
+ if (w->testAttribute(Qt::WA_AcceptTouchEvents))
+ qt_widget_private(w)->registerTouchWindow(true);
+ }
+ res = d->notify_helper(receiver, e);
+ break;
+ case QEvent::Leave:
+ if (receiver->isWidgetType()) {
+ QWidget *w = static_cast<QWidget *>(receiver);
+ if (w->testAttribute(Qt::WA_AcceptTouchEvents))
+ qt_widget_private(w)->registerTouchWindow(false);
+ }
+ res = d->notify_helper(receiver, e);
+ break;
+#endif
+ default:
+ res = d->notify_helper(receiver, e);
+ break;
+ }
+
+ return res;
+}
+
+bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
+{
+ // send to all application event filters
+ if (sendThroughApplicationEventFilters(receiver, e))
+ return true;
+
+ if (receiver->isWidgetType()) {
+ QWidget *widget = static_cast<QWidget *>(receiver);
+
+#if !defined(Q_WS_WINCE) || (defined(GWES_ICONCURS) && !defined(QT_NO_CURSOR))
+ // toggle HasMouse widget state on enter and leave
+ if ((e->type() == QEvent::Enter || e->type() == QEvent::DragEnter) &&
+ (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == widget->window()))
+ widget->setAttribute(Qt::WA_UnderMouse, true);
+ else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave)
+ widget->setAttribute(Qt::WA_UnderMouse, false);
+#endif
+
+ if (QLayout *layout=widget->d_func()->layout) {
+ layout->widgetEvent(e);
+ }
+ }
+
+ // send to all receiver event filters
+ if (sendThroughObjectEventFilters(receiver, e))
+ return true;
+
+ // deliver the event
+ bool consumed = receiver->event(e);
+ e->spont = false;
+ return consumed;
+}
+
+
+/*!
+ \class QSessionManager
+ \brief The QSessionManager class provides access to the session manager.
+
+ A session manager in a desktop environment (in which Qt GUI applications
+ live) keeps track of a session, which is a group of running applications,
+ each of which has a particular state. The state of an application contains
+ (most notably) the documents the application has open and the position and
+ size of its windows.
+
+ The session manager is used to save the session, e.g., when the machine is
+ shut down, and to restore a session, e.g., when the machine is started up.
+ We recommend that you use QSettings to save an application's settings,
+ for example, window positions, recently used files, etc. When the
+ application is restarted by the session manager, you can restore the
+ settings.
+
+ QSessionManager provides an interface between the application and the
+ session manager so that the program can work well with the session manager.
+ In Qt, session management requests for action are handled by the two
+ virtual functions QApplication::commitData() and QApplication::saveState().
+ Both provide a reference to a session manager object as argument, to allow
+ the application to communicate with the session manager. The session
+ manager can only be accessed through these functions.
+
+ No user interaction is possible \e unless the application gets explicit
+ permission from the session manager. You ask for permission by calling
+ allowsInteraction() or, if it is really urgent, allowsErrorInteraction().
+ Qt does not enforce this, but the session manager may.
+
+ You can try to abort the shutdown process by calling cancel(). The default
+ commitData() function does this if some top-level window rejected its
+ closeEvent().
+
+ For sophisticated session managers provided on Unix/X11, QSessionManager
+ offers further possibilities to fine-tune an application's session
+ management behavior: setRestartCommand(), setDiscardCommand(),
+ setRestartHint(), setProperty(), requestPhase2(). See the respective
+ function descriptions for further details.
+
+ \sa QApplication, {Session Management}
+*/
+
+/*! \enum QSessionManager::RestartHint
+
+ This enum type defines the circumstances under which this application wants
+ to be restarted by the session manager. The current values are:
+
+ \value RestartIfRunning If the application is still running when the
+ session is shut down, it wants to be restarted
+ at the start of the next session.
+
+ \value RestartAnyway The application wants to be started at the
+ start of the next session, no matter what.
+ (This is useful for utilities that run just
+ after startup and then quit.)
+
+ \value RestartImmediately The application wants to be started immediately
+ whenever it is not running.
+
+ \value RestartNever The application does not want to be restarted
+ automatically.
+
+ The default hint is \c RestartIfRunning.
+*/
+
+
+/*!
+ \fn QString QSessionManager::sessionId() const
+
+ Returns the identifier of the current session.
+
+ If the application has been restored from an earlier session, this
+ identifier is the same as it was in the earlier session.
+
+ \sa sessionKey(), QApplication::sessionId()
+*/
+
+/*!
+ \fn QString QSessionManager::sessionKey() const
+
+ Returns the session key in the current session.
+
+ If the application has been restored from an earlier session, this key is
+ the same as it was when the previous session ended.
+
+ The session key changes with every call of commitData() or saveState().
+
+ \sa sessionId(), QApplication::sessionKey()
+*/
+
+/*!
+ \fn void* QSessionManager::handle() const
+
+ \internal
+*/
+
+/*!
+ \fn bool QSessionManager::allowsInteraction()
+
+ Asks the session manager for permission to interact with the user. Returns
+ true if interaction is permitted; otherwise returns false.
+
+ The rationale behind this mechanism is to make it possible to synchronize
+ user interaction during a shutdown. Advanced session managers may ask all
+ applications simultaneously to commit their data, resulting in a much
+ faster shutdown.
+
+ When the interaction is completed we strongly recommend releasing the user
+ interaction semaphore with a call to release(). This way, other
+ applications may get the chance to interact with the user while your
+ application is still busy saving data. (The semaphore is implicitly
+ released when the application exits.)
+
+ If the user decides to cancel the shutdown process during the interaction
+ phase, you must tell the session manager that this has happened by calling
+ cancel().
+
+ Here's an example of how an application's QApplication::commitData() might
+ be implemented:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 8
+
+ If an error occurred within the application while saving its data, you may
+ want to try allowsErrorInteraction() instead.
+
+ \sa QApplication::commitData(), release(), cancel()
+*/
+
+
+/*!
+ \fn bool QSessionManager::allowsErrorInteraction()
+
+ Returns true if error interaction is permitted; otherwise returns false.
+
+ This is similar to allowsInteraction(), but also enables the application to
+ tell the user about any errors that occur. Session managers may give error
+ interaction requests higher priority, which means that it is more likely
+ that an error interaction is permitted. However, you are still not
+ guaranteed that the session manager will allow interaction.
+
+ \sa allowsInteraction(), release(), cancel()
+*/
+
+/*!
+ \fn void QSessionManager::release()
+
+ Releases the session manager's interaction semaphore after an interaction
+ phase.
+
+ \sa allowsInteraction(), allowsErrorInteraction()
+*/
+
+/*!
+ \fn void QSessionManager::cancel()
+
+ Tells the session manager to cancel the shutdown process. Applications
+ should not call this function without asking the user first.
+
+ \sa allowsInteraction(), allowsErrorInteraction()
+*/
+
+/*!
+ \fn void QSessionManager::setRestartHint(RestartHint hint)
+
+ Sets the application's restart hint to \a hint. On application startup, the
+ hint is set to \c RestartIfRunning.
+
+ \note These flags are only hints, a session manager may or may not respect
+ them.
+
+ We recommend setting the restart hint in QApplication::saveState() because
+ most session managers perform a checkpoint shortly after an application's
+ startup.
+
+ \sa restartHint()
+*/
+
+/*!
+ \fn QSessionManager::RestartHint QSessionManager::restartHint() const
+
+ Returns the application's current restart hint. The default is
+ \c RestartIfRunning.
+
+ \sa setRestartHint()
+*/
+
+/*!
+ \fn void QSessionManager::setRestartCommand(const QStringList& command)
+
+ If the session manager is capable of restoring sessions it will execute
+ \a command in order to restore the application. The command defaults to
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 9
+
+ The \c -session option is mandatory; otherwise QApplication cannot tell
+ whether it has been restored or what the current session identifier is.
+ See QApplication::isSessionRestored() and QApplication::sessionId() for
+ details.
+
+ If your application is very simple, it may be possible to store the entire
+ application state in additional command line options. This is usually a
+ very bad idea because command lines are often limited to a few hundred
+ bytes. Instead, use QSettings, temporary files, or a database for this
+ purpose. By marking the data with the unique sessionId(), you will be able
+ to restore the application in a future session.
+
+ \sa restartCommand(), setDiscardCommand(), setRestartHint()
+*/
+
+/*!
+ \fn QStringList QSessionManager::restartCommand() const
+
+ Returns the currently set restart command.
+
+ To iterate over the list, you can use the \l foreach pseudo-keyword:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 10
+
+ \sa setRestartCommand(), restartHint()
+*/
+
+/*!
+ \fn void QSessionManager::setDiscardCommand(const QStringList& list)
+
+ Sets the discard command to the given \a list.
+
+ \sa discardCommand(), setRestartCommand()
+*/
+
+
+/*!
+ \fn QStringList QSessionManager::discardCommand() const
+
+ Returns the currently set discard command.
+
+ To iterate over the list, you can use the \l foreach pseudo-keyword:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 11
+
+ \sa setDiscardCommand(), restartCommand(), setRestartCommand()
+*/
+
+/*!
+ \fn void QSessionManager::setManagerProperty(const QString &name, const QString &value)
+ \overload
+
+ Low-level write access to the application's identification and state
+ records are kept in the session manager.
+
+ The property called \a name has its value set to the string \a value.
+*/
+
+/*!
+ \fn void QSessionManager::setManagerProperty(const QString& name,
+ const QStringList& value)
+
+ Low-level write access to the application's identification and state record
+ are kept in the session manager.
+
+ The property called \a name has its value set to the string list \a value.
+*/
+
+/*!
+ \fn bool QSessionManager::isPhase2() const
+
+ Returns true if the session manager is currently performing a second
+ session management phase; otherwise returns false.
+
+ \sa requestPhase2()
+*/
+
+/*!
+ \fn void QSessionManager::requestPhase2()
+
+ Requests a second session management phase for the application. The
+ application may then return immediately from the QApplication::commitData()
+ or QApplication::saveState() function, and they will be called again once
+ most or all other applications have finished their session management.
+
+ The two phases are useful for applications such as the X11 window manager
+ that need to store information about another application's windows and
+ therefore have to wait until these applications have completed their
+ respective session management tasks.
+
+ \note If another application has requested a second phase it may get called
+ before, simultaneously with, or after your application's second phase.
+
+ \sa isPhase2()
+*/
+
+/*****************************************************************************
+ Stubbed session management support
+ *****************************************************************************/
+#ifndef QT_NO_SESSIONMANAGER
+#if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
+
+#if defined(Q_OS_WINCE)
+HRESULT qt_CoCreateGuid(GUID* guid)
+{
+ // We will use the following information to create the GUID
+ // 1. absolute path to application
+ wchar_t tempFilename[MAX_PATH];
+ if (!GetModuleFileName(0, tempFilename, MAX_PATH))
+ return S_FALSE;
+ unsigned int hash = qHash(QString::fromWCharArray(tempFilename));
+ guid->Data1 = hash;
+ // 2. creation time of file
+ QFileInfo info(QString::fromWCharArray(tempFilename));
+ guid->Data2 = qHash(info.created().toTime_t());
+ // 3. current system time
+ guid->Data3 = qHash(QDateTime::currentDateTime().toTime_t());
+ return S_OK;
+}
+#if !defined(OLE32_MCOMGUID) || defined(QT_WINCE_FORCE_CREATE_GUID)
+#define CoCreateGuid qt_CoCreateGuid
+#endif
+
+#endif
+
+class QSessionManagerPrivate : public QObjectPrivate
+{
+public:
+ QStringList restartCommand;
+ QStringList discardCommand;
+ QString sessionId;
+ QString sessionKey;
+ QSessionManager::RestartHint restartHint;
+};
+
+QSessionManager* qt_session_manager_self = 0;
+QSessionManager::QSessionManager(QApplication * app, QString &id, QString &key)
+ : QObject(*new QSessionManagerPrivate, app)
+{
+ Q_D(QSessionManager);
+ setObjectName(QLatin1String("qt_sessionmanager"));
+ qt_session_manager_self = this;
+#if defined(Q_WS_WIN)
+ wchar_t guidstr[40];
+ GUID guid;
+ CoCreateGuid(&guid);
+ StringFromGUID2(guid, guidstr, 40);
+ id = QString::fromWCharArray(guidstr);
+ CoCreateGuid(&guid);
+ StringFromGUID2(guid, guidstr, 40);
+ key = QString::fromWCharArray(guidstr);
+#endif
+ d->sessionId = id;
+ d->sessionKey = key;
+ d->restartHint = RestartIfRunning;
+}
+
+QSessionManager::~QSessionManager()
+{
+ qt_session_manager_self = 0;
+}
+
+QString QSessionManager::sessionId() const
+{
+ Q_D(const QSessionManager);
+ return d->sessionId;
+}
+
+QString QSessionManager::sessionKey() const
+{
+ Q_D(const QSessionManager);
+ return d->sessionKey;
+}
+
+
+#if defined(Q_WS_X11) || defined(Q_WS_MAC)
+void* QSessionManager::handle() const
+{
+ return 0;
+}
+#endif
+
+#if !defined(Q_WS_WIN)
+bool QSessionManager::allowsInteraction()
+{
+ return true;
+}
+
+bool QSessionManager::allowsErrorInteraction()
+{
+ return true;
+}
+void QSessionManager::release()
+{
+}
+
+void QSessionManager::cancel()
+{
+}
+#endif
+
+
+void QSessionManager::setRestartHint(QSessionManager::RestartHint hint)
+{
+ Q_D(QSessionManager);
+ d->restartHint = hint;
+}
+
+QSessionManager::RestartHint QSessionManager::restartHint() const
+{
+ Q_D(const QSessionManager);
+ return d->restartHint;
+}
+
+void QSessionManager::setRestartCommand(const QStringList& command)
+{
+ Q_D(QSessionManager);
+ d->restartCommand = command;
+}
+
+QStringList QSessionManager::restartCommand() const
+{
+ Q_D(const QSessionManager);
+ return d->restartCommand;
+}
+
+void QSessionManager::setDiscardCommand(const QStringList& command)
+{
+ Q_D(QSessionManager);
+ d->discardCommand = command;
+}
+
+QStringList QSessionManager::discardCommand() const
+{
+ Q_D(const QSessionManager);
+ return d->discardCommand;
+}
+
+void QSessionManager::setManagerProperty(const QString&, const QString&)
+{
+}
+
+void QSessionManager::setManagerProperty(const QString&, const QStringList&)
+{
+}
+
+bool QSessionManager::isPhase2() const
+{
+ return false;
+}
+
+void QSessionManager::requestPhase2()
+{
+}
+
+#endif
+#endif // QT_NO_SESSIONMANAGER
+
+/*!
+ \typedef QApplication::ColorMode
+ \compat
+
+ Use ColorSpec instead.
+*/
+
+/*!
+ \fn Qt::MacintoshVersion QApplication::macVersion()
+
+ Use QSysInfo::MacintoshVersion instead.
+*/
+
+/*!
+ \fn QApplication::ColorMode QApplication::colorMode()
+
+ Use colorSpec() instead, and use ColorSpec as the enum type.
+*/
+
+/*!
+ \fn void QApplication::setColorMode(ColorMode mode)
+
+ Use setColorSpec() instead, and pass a ColorSpec value instead.
+*/
+
+/*!
+ \fn bool QApplication::hasGlobalMouseTracking()
+
+ This feature does not exist anymore. This function always returns true
+ in Qt 4.
+*/
+
+/*!
+ \fn void QApplication::setGlobalMouseTracking(bool dummy)
+
+ This function does nothing in Qt 4. The \a dummy parameter is ignored.
+*/
+
+/*!
+ \fn void QApplication::flushX()
+
+ Use flush() instead.
+*/
+
+/*!
+ \fn void QApplication::setWinStyleHighlightColor(const QColor &c)
+
+ Use the palette instead.
+
+ \oldcode
+ app.setWinStyleHighlightColor(color);
+ \newcode
+ QPalette palette(QApplication::palette());
+ palette.setColor(QPalette::Highlight, color);
+ QApplication::setPalette(palette);
+ \endcode
+*/
+
+/*!
+ \fn void QApplication::setPalette(const QPalette &pal, bool b, const char* className = 0)
+
+ Use the two-argument overload instead.
+*/
+
+/*!
+ \fn void QApplication::setFont(const QFont &font, bool b, const char* className = 0)
+
+ Use the two-argument overload instead.
+*/
+
+/*!
+ \fn const QColor &QApplication::winStyleHighlightColor()
+
+ Use QApplication::palette().color(QPalette::Active, QPalette::Highlight) instead.
+*/
+
+/*!
+ \fn QWidget *QApplication::widgetAt(int x, int y, bool child)
+
+ Use the two-argument widgetAt() overload to get the child widget. To get
+ the top-level widget do this:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 12
+*/
+
+/*!
+ \fn QWidget *QApplication::widgetAt(const QPoint &point, bool child)
+
+ Use the single-argument widgetAt() overload to get the child widget. To get
+ the top-level widget do this:
+
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 13
+*/
+
+#ifdef QT3_SUPPORT
+QWidget *QApplication::mainWidget()
+{
+ return QApplicationPrivate::main_widget;
+}
+#endif
+bool QApplicationPrivate::inPopupMode() const
+{
+ return QApplicationPrivate::popupWidgets != 0;
+}
+
+/*!
+ \property QApplication::quitOnLastWindowClosed
+
+ \brief whether the application implicitly quits when the last window is
+ closed.
+
+ The default is true.
+
+ If this property is true, the applications quits when the last visible
+ primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose
+ attribute set is closed. By default this attribute is set for all widgets
+ except for sub-windows. Refer to \l{Qt::WindowType} for a detailed list of
+ Qt::Window objects.
+
+ \sa quit(), QWidget::close()
+ */
+
+void QApplication::setQuitOnLastWindowClosed(bool quit)
+{
+ QApplicationPrivate::quitOnLastWindowClosed = quit;
+}
+
+bool QApplication::quitOnLastWindowClosed()
+{
+ return QApplicationPrivate::quitOnLastWindowClosed;
+}
+
+void QApplicationPrivate::emitLastWindowClosed()
+{
+ if (qApp && qApp->d_func()->in_exec) {
+ if (QApplicationPrivate::quitOnLastWindowClosed) {
+ // get ready to quit, this event might be removed if the
+ // event loop is re-entered, however
+ QApplication::postEvent(qApp, new QEvent(QEvent::Quit));
+ }
+ emit qApp->lastWindowClosed();
+ }
+}
+
+/*! \variable QApplication::NormalColors
+ \compat
+
+ Use \l NormalColor instead.
+*/
+
+/*! \variable QApplication::CustomColors
+ \compat
+
+ Use \l CustomColor instead.
+*/
+
+#ifdef QT_KEYPAD_NAVIGATION
+/*!
+ Sets the kind of focus navigation Qt should use to \a mode.
+
+ This feature is available in Qt for Embedded Linux, Symbian and Windows CE
+ only.
+
+ \note On Windows CE this feature is disabled by default for touch device
+ mkspecs. To enable keypad navigation, build Qt with
+ QT_KEYPAD_NAVIGATION defined.
+
+ \note On Symbian, setting the mode to Qt::NavigationModeCursorAuto will enable a
+ virtual mouse cursor on non touchscreen devices, which is controlled
+ by the cursor keys if there is no analog pointer device.
+ On other platforms and on touchscreen devices, it has the same
+ meaning as Qt::NavigationModeNone.
+
+ \since 4.6
+
+ \sa keypadNavigationEnabled()
+*/
+void QApplication::setNavigationMode(Qt::NavigationMode mode)
+{
+#ifdef Q_OS_SYMBIAN
+ QApplicationPrivate::setNavigationMode(mode);
+#else
+ QApplicationPrivate::navigationMode = mode;
+#endif
+}
+
+/*!
+ Returns what kind of focus navigation Qt is using.
+
+ This feature is available in Qt for Embedded Linux, Symbian and Windows CE
+ only.
+
+ \note On Windows CE this feature is disabled by default for touch device
+ mkspecs. To enable keypad navigation, build Qt with
+ QT_KEYPAD_NAVIGATION defined.
+
+ \note On Symbian, the default mode is Qt::NavigationModeNone for touch
+ devices, and Qt::NavigationModeKeypadDirectional.
+
+ \since 4.6
+
+ \sa keypadNavigationEnabled()
+*/
+Qt::NavigationMode QApplication::navigationMode()
+{
+ return QApplicationPrivate::navigationMode;
+}
+
+/*!
+ Sets whether Qt should use focus navigation suitable for use with a
+ minimal keypad.
+
+ This feature is available in Qt for Embedded Linux, Symbian and Windows CE
+ only.
+
+ \note On Windows CE this feature is disabled by default for touch device
+ mkspecs. To enable keypad navigation, build Qt with
+ QT_KEYPAD_NAVIGATION defined.
+
+ \deprecated
+
+ \sa setNavigationMode()
+*/
+void QApplication::setKeypadNavigationEnabled(bool enable)
+{
+ if (enable) {
+#ifdef Q_OS_SYMBIAN
+ QApplication::setNavigationMode(Qt::NavigationModeKeypadDirectional);
+#else
+ QApplication::setNavigationMode(Qt::NavigationModeKeypadTabOrder);
+#endif
+ }
+ else {
+ QApplication::setNavigationMode(Qt::NavigationModeNone);
+ }
+}
+
+/*!
+ Returns true if Qt is set to use keypad navigation; otherwise returns
+ false. The default value is true on Symbian, but false on other platforms.
+
+ This feature is available in Qt for Embedded Linux, Symbian and Windows CE
+ only.
+
+ \note On Windows CE this feature is disabled by default for touch device
+ mkspecs. To enable keypad navigation, build Qt with
+ QT_KEYPAD_NAVIGATION defined.
+
+ \deprecated
+
+ \sa navigationMode()
+*/
+bool QApplication::keypadNavigationEnabled()
+{
+ return QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadTabOrder ||
+ QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadDirectional;
+}
+#endif
+
+/*!
+ \fn void QApplication::alert(QWidget *widget, int msec)
+ \since 4.3
+
+ Causes an alert to be shown for \a widget if the window is not the active
+ window. The alert is shown for \a msec miliseconds. If \a msec is zero (the
+ default), then the alert is shown indefinitely until the window becomes
+ active again.
+
+ Currently this function does nothing on Qt for Embedded Linux.
+
+ On Mac OS X, this works more at the application level and will cause the
+ application icon to bounce in the dock.
+
+ On Windows, this causes the window's taskbar entry to flash for a time. If
+ \a msec is zero, the flashing will stop and the taskbar entry will turn a
+ different color (currently orange).
+
+ On X11, this will cause the window to be marked as "demands attention", the
+ window must not be hidden (i.e. not have hide() called on it, but be
+ visible in some sort of way) in order for this to work.
+*/
+
+/*!
+ \property QApplication::cursorFlashTime
+ \brief the text cursor's flash (blink) time in milliseconds
+
+ The flash time is the time required to display, invert and restore the
+ caret display. Usually the text cursor is displayed for half the cursor
+ flash time, then hidden for the same amount of time, but this may vary.
+
+ The default value on X11 is 1000 milliseconds. On Windows, the
+ \gui{Control Panel} value is used and setting this property sets the cursor
+ flash time for all applications.
+
+ We recommend that widgets do not cache this value as it may change at any
+ time if the user changes the global desktop settings.
+*/
+
+/*!
+ \property QApplication::doubleClickInterval
+ \brief the time limit in milliseconds that distinguishes a double click
+ from two consecutive mouse clicks
+
+ The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
+ operating system's value is used. However, on Windows and Symbian OS,
+ calling this function sets the double click interval for all applications.
+*/
+
+/*!
+ \property QApplication::keyboardInputInterval
+ \brief the time limit in milliseconds that distinguishes a key press
+ from two consecutive key presses
+ \since 4.2
+
+ The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
+ operating system's value is used.
+*/
+
+/*!
+ \property QApplication::wheelScrollLines
+ \brief the number of lines to scroll a widget, when the
+ mouse wheel is rotated.
+
+ If the value exceeds the widget's number of visible lines, the widget
+ should interpret the scroll operation as a single \e{page up} or
+ \e{page down}. If the widget is an \l{QAbstractItemView}{item view class},
+ then the result of scrolling one \e line depends on the setting of the
+ widget's \l{QAbstractItemView::verticalScrollMode()}{scroll mode}. Scroll
+ one \e line can mean \l{QAbstractItemView::ScrollPerItem}{scroll one item}
+ or \l{QAbstractItemView::ScrollPerPixel}{scroll one pixel}.
+
+ By default, this property has a value of 3.
+*/
+
+/*!
+ \fn void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
+
+ Enables the UI effect \a effect if \a enable is true, otherwise the effect
+ will not be used.
+
+ \note All effects are disabled on screens running at less than 16-bit color
+ depth.
+
+ \sa isEffectEnabled(), Qt::UIEffect, setDesktopSettingsAware()
+*/
+
+/*!
+ \fn bool QApplication::isEffectEnabled(Qt::UIEffect effect)
+
+ Returns true if \a effect is enabled; otherwise returns false.
+
+ By default, Qt will try to use the desktop settings. To prevent this, call
+ setDesktopSettingsAware(false).
+
+ \note All effects are disabled on screens running at less than 16-bit color
+ depth.
+
+ \sa setEffectEnabled(), Qt::UIEffect
+*/
+
+/*!
+ \fn QWidget *QApplication::mainWidget()
+
+ Returns the main application widget, or 0 if there is no main widget.
+*/
+
+/*!
+ \fn void QApplication::setMainWidget(QWidget *mainWidget)
+
+ Sets the application's main widget to \a mainWidget.
+
+ In most respects the main widget is like any other widget, except that if
+ it is closed, the application exits. QApplication does \e not take
+ ownership of the \a mainWidget, so if you create your main widget on the
+ heap you must delete it yourself.
+
+ You need not have a main widget; connecting lastWindowClosed() to quit()
+ is an alternative.
+
+ On X11, this function also resizes and moves the main widget according
+ to the \e -geometry command-line option, so you should set the default
+ geometry (using \l QWidget::setGeometry()) before calling setMainWidget().
+
+ \sa mainWidget(), exec(), quit()
+*/
+
+/*!
+ \fn void QApplication::beep()
+
+ Sounds the bell, using the default volume and sound. The function is \e not
+ available in Qt for Embedded Linux.
+*/
+
+/*!
+ \fn void QApplication::setOverrideCursor(const QCursor &cursor)
+
+ Sets the application override cursor to \a cursor.
+
+ Application override cursors are intended for showing the user that the
+ application is in a special state, for example during an operation that
+ might take some time.
+
+ This cursor will be displayed in all the application's widgets until
+ restoreOverrideCursor() or another setOverrideCursor() is called.
+
+ Application cursors are stored on an internal stack. setOverrideCursor()
+ pushes the cursor onto the stack, and restoreOverrideCursor() pops the
+ active cursor off the stack. changeOverrideCursor() changes the curently
+ active application override cursor.
+
+ Every setOverrideCursor() must eventually be followed by a corresponding
+ restoreOverrideCursor(), otherwise the stack will never be emptied.
+
+ Example:
+ \snippet doc/src/snippets/code/src_gui_kernel_qapplication_x11.cpp 0
+
+ \sa overrideCursor(), restoreOverrideCursor(), changeOverrideCursor(),
+ QWidget::setCursor()
+*/
+
+/*!
+ \fn void QApplication::restoreOverrideCursor()
+
+ Undoes the last setOverrideCursor().
+
+ If setOverrideCursor() has been called twice, calling
+ restoreOverrideCursor() will activate the first cursor set. Calling this
+ function a second time restores the original widgets' cursors.
+
+ \sa setOverrideCursor(), overrideCursor()
+*/
+
+/*!
+ \macro qApp
+ \relates QApplication
+
+ A global pointer referring to the unique application object. It is
+ equivalent to the pointer returned by the QCoreApplication::instance()
+ function except that, in GUI applications, it is a pointer to a
+ QApplication instance.
+
+ Only one application object can be created.
+
+ \sa QCoreApplication::instance()
+*/
+
+#ifndef QT_NO_IM
+// ************************************************************************
+// Input Method support
+// ************************************************************************
+
+/*!
+ This function replaces the QInputContext instance used by the application
+ with \a inputContext.
+
+ Qt takes ownership of the given \a inputContext.
+
+ \sa inputContext()
+*/
+void QApplication::setInputContext(QInputContext *inputContext)
+{
+ if (inputContext == QApplicationPrivate::inputContext)
+ return;
+ if (!inputContext) {
+ qWarning("QApplication::setInputContext: called with 0 input context");
+ return;
+ }
+ delete QApplicationPrivate::inputContext;
+ QApplicationPrivate::inputContext = inputContext;
+ QApplicationPrivate::inputContext->setParent(this);
+}
+
+/*!
+ Returns the QInputContext instance used by the application.
+
+ \sa setInputContext()
+*/
+QInputContext *QApplication::inputContext() const
+{
+ Q_D(const QApplication);
+ Q_UNUSED(d);// only static members being used.
+ if (QApplicationPrivate::is_app_closing)
+ return d->inputContext;
+#ifdef Q_WS_X11
+ if (!X11)
+ return 0;
+ if (!d->inputContext) {
+ QApplication *that = const_cast<QApplication *>(this);
+ QInputContext *qic = QInputContextFactory::create(X11->default_im, that);
+ // fallback to default X Input Method.
+ if (!qic)
+ qic = QInputContextFactory::create(QLatin1String("xim"), that);
+ that->d_func()->inputContext = qic;
+ }
+#elif defined(Q_OS_SYMBIAN)
+ if (!d->inputContext) {
+ QApplication *that = const_cast<QApplication *>(this);
+ const QStringList keys = QInputContextFactory::keys();
+ // Try hbim and coefep first, then try others.
+ if (keys.contains(QLatin1String("hbim"))) {
+ that->d_func()->inputContext = QInputContextFactory::create(QLatin1String("hbim"), that);
+ } else if (keys.contains(QLatin1String("coefep"))) {
+ that->d_func()->inputContext = QInputContextFactory::create(QLatin1String("coefep"), that);
+ } else {
+ for (int c = 0; c < keys.size() && !d->inputContext; ++c) {
+ that->d_func()->inputContext = QInputContextFactory::create(keys[c], that);
+ }
+ }
+ }
+#endif
+ return d->inputContext;
+}
+#endif // QT_NO_IM
+
+//Returns the current platform used by keyBindings
+uint QApplicationPrivate::currentPlatform(){
+ uint platform = KB_Win;
+#ifdef Q_WS_MAC
+ platform = KB_Mac;
+#elif defined Q_WS_X11
+ platform = KB_X11;
+ if (X11->desktopEnvironment == DE_KDE)
+ platform |= KB_KDE;
+ if (X11->desktopEnvironment == DE_GNOME)
+ platform |= KB_Gnome;
+ if (X11->desktopEnvironment == DE_CDE)
+ platform |= KB_CDE;
+#elif defined(Q_OS_SYMBIAN)
+ platform = KB_S60;
+#endif
+ return platform;
+}
+
+bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
+{
+ return QCoreApplication::sendSpontaneousEvent(receiver, event);
+}
+
+
+/*!
+ \since 4.2
+
+ Returns the current keyboard input locale.
+*/
+QLocale QApplication::keyboardInputLocale()
+{
+ if (!QApplicationPrivate::checkInstance("keyboardInputLocale"))
+ return QLocale::c();
+ return qt_keymapper_private()->keyboardInputLocale;
+}
+
+/*!
+ \since 4.2
+
+ Returns the current keyboard input direction.
+*/
+Qt::LayoutDirection QApplication::keyboardInputDirection()
+{
+ if (!QApplicationPrivate::checkInstance("keyboardInputDirection"))
+ return Qt::LeftToRight;
+ return qt_keymapper_private()->keyboardInputDirection;
+}
+
+void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget,
+ Qt::FocusPolicy focusPolicy,
+ Qt::FocusReason focusReason)
+{
+ QWidget *focusWidget = widget;
+ while (focusWidget) {
+ if (focusWidget->isEnabled()
+ && QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) {
+ focusWidget->setFocus(focusReason);
+ break;
+ }
+ if (focusWidget->isWindow())
+ break;
+ focusWidget = focusWidget->parentWidget();
+ }
+}
+
+bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy)
+{
+ QWidget *f = w;
+ while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
+ f = f->d_func()->extra->focus_proxy;
+
+ if ((w->focusPolicy() & policy) != policy)
+ return false;
+ if (w != f && (f->focusPolicy() & policy) != policy)
+ return false;
+ return true;
+}
+
+/*! \fn QDecoration &QApplication::qwsDecoration()
+ Return the QWSDecoration used for decorating windows.
+
+ \warning This method is non-portable. It is only available in
+ Qt for Embedded Linux.
+
+ \sa QDecoration
+*/
+
+/*!
+ \fn void QApplication::qwsSetDecoration(QDecoration *decoration)
+
+ Sets the QDecoration derived class to use for decorating the
+ windows used by Qt for Embedded Linux to the \a decoration
+ specified.
+
+ This method is non-portable. It is only available in Qt for Embedded Linux.
+
+ \sa QDecoration
+*/
+
+/*! \fn QDecoration* QApplication::qwsSetDecoration(const QString &decoration)
+ \overload
+
+ Requests a QDecoration object for \a decoration from the
+ QDecorationFactory.
+
+ The string must be one of the QDecorationFactory::keys(). Keys are case
+ insensitive.
+
+ A later call to the QApplication constructor will override the requested
+ style when a "-style" option is passed in as a commandline parameter.
+
+ Returns 0 if an unknown \a decoration is passed, otherwise the QStyle object
+ returned is set as the application's GUI style.
+*/
+
+/*!
+ \fn bool QApplication::qwsEventFilter(QWSEvent *event)
+
+ This virtual function is only implemented under Qt for Embedded Linux.
+
+ If you create an application that inherits QApplication and
+ reimplement this function, you get direct access to all QWS (Q
+ Window System) events that the are received from the QWS master
+ process. The events are passed in the \a event parameter.
+
+ Return true if you want to stop the event from being processed.
+ Return false for normal event dispatching. The default
+ implementation returns false.
+*/
+
+/*! \fn void QApplication::qwsSetCustomColors(QRgb *colorTable, int start, int numColors)
+ Set Qt for Embedded Linux custom color table.
+
+ Qt for Embedded Linux on 8-bpp displays allocates a standard 216 color cube.
+ The remaining 40 colors may be used by setting a custom color
+ table in the QWS master process before any clients connect.
+
+ \a colorTable is an array of up to 40 custom colors. \a start is
+ the starting index (0-39) and \a numColors is the number of colors
+ to be set (1-40).
+
+ This method is non-portable. It is available \e only in
+ Qt for Embedded Linux.
+
+ \note The custom colors will not be used by the default screen
+ driver. To make use of the new colors, implement a custom screen
+ driver, or use QDirectPainter.
+*/
+
+/*! \fn int QApplication::qwsProcessEvent(QWSEvent* event)
+ \internal
+*/
+
+/*! \fn int QApplication::x11ClientMessage(QWidget* w, XEvent* event, bool passive_only)
+ \internal
+*/
+
+/*! \fn int QApplication::x11ProcessEvent(XEvent* event)
+ This function does the core processing of individual X
+ \a{event}s, normally by dispatching Qt events to the right
+ destination.
+
+ It returns 1 if the event was consumed by special handling, 0 if
+ the \a event was consumed by normal handling, and -1 if the \a
+ event was for an unrecognized widget.
+
+ \sa x11EventFilter()
+*/
+
+/*!
+ \fn bool QApplication::x11EventFilter(XEvent *event)
+
+ \warning This virtual function is only implemented under X11.
+
+ If you create an application that inherits QApplication and
+ reimplement this function, you get direct access to all X events
+ that the are received from the X server. The events are passed in
+ the \a event parameter.
+
+ Return true if you want to stop the event from being processed.
+ Return false for normal event dispatching. The default
+ implementation returns false.
+
+ It is only the directly addressed messages that are filtered.
+ You must install an event filter directly on the event
+ dispatcher, which is returned by
+ QAbstractEventDispatcher::instance(), to handle system wide
+ messages.
+
+ \sa x11ProcessEvent()
+*/
+
+/*! \fn void QApplication::winFocus(QWidget *widget, bool gotFocus)
+ \internal
+ \since 4.1
+
+ If \a gotFocus is true, \a widget will become the active window.
+ Otherwise the active window is reset to 0.
+*/
+
+/*! \fn void QApplication::winMouseButtonUp()
+ \internal
+ */
+
+/*! \fn void QApplication::syncX()
+ Synchronizes with the X server in the X11 implementation.
+ This normally takes some time. Does nothing on other platforms.
+*/
+
+void QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent)
+{
+ for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
+ QTouchEvent::TouchPoint &touchPoint = touchEvent->_touchPoints[i];
+
+ // preserve the sub-pixel resolution
+ QRectF rect = touchPoint.screenRect();
+ const QPointF screenPos = rect.center();
+ const QPointF delta = screenPos - screenPos.toPoint();
+
+ rect.moveCenter(widget->mapFromGlobal(screenPos.toPoint()) + delta);
+ touchPoint.d->rect = rect;
+ if (touchPoint.state() == Qt::TouchPointPressed) {
+ touchPoint.d->startPos = widget->mapFromGlobal(touchPoint.startScreenPos().toPoint()) + delta;
+ touchPoint.d->lastPos = widget->mapFromGlobal(touchPoint.lastScreenPos().toPoint()) + delta;
+ }
+ }
+}
+
+void QApplicationPrivate::initializeMultitouch()
+{
+ widgetForTouchPointId.clear();
+ appCurrentTouchPoints.clear();
+
+ initializeMultitouch_sys();
+}
+
+void QApplicationPrivate::cleanupMultitouch()
+{
+ cleanupMultitouch_sys();
+
+ widgetForTouchPointId.clear();
+ appCurrentTouchPoints.clear();
+}
+
+int QApplicationPrivate::findClosestTouchPointId(const QPointF &screenPos)
+{
+ int closestTouchPointId = -1;
+ qreal closestDistance = qreal(0.);
+ foreach (const QTouchEvent::TouchPoint &touchPoint, appCurrentTouchPoints) {
+ qreal distance = QLineF(screenPos, touchPoint.screenPos()).length();
+ if (closestTouchPointId == -1 || distance < closestDistance) {
+ closestTouchPointId = touchPoint.id();
+ closestDistance = distance;
+ }
+ }
+ return closestTouchPointId;
+}
+
+void QApplicationPrivate::translateRawTouchEvent(QWidget *window,
+ QTouchEvent::DeviceType deviceType,
+ const QList<QTouchEvent::TouchPoint> &touchPoints)
+{
+ QApplicationPrivate *d = self;
+ typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
+ QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents;
+
+ for (int i = 0; i < touchPoints.count(); ++i) {
+ QTouchEvent::TouchPoint touchPoint = touchPoints.at(i);
+ // explicitly detach from the original touch point that we got, so even
+ // if the touchpoint structs are reused, we will make a copy that we'll
+ // deliver to the user (which might want to store the struct for later use).
+ touchPoint.d = touchPoint.d->detach();
+
+ // update state
+ QWeakPointer<QWidget> widget;
+ switch (touchPoint.state()) {
+ case Qt::TouchPointPressed:
+ {
+ if (deviceType == QTouchEvent::TouchPad) {
+ // on touch-pads, send all touch points to the same widget
+ widget = d->widgetForTouchPointId.isEmpty()
+ ? QWeakPointer<QWidget>()
+ : d->widgetForTouchPointId.constBegin().value();
+ }
+
+ if (!widget) {
+ // determine which widget this event will go to
+ if (!window)
+ window = QApplication::topLevelAt(touchPoint.screenPos().toPoint());
+ if (!window)
+ continue;
+ widget = window->childAt(window->mapFromGlobal(touchPoint.screenPos().toPoint()));
+ if (!widget)
+ widget = window;
+ }
+
+ if (deviceType == QTouchEvent::TouchScreen) {
+ int closestTouchPointId = d->findClosestTouchPointId(touchPoint.screenPos());
+ QWidget *closestWidget = d->widgetForTouchPointId.value(closestTouchPointId).data();
+ if (closestWidget
+ && (widget.data()->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget.data()))) {
+ widget = closestWidget;
+ }
+ }
+
+ d->widgetForTouchPointId[touchPoint.id()] = widget;
+ touchPoint.d->startScreenPos = touchPoint.screenPos();
+ touchPoint.d->lastScreenPos = touchPoint.screenPos();
+ touchPoint.d->startNormalizedPos = touchPoint.normalizedPos();
+ touchPoint.d->lastNormalizedPos = touchPoint.normalizedPos();
+ if (touchPoint.pressure() < qreal(0.))
+ touchPoint.d->pressure = qreal(1.);
+
+ d->appCurrentTouchPoints.insert(touchPoint.id(), touchPoint);
+ break;
+ }
+ case Qt::TouchPointReleased:
+ {
+ widget = d->widgetForTouchPointId.take(touchPoint.id());
+ if (!widget)
+ continue;
+
+ QTouchEvent::TouchPoint previousTouchPoint = d->appCurrentTouchPoints.take(touchPoint.id());
+ touchPoint.d->startScreenPos = previousTouchPoint.startScreenPos();
+ touchPoint.d->lastScreenPos = previousTouchPoint.screenPos();
+ touchPoint.d->startPos = previousTouchPoint.startPos();
+ touchPoint.d->lastPos = previousTouchPoint.pos();
+ touchPoint.d->startNormalizedPos = previousTouchPoint.startNormalizedPos();
+ touchPoint.d->lastNormalizedPos = previousTouchPoint.normalizedPos();
+ if (touchPoint.pressure() < qreal(0.))
+ touchPoint.d->pressure = qreal(0.);
+ break;
+ }
+ default:
+ widget = d->widgetForTouchPointId.value(touchPoint.id());
+ if (!widget)
+ continue;
+
+ Q_ASSERT(d->appCurrentTouchPoints.contains(touchPoint.id()));
+ QTouchEvent::TouchPoint previousTouchPoint = d->appCurrentTouchPoints.value(touchPoint.id());
+ touchPoint.d->startScreenPos = previousTouchPoint.startScreenPos();
+ touchPoint.d->lastScreenPos = previousTouchPoint.screenPos();
+ touchPoint.d->startPos = previousTouchPoint.startPos();
+ touchPoint.d->lastPos = previousTouchPoint.pos();
+ touchPoint.d->startNormalizedPos = previousTouchPoint.startNormalizedPos();
+ touchPoint.d->lastNormalizedPos = previousTouchPoint.normalizedPos();
+ if (touchPoint.pressure() < qreal(0.))
+ touchPoint.d->pressure = qreal(1.);
+ d->appCurrentTouchPoints[touchPoint.id()] = touchPoint;
+ break;
+ }
+ Q_ASSERT(widget.data() != 0);
+
+ // make the *scene* functions return the same as the *screen* functions
+ touchPoint.d->sceneRect = touchPoint.screenRect();
+ touchPoint.d->startScenePos = touchPoint.startScreenPos();
+ touchPoint.d->lastScenePos = touchPoint.lastScreenPos();
+
+ StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[widget.data()];
+ maskAndPoints.first |= touchPoint.state();
+ if (touchPoint.isPrimary())
+ maskAndPoints.first |= Qt::TouchPointPrimary;
+ maskAndPoints.second.append(touchPoint);
+ }
+
+ if (widgetsNeedingEvents.isEmpty())
+ return;
+
+ QHash<QWidget *, StatesAndTouchPoints>::ConstIterator it = widgetsNeedingEvents.constBegin();
+ const QHash<QWidget *, StatesAndTouchPoints>::ConstIterator end = widgetsNeedingEvents.constEnd();
+ for (; it != end; ++it) {
+ QWidget *widget = it.key();
+ if (!QApplicationPrivate::tryModalHelper(widget, 0))
+ continue;
+
+ QEvent::Type eventType;
+ switch (it.value().first & Qt::TouchPointStateMask) {
+ case Qt::TouchPointPressed:
+ eventType = QEvent::TouchBegin;
+ break;
+ case Qt::TouchPointReleased:
+ eventType = QEvent::TouchEnd;
+ break;
+ case Qt::TouchPointStationary:
+ // don't send the event if nothing changed
+ continue;
+ default:
+ eventType = QEvent::TouchUpdate;
+ break;
+ }
+
+ QTouchEvent touchEvent(eventType,
+ deviceType,
+ QApplication::keyboardModifiers(),
+ it.value().first,
+ it.value().second);
+ updateTouchPointsForWidget(widget, &touchEvent);
+
+ switch (touchEvent.type()) {
+ case QEvent::TouchBegin:
+ {
+ // if the TouchBegin handler recurses, we assume that means the event
+ // has been implicitly accepted and continue to send touch events
+ widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
+ (void ) QApplication::sendSpontaneousEvent(widget, &touchEvent);
+ break;
+ }
+ default:
+ if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent)) {
+ if (touchEvent.type() == QEvent::TouchEnd)
+ widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, false);
+ (void) QApplication::sendSpontaneousEvent(widget, &touchEvent);
+ }
+ break;
+ }
+ }
+}
+
+Q_GUI_EXPORT void qt_translateRawTouchEvent(QWidget *window,
+ QTouchEvent::DeviceType deviceType,
+ const QList<QTouchEvent::TouchPoint> &touchPoints)
+{
+ QApplicationPrivate::translateRawTouchEvent(window, deviceType, touchPoints);
+}
+
+#ifndef QT_NO_GESTURES
+QGestureManager* QGestureManager::instance()
+{
+ QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
+ if (!qAppPriv)
+ return 0;
+ if (!qAppPriv->gestureManager)
+ qAppPriv->gestureManager = new QGestureManager(qApp);
+ return qAppPriv->gestureManager;
+}
+#endif // QT_NO_GESTURES
+
+// These pixmaps approximate the images in the Windows User Interface Guidelines.
+
+// XPM
+
+static const char * const move_xpm[] = {
+"11 20 3 1",
+". c None",
+#if defined(Q_WS_WIN)
+"a c #000000",
+"X c #FFFFFF", // Windows cursor is traditionally white
+#else
+"a c #FFFFFF",
+"X c #000000", // X11 cursor is traditionally black
+#endif
+"aa.........",
+"aXa........",
+"aXXa.......",
+"aXXXa......",
+"aXXXXa.....",
+"aXXXXXa....",
+"aXXXXXXa...",
+"aXXXXXXXa..",
+"aXXXXXXXXa.",
+"aXXXXXXXXXa",
+"aXXXXXXaaaa",
+"aXXXaXXa...",
+"aXXaaXXa...",
+"aXa..aXXa..",
+"aa...aXXa..",
+"a.....aXXa.",
+"......aXXa.",
+".......aXXa",
+".......aXXa",
+"........aa."};
+
+#ifdef Q_WS_WIN
+/* XPM */
+static const char * const ignore_xpm[] = {
+"24 30 3 1",
+". c None",
+"a c #000000",
+"X c #FFFFFF",
+"aa......................",
+"aXa.....................",
+"aXXa....................",
+"aXXXa...................",
+"aXXXXa..................",
+"aXXXXXa.................",
+"aXXXXXXa................",
+"aXXXXXXXa...............",
+"aXXXXXXXXa..............",
+"aXXXXXXXXXa.............",
+"aXXXXXXaaaa.............",
+"aXXXaXXa................",
+"aXXaaXXa................",
+"aXa..aXXa...............",
+"aa...aXXa...............",
+"a.....aXXa..............",
+"......aXXa.....XXXX.....",
+".......aXXa..XXaaaaXX...",
+".......aXXa.XaaaaaaaaX..",
+"........aa.XaaaXXXXaaaX.",
+"...........XaaaaX..XaaX.",
+"..........XaaXaaaX..XaaX",
+"..........XaaXXaaaX.XaaX",
+"..........XaaX.XaaaXXaaX",
+"..........XaaX..XaaaXaaX",
+"...........XaaX..XaaaaX.",
+"...........XaaaXXXXaaaX.",
+"............XaaaaaaaaX..",
+".............XXaaaaXX...",
+"...............XXXX....."};
+#endif
+
+/* XPM */
+static const char * const copy_xpm[] = {
+"24 30 3 1",
+". c None",
+"a c #000000",
+"X c #FFFFFF",
+#if defined(Q_WS_WIN) // Windows cursor is traditionally white
+"aa......................",
+"aXa.....................",
+"aXXa....................",
+"aXXXa...................",
+"aXXXXa..................",
+"aXXXXXa.................",
+"aXXXXXXa................",
+"aXXXXXXXa...............",
+"aXXXXXXXXa..............",
+"aXXXXXXXXXa.............",
+"aXXXXXXaaaa.............",
+"aXXXaXXa................",
+"aXXaaXXa................",
+"aXa..aXXa...............",
+"aa...aXXa...............",
+"a.....aXXa..............",
+"......aXXa..............",
+".......aXXa.............",
+".......aXXa.............",
+"........aa...aaaaaaaaaaa",
+#else
+"XX......................",
+"XaX.....................",
+"XaaX....................",
+"XaaaX...................",
+"XaaaaX..................",
+"XaaaaaX.................",
+"XaaaaaaX................",
+"XaaaaaaaX...............",
+"XaaaaaaaaX..............",
+"XaaaaaaaaaX.............",
+"XaaaaaaXXXX.............",
+"XaaaXaaX................",
+"XaaXXaaX................",
+"XaX..XaaX...............",
+"XX...XaaX...............",
+"X.....XaaX..............",
+"......XaaX..............",
+".......XaaX.............",
+".......XaaX.............",
+"........XX...aaaaaaaaaaa",
+#endif
+".............aXXXXXXXXXa",
+".............aXXXXXXXXXa",
+".............aXXXXaXXXXa",
+".............aXXXXaXXXXa",
+".............aXXaaaaaXXa",
+".............aXXXXaXXXXa",
+".............aXXXXaXXXXa",
+".............aXXXXXXXXXa",
+".............aXXXXXXXXXa",
+".............aaaaaaaaaaa"};
+
+/* XPM */
+static const char * const link_xpm[] = {
+"24 30 3 1",
+". c None",
+"a c #000000",
+"X c #FFFFFF",
+#if defined(Q_WS_WIN) // Windows cursor is traditionally white
+"aa......................",
+"aXa.....................",
+"aXXa....................",
+"aXXXa...................",
+"aXXXXa..................",
+"aXXXXXa.................",
+"aXXXXXXa................",
+"aXXXXXXXa...............",
+"aXXXXXXXXa..............",
+"aXXXXXXXXXa.............",
+"aXXXXXXaaaa.............",
+"aXXXaXXa................",
+"aXXaaXXa................",
+"aXa..aXXa...............",
+"aa...aXXa...............",
+"a.....aXXa..............",
+"......aXXa..............",
+".......aXXa.............",
+".......aXXa.............",
+"........aa...aaaaaaaaaaa",
+#else
+"XX......................",
+"XaX.....................",
+"XaaX....................",
+"XaaaX...................",
+"XaaaaX..................",
+"XaaaaaX.................",
+"XaaaaaaX................",
+"XaaaaaaaX...............",
+"XaaaaaaaaX..............",
+"XaaaaaaaaaX.............",
+"XaaaaaaXXXX.............",
+"XaaaXaaX................",
+"XaaXXaaX................",
+"XaX..XaaX...............",
+"XX...XaaX...............",
+"X.....XaaX..............",
+"......XaaX..............",
+".......XaaX.............",
+".......XaaX.............",
+"........XX...aaaaaaaaaaa",
+#endif
+".............aXXXXXXXXXa",
+".............aXXXaaaaXXa",
+".............aXXXXaaaXXa",
+".............aXXXaaaaXXa",
+".............aXXaaaXaXXa",
+".............aXXaaXXXXXa",
+".............aXXaXXXXXXa",
+".............aXXXaXXXXXa",
+".............aXXXXXXXXXa",
+".............aaaaaaaaaaa"};
+
+QPixmap QApplicationPrivate::getPixmapCursor(Qt::CursorShape cshape)
+{
+#if defined(Q_WS_X11) || defined(Q_WS_WIN)
+ if (!move_cursor) {
+ move_cursor = new QPixmap((const char **)move_xpm);
+ copy_cursor = new QPixmap((const char **)copy_xpm);
+ link_cursor = new QPixmap((const char **)link_xpm);
+#ifdef Q_WS_WIN
+ ignore_cursor = new QPixmap((const char **)ignore_xpm);
+#endif
+ }
+
+ switch (cshape) {
+ case Qt::DragMoveCursor:
+ return *move_cursor;
+ case Qt::DragCopyCursor:
+ return *copy_cursor;
+ case Qt::DragLinkCursor:
+ return *link_cursor;
+#ifdef Q_WS_WIN
+ case Qt::ForbiddenCursor:
+ return *ignore_cursor;
+#endif
+ default:
+ break;
+ }
+#else
+ Q_UNUSED(cshape);
+#endif
+ return QPixmap();
+}
+
+QString QApplicationPrivate::qmljsDebugArgumentsString()
+{
+ return qmljs_debug_arguments;
+}
+
+QT_END_NAMESPACE
+
+#include "moc_qapplication.cpp"
diff --git a/src/gui/kernel/qapplication.h b/src/gui/kernel/qapplication.h
new file mode 100644
index 0000000000..fb61d36307
--- /dev/null
+++ b/src/gui/kernel/qapplication.h
@@ -0,0 +1,430 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QAPPLICATION_H
+#define QAPPLICATION_H
+
+#include <QtCore/qcoreapplication.h>
+#include <QtGui/qwindowdefs.h>
+#include <QtCore/qpoint.h>
+#include <QtCore/qsize.h>
+#include <QtGui/qcursor.h>
+#ifdef QT_INCLUDE_COMPAT
+# include <QtGui/qdesktopwidget.h>
+#endif
+#ifdef QT3_SUPPORT
+# include <QtGui/qwidget.h>
+# include <QtGui/qpalette.h>
+#endif
+#ifdef Q_WS_QWS
+# include <QtGui/qrgb.h>
+# include <QtGui/qtransportauth_qws.h>
+#endif
+
+QT_BEGIN_HEADER
+
+#if defined(Q_OS_SYMBIAN)
+class CApaApplication;
+#endif
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Gui)
+
+class QSessionManager;
+class QDesktopWidget;
+class QStyle;
+class QEventLoop;
+class QIcon;
+class QInputContext;
+template <typename T> class QList;
+class QLocale;
+#if defined(Q_WS_QWS)
+class QDecoration;
+#elif defined(Q_WS_QPA)
+class QPlatformNativeInterface;
+#endif
+#if defined(Q_OS_SYMBIAN)
+class QSymbianEvent;
+#endif
+
+class QApplication;
+class QApplicationPrivate;
+#if defined(qApp)
+#undef qApp
+#endif
+#define qApp (static_cast<QApplication *>(QCoreApplication::instance()))
+
+
+class Q_GUI_EXPORT QApplication : public QCoreApplication
+{
+ Q_OBJECT
+ Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection)
+ Q_PROPERTY(QIcon windowIcon READ windowIcon WRITE setWindowIcon)
+ Q_PROPERTY(int cursorFlashTime READ cursorFlashTime WRITE setCursorFlashTime)
+ Q_PROPERTY(int doubleClickInterval READ doubleClickInterval WRITE setDoubleClickInterval)
+ Q_PROPERTY(int keyboardInputInterval READ keyboardInputInterval WRITE setKeyboardInputInterval)
+#ifndef QT_NO_WHEELEVENT
+ Q_PROPERTY(int wheelScrollLines READ wheelScrollLines WRITE setWheelScrollLines)
+#endif
+ Q_PROPERTY(QSize globalStrut READ globalStrut WRITE setGlobalStrut)
+ Q_PROPERTY(int startDragTime READ startDragTime WRITE setStartDragTime)
+ Q_PROPERTY(int startDragDistance READ startDragDistance WRITE setStartDragDistance)
+ Q_PROPERTY(bool quitOnLastWindowClosed READ quitOnLastWindowClosed WRITE setQuitOnLastWindowClosed)
+#ifndef QT_NO_STYLE_STYLESHEET
+ Q_PROPERTY(QString styleSheet READ styleSheet WRITE setStyleSheet)
+#endif
+#ifdef Q_WS_WINCE
+ Q_PROPERTY(int autoMaximizeThreshold READ autoMaximizeThreshold WRITE setAutoMaximizeThreshold)
+#endif
+ Q_PROPERTY(bool autoSipEnabled READ autoSipEnabled WRITE setAutoSipEnabled)
+
+public:
+ enum Type { Tty, GuiClient, GuiServer };
+
+#ifdef Q_OS_SYMBIAN
+ typedef CApaApplication * (*QS60MainApplicationFactory)();
+#endif
+
+#ifndef qdoc
+ QApplication(int &argc, char **argv, int = ApplicationFlags);
+ QApplication(int &argc, char **argv, bool GUIenabled, int = ApplicationFlags);
+ QApplication(int &argc, char **argv, Type, int = ApplicationFlags);
+#if defined(Q_WS_X11)
+ QApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0, int = ApplicationFlags);
+ QApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0, int = ApplicationFlags);
+#endif
+#if defined(Q_OS_SYMBIAN)
+ QApplication(QApplication::QS60MainApplicationFactory factory, int &argc, char **argv, int = ApplicationFlags);
+#endif
+#endif
+ virtual ~QApplication();
+
+ static Type type();
+
+ static QStyle *style();
+ static void setStyle(QStyle*);
+ static QStyle *setStyle(const QString&);
+ enum ColorSpec { NormalColor=0, CustomColor=1, ManyColor=2 };
+ static int colorSpec();
+ static void setColorSpec(int);
+ static void setGraphicsSystem(const QString &);
+
+#ifndef QT_NO_CURSOR
+ static QCursor *overrideCursor();
+ static void setOverrideCursor(const QCursor &);
+ static void changeOverrideCursor(const QCursor &);
+ static void restoreOverrideCursor();
+#endif
+ static QPalette palette();
+ static QPalette palette(const QWidget *);
+ static QPalette palette(const char *className);
+ static void setPalette(const QPalette &, const char* className = 0);
+ static QFont font();
+ static QFont font(const QWidget*);
+ static QFont font(const char *className);
+ static void setFont(const QFont &, const char* className = 0);
+ static QFontMetrics fontMetrics();
+
+ static void setWindowIcon(const QIcon &icon);
+ static QIcon windowIcon();
+
+
+#ifdef QT3_SUPPORT
+ static QT3_SUPPORT QWidget *mainWidget();
+ static QT3_SUPPORT void setMainWidget(QWidget *);
+#endif
+
+ static QWidgetList allWidgets();
+ static QWidgetList topLevelWidgets();
+
+ static QDesktopWidget *desktop();
+
+ static QWidget *activePopupWidget();
+ static QWidget *activeModalWidget();
+#ifndef QT_NO_CLIPBOARD
+ static QClipboard *clipboard();
+#endif
+ static QWidget *focusWidget();
+
+ static QWidget *activeWindow();
+ static void setActiveWindow(QWidget* act);
+
+ static QWidget *widgetAt(const QPoint &p);
+ static inline QWidget *widgetAt(int x, int y) { return widgetAt(QPoint(x, y)); }
+ static QWidget *topLevelAt(const QPoint &p);
+ static inline QWidget *topLevelAt(int x, int y) { return topLevelAt(QPoint(x, y)); }
+
+ static void syncX();
+ static void beep();
+ static void alert(QWidget *widget, int duration = 0);
+
+ static Qt::KeyboardModifiers keyboardModifiers();
+ static Qt::MouseButtons mouseButtons();
+
+ static void setDesktopSettingsAware(bool);
+ static bool desktopSettingsAware();
+
+ static void setCursorFlashTime(int);
+ static int cursorFlashTime();
+
+ static void setDoubleClickInterval(int);
+ static int doubleClickInterval();
+
+ static void setKeyboardInputInterval(int);
+ static int keyboardInputInterval();
+
+#ifndef QT_NO_WHEELEVENT
+ static void setWheelScrollLines(int);
+ static int wheelScrollLines();
+#endif
+ static void setGlobalStrut(const QSize &);
+ static QSize globalStrut();
+
+ static void setStartDragTime(int ms);
+ static int startDragTime();
+ static void setStartDragDistance(int l);
+ static int startDragDistance();
+
+ static void setLayoutDirection(Qt::LayoutDirection direction);
+ static Qt::LayoutDirection layoutDirection();
+
+ static inline bool isRightToLeft() { return layoutDirection() == Qt::RightToLeft; }
+ static inline bool isLeftToRight() { return layoutDirection() == Qt::LeftToRight; }
+
+ static bool isEffectEnabled(Qt::UIEffect);
+ static void setEffectEnabled(Qt::UIEffect, bool enable = true);
+
+#if defined(Q_WS_MAC)
+ virtual bool macEventFilter(EventHandlerCallRef, EventRef);
+#endif
+#if defined(Q_WS_X11)
+ virtual bool x11EventFilter(XEvent *);
+ virtual int x11ClientMessage(QWidget*, XEvent*, bool passive_only);
+ int x11ProcessEvent(XEvent*);
+#endif
+#if defined(Q_OS_SYMBIAN)
+ int symbianProcessEvent(const QSymbianEvent *event);
+ virtual bool symbianEventFilter(const QSymbianEvent *event);
+#endif
+#if defined(Q_WS_QWS)
+ virtual bool qwsEventFilter(QWSEvent *);
+ int qwsProcessEvent(QWSEvent*);
+ void qwsSetCustomColors(QRgb *colortable, int start, int numColors);
+#ifndef QT_NO_QWS_MANAGER
+ static QDecoration &qwsDecoration();
+ static void qwsSetDecoration(QDecoration *);
+ static QDecoration *qwsSetDecoration(const QString &decoration);
+#endif
+#endif
+
+#if defined(Q_WS_QPA)
+ static QPlatformNativeInterface *platformNativeInterface();
+#endif
+
+
+#if defined(Q_WS_WIN)
+ void winFocus(QWidget *, bool);
+ static void winMouseButtonUp();
+#endif
+#ifndef QT_NO_SESSIONMANAGER
+ // session management
+ bool isSessionRestored() const;
+ QString sessionId() const;
+ QString sessionKey() const;
+ virtual void commitData(QSessionManager& sm);
+ virtual void saveState(QSessionManager& sm);
+#endif
+
+#ifndef QT_NO_IM
+ void setInputContext(QInputContext *);
+ QInputContext *inputContext() const;
+#endif
+
+ static QLocale keyboardInputLocale();
+ static Qt::LayoutDirection keyboardInputDirection();
+
+ static int exec();
+ bool notify(QObject *, QEvent *);
+
+
+ static void setQuitOnLastWindowClosed(bool quit);
+ static bool quitOnLastWindowClosed();
+
+#ifdef QT_KEYPAD_NAVIGATION
+ static Q_DECL_DEPRECATED void setKeypadNavigationEnabled(bool);
+ static bool keypadNavigationEnabled();
+ static void setNavigationMode(Qt::NavigationMode mode);
+ static Qt::NavigationMode navigationMode();
+#endif
+
+Q_SIGNALS:
+ void lastWindowClosed();
+ void focusChanged(QWidget *old, QWidget *now);
+ void fontDatabaseChanged();
+#ifndef QT_NO_SESSIONMANAGER
+ void commitDataRequest(QSessionManager &sessionManager);
+ void saveStateRequest(QSessionManager &sessionManager);
+#endif
+
+public:
+ QString styleSheet() const;
+public Q_SLOTS:
+#ifndef QT_NO_STYLE_STYLESHEET
+ void setStyleSheet(const QString& sheet);
+#endif
+#ifdef Q_WS_WINCE
+ void setAutoMaximizeThreshold(const int threshold);
+ int autoMaximizeThreshold() const;
+#endif
+ void setAutoSipEnabled(const bool enabled);
+ bool autoSipEnabled() const;
+ static void closeAllWindows();
+ static void aboutQt();
+
+protected:
+#if defined(Q_WS_QWS)
+ void setArgs(int, char **);
+#endif
+ bool event(QEvent *);
+ bool compressEvent(QEvent *, QObject *receiver, QPostEventList *);
+
+#ifdef QT3_SUPPORT
+public:
+ static inline QT3_SUPPORT void setReverseLayout(bool b) { setLayoutDirection(b?Qt::RightToLeft:Qt::LeftToRight); }
+ static inline bool QT3_SUPPORT reverseLayout() { return layoutDirection() == Qt::RightToLeft; }
+ static QT3_SUPPORT Qt::Alignment horizontalAlignment(Qt::Alignment align);
+ typedef int ColorMode;
+ enum { NormalColors = NormalColor, CustomColors = CustomColor };
+ static inline QT3_SUPPORT ColorMode colorMode() { return static_cast<ColorMode>(colorSpec()); }
+ static inline QT3_SUPPORT void setColorMode(ColorMode mode) { setColorSpec(int(mode)); }
+#if defined(Q_OS_WIN32) || defined(Q_OS_CYGWIN)
+ static QT3_SUPPORT Qt::WindowsVersion winVersion() { return (Qt::WindowsVersion)QSysInfo::WindowsVersion; }
+#endif
+#if defined(Q_OS_MAC)
+ static QT3_SUPPORT Qt::MacintoshVersion macVersion() { return (Qt::MacintoshVersion)QSysInfo::MacintoshVersion; }
+#endif
+# ifndef QT_NO_CURSOR
+ inline static QT3_SUPPORT void setOverrideCursor(const QCursor &cursor, bool replace)
+ { if (replace) changeOverrideCursor(cursor); else setOverrideCursor(cursor); }
+# endif
+ inline static QT3_SUPPORT bool hasGlobalMouseTracking() {return true;}
+ inline static QT3_SUPPORT void setGlobalMouseTracking(bool) {}
+ inline static QT3_SUPPORT void flushX() { flush(); }
+ static inline QT3_SUPPORT void setWinStyleHighlightColor(const QColor &c) {
+ QPalette p(palette());
+ p.setColor(QPalette::Highlight, c);
+ setPalette(p);
+ }
+ static inline QT3_SUPPORT const QColor &winStyleHighlightColor()
+ { return palette().color(QPalette::Active, QPalette::Highlight); }
+ static inline QT3_SUPPORT void setPalette(const QPalette &pal, bool, const char* className = 0)
+ { setPalette(pal, className); }
+ static inline QT3_SUPPORT void setFont(const QFont &font, bool, const char* className = 0)
+ { setFont(font, className); }
+
+ static inline QT3_SUPPORT QWidget *widgetAt(int x, int y, bool child)
+ { QWidget *w = widgetAt(x, y); return child ? w : (w ? w->window() : 0); }
+ static inline QT3_SUPPORT QWidget *widgetAt(const QPoint &p, bool child)
+ { QWidget *w = widgetAt(p); return child ? w : (w ? w->window() : 0); }
+#endif // QT3_SUPPORT
+
+#if defined(Q_INTERNAL_QAPP_SRC) || defined(qdoc)
+ QApplication(int &argc, char **argv);
+ QApplication(int &argc, char **argv, bool GUIenabled);
+ QApplication(int &argc, char **argv, Type);
+#if defined(Q_WS_X11)
+ QApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0);
+ QApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0);
+#endif
+#if defined(Q_OS_SYMBIAN) || defined(qdoc)
+ QApplication(QApplication::QS60MainApplicationFactory factory, int &argc, char **argv);
+#endif
+#endif
+
+private:
+ Q_DISABLE_COPY(QApplication)
+ Q_DECLARE_PRIVATE(QApplication)
+
+ friend class QGraphicsWidget;
+ friend class QGraphicsItem;
+ friend class QGraphicsScene;
+ friend class QGraphicsScenePrivate;
+ friend class QWidget;
+ friend class QWidgetPrivate;
+ friend class QETWidget;
+ friend class Q3AccelManager;
+ friend class QTranslator;
+ friend class QWidgetAnimator;
+#ifndef QT_NO_SHORTCUT
+ friend class QShortcut;
+ friend class QLineEdit;
+ friend class QTextControl;
+#endif
+ friend class QAction;
+ friend class QFontDatabasePrivate;
+
+#if defined(Q_WS_QWS)
+ friend class QInputContext;
+ friend class QWSDirectPainterSurface;
+ friend class QDirectPainter;
+ friend class QDirectPainterPrivate;
+#endif
+#ifndef QT_NO_GESTURES
+ friend class QGestureManager;
+#endif
+
+#if defined(Q_WS_MAC) || defined(Q_WS_X11)
+ Q_PRIVATE_SLOT(d_func(), void _q_alertTimeOut())
+#endif
+#if defined(QT_RX71_MULTITOUCH)
+ Q_PRIVATE_SLOT(d_func(), void _q_readRX71MultiTouchEvents())
+#endif
+#if defined(Q_OS_SYMBIAN)
+ Q_PRIVATE_SLOT(d_func(), void _q_aboutToQuit())
+#endif
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QAPPLICATION_H
diff --git a/src/gui/kernel/qapplication_mac.mm b/src/gui/kernel/qapplication_mac.mm
new file mode 100644
index 0000000000..f607a72e92
--- /dev/null
+++ b/src/gui/kernel/qapplication_mac.mm
@@ -0,0 +1,3134 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (c) 2007-2008, Apple, Inc.
+**
+** All rights reserved.
+**
+** Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are met:
+**
+** * Redistributions of source code must retain the above copyright notice,
+** this list of conditions and the following disclaimer.
+**
+** * Redistributions in binary form must reproduce the above copyright notice,
+** this list of conditions and the following disclaimer in the documentation
+** and/or other materials provided with the distribution.
+**
+** * Neither the name of Apple, Inc. nor the names of its contributors
+** may be used to endorse or promote products derived from this software
+** without specific prior written permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+**
+****************************************************************************/
+
+#include <Cocoa/Cocoa.h>
+
+#include "qapplication.h"
+#include "qbitarray.h"
+#include "qclipboard.h"
+#include "qcursor.h"
+#include "qdatastream.h"
+#include "qdatetime.h"
+#include "qdesktopwidget.h"
+#include "qdockwidget.h"
+#include "qevent.h"
+#include "qhash.h"
+#include "qlayout.h"
+#include "qmenubar.h"
+#include "qmessagebox.h"
+#include "qmime.h"
+#include "qpixmapcache.h"
+#include "qpointer.h"
+#include "qsessionmanager.h"
+#include "qsettings.h"
+#include "qsocketnotifier.h"
+#include "qstyle.h"
+#include "qstylefactory.h"
+#include "qtextcodec.h"
+#include "qtoolbar.h"
+#include "qvariant.h"
+#include "qwidget.h"
+#include "qcolormap.h"
+#include "qdir.h"
+#include "qdebug.h"
+#include "qtimer.h"
+#include "qurl.h"
+#include "private/qmacinputcontext_p.h"
+#include "private/qpaintengine_mac_p.h"
+#include "private/qcursor_p.h"
+#include "private/qapplication_p.h"
+#include "private/qcolor_p.h"
+#include "private/qwidget_p.h"
+#include "private/qkeymapper_p.h"
+#include "private/qeventdispatcher_mac_p.h"
+#include "private/qeventdispatcher_unix_p.h"
+#include <private/qcocoamenuloader_mac_p.h>
+#include <private/qcocoaapplication_mac_p.h>
+#include <private/qcocoaapplicationdelegate_mac_p.h>
+#include <private/qt_cocoa_helpers_mac_p.h>
+#include <private/qcocoawindow_mac_p.h>
+#include <private/qpixmap_mac_p.h>
+#include <private/qdesktopwidget_mac_p.h>
+#include <private/qeventdispatcher_mac_p.h>
+#include <qvarlengtharray.h>
+
+#ifndef QT_NO_ACCESSIBILITY
+# include "qaccessible.h"
+#endif
+
+#ifndef QT_NO_THREAD
+# include "qmutex.h"
+#endif
+
+#include <unistd.h>
+#include <string.h>
+#include <sys/time.h>
+#include <sys/select.h>
+
+/*****************************************************************************
+ QApplication debug facilities
+ *****************************************************************************/
+//#define DEBUG_EVENTS //like EventDebug but more specific to Qt
+//#define DEBUG_DROPPED_EVENTS
+//#define DEBUG_MOUSE_MAPS
+//#define DEBUG_MODAL_EVENTS
+//#define DEBUG_PLATFORM_SETTINGS
+
+#define QMAC_SPEAK_TO_ME
+#ifdef QMAC_SPEAK_TO_ME
+#include "qregexp.h"
+#endif
+
+#ifndef kThemeBrushAlternatePrimaryHighlightColor
+#define kThemeBrushAlternatePrimaryHighlightColor -5
+#endif
+
+#define kCMDeviceUnregisteredNotification CFSTR("CMDeviceUnregisteredNotification")
+#define kCMDefaultDeviceNotification CFSTR("CMDefaultDeviceNotification")
+#define kCMDeviceProfilesNotification CFSTR("CMDeviceProfilesNotification")
+#define kCMDefaultDeviceProfileNotification CFSTR("CMDefaultDeviceProfileNotification")
+
+QT_BEGIN_NAMESPACE
+
+//for qt_mac.h
+QPaintDevice *qt_mac_safe_pdev = 0;
+QList<QMacWindowChangeEvent*> *QMacWindowChangeEvent::change_events = 0;
+QPointer<QWidget> topLevelAt_cache = 0;
+
+/*****************************************************************************
+ Internal variables and functions
+ *****************************************************************************/
+static struct {
+ bool use_qt_time_limit;
+ QPointer<QWidget> last_widget;
+ int last_x, last_y;
+ int last_modifiers, last_button;
+ EventTime last_time;
+} qt_mac_dblclick = { false, 0, -1, -1, 0, 0, -2 };
+
+static bool app_do_modal = false; // modal mode
+extern QWidgetList *qt_modal_stack; // stack of modal widgets
+extern bool qt_tab_all_widgets; // from qapplication.cpp
+bool qt_mac_app_fullscreen = false;
+bool qt_scrollbar_jump_to_pos = false;
+static bool qt_mac_collapse_on_dblclick = true;
+extern int qt_antialiasing_threshold; // from qapplication.cpp
+QWidget * qt_button_down; // widget got last button-down
+QPointer<QWidget> qt_last_mouse_receiver;
+#ifndef QT_MAC_USE_COCOA
+static bool qt_button_down_in_content; // whether the button_down was in the content area.
+static bool qt_mac_previous_press_in_popup_mode = false;
+static bool qt_mac_no_click_through_mode = false;
+static int tablet_button_state = 0;
+#endif
+#if defined(QT_DEBUG)
+static bool appNoGrab = false; // mouse/keyboard grabbing
+#endif
+#ifndef QT_MAC_USE_COCOA
+static EventHandlerRef app_proc_handler = 0;
+static EventHandlerUPP app_proc_handlerUPP = 0;
+#endif
+static AEEventHandlerUPP app_proc_ae_handlerUPP = NULL;
+static EventHandlerRef tablet_proximity_handler = 0;
+static EventHandlerUPP tablet_proximity_UPP = 0;
+bool QApplicationPrivate::native_modal_dialog_active;
+
+Q_GUI_EXPORT bool qt_applefontsmoothing_enabled;
+
+/*****************************************************************************
+ External functions
+ *****************************************************************************/
+extern void qt_mac_beep(); //qsound_mac.mm
+extern Qt::KeyboardModifiers qt_mac_get_modifiers(int keys); //qkeymapper_mac.cpp
+extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
+extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
+extern OSWindowRef qt_mac_window_for(const QWidget*); //qwidget_mac.cpp
+extern QWidget *qt_mac_find_window(OSWindowRef); //qwidget_mac.cpp
+extern void qt_mac_set_cursor(const QCursor *); //qcursor_mac.cpp
+extern bool qt_mac_is_macsheet(const QWidget *); //qwidget_mac.cpp
+extern QString qt_mac_from_pascal_string(const Str255); //qglobal.cpp
+extern void qt_mac_command_set_enabled(MenuRef, UInt32, bool); //qmenu_mac.cpp
+extern bool qt_sendSpontaneousEvent(QObject *obj, QEvent *event); // qapplication.cpp
+extern void qt_mac_update_cursor(); // qcursor_mac.mm
+
+// Forward Decls
+void onApplicationWindowChangedActivation( QWidget*widget, bool activated );
+void onApplicationChangedActivation( bool activated );
+
+static void qt_mac_read_fontsmoothing_settings()
+{
+ qt_applefontsmoothing_enabled = true;
+ int w = 10, h = 10;
+ QImage image(w, h, QImage::Format_RGB32);
+ image.fill(0xffffffff);
+ QPainter p(&image);
+ p.drawText(0, h, "X\\");
+ p.end();
+
+ const int *bits = (const int *) ((const QImage &) image).bits();
+ int bpl = image.bytesPerLine() / 4;
+ for (int y=0; y<w; ++y) {
+ for (int x=0; x<h; ++x) {
+ int r = qRed(bits[x]);
+ int g = qGreen(bits[x]);
+ int b = qBlue(bits[x]);
+ if (r != g || r != b) {
+ qt_applefontsmoothing_enabled = true;
+ return;
+ }
+ }
+ bits += bpl;
+ }
+ qt_applefontsmoothing_enabled = false;
+}
+
+Q_GUI_EXPORT bool qt_mac_execute_apple_script(const char *script, long script_len, AEDesc *ret) {
+ OSStatus err;
+ AEDesc scriptTextDesc;
+ ComponentInstance theComponent = 0;
+ OSAID scriptID = kOSANullScript, resultID = kOSANullScript;
+
+ // set up locals to a known state
+ AECreateDesc(typeNull, 0, 0, &scriptTextDesc);
+ scriptID = kOSANullScript;
+ resultID = kOSANullScript;
+
+ // open the scripting component
+ theComponent = OpenDefaultComponent(kOSAComponentType, typeAppleScript);
+ if (!theComponent) {
+ err = paramErr;
+ goto bail;
+ }
+
+ // put the script text into an aedesc
+ err = AECreateDesc(typeUTF8Text, script, script_len, &scriptTextDesc);
+ if (err != noErr)
+ goto bail;
+
+ // compile the script
+ err = OSACompile(theComponent, &scriptTextDesc, kOSAModeNull, &scriptID);
+ if (err != noErr)
+ goto bail;
+
+ // run the script
+ err = OSAExecute(theComponent, scriptID, kOSANullScript, kOSAModeNull, &resultID);
+
+ // collect the results - if any
+ if (ret) {
+ AECreateDesc(typeNull, 0, 0, ret);
+ if (err == errOSAScriptError)
+ OSAScriptError(theComponent, kOSAErrorMessage, typeChar, ret);
+ else if (err == noErr && resultID != kOSANullScript)
+ OSADisplay(theComponent, resultID, typeChar, kOSAModeNull, ret);
+ }
+bail:
+ AEDisposeDesc(&scriptTextDesc);
+ if (scriptID != kOSANullScript)
+ OSADispose(theComponent, scriptID);
+ if (resultID != kOSANullScript)
+ OSADispose(theComponent, resultID);
+ if (theComponent)
+ CloseComponent(theComponent);
+ return err == noErr;
+}
+
+Q_GUI_EXPORT bool qt_mac_execute_apple_script(const char *script, AEDesc *ret)
+{
+ return qt_mac_execute_apple_script(script, qstrlen(script), ret);
+}
+
+Q_GUI_EXPORT bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret)
+{
+ const QByteArray l = script.toUtf8(); return qt_mac_execute_apple_script(l.constData(), l.size(), ret);
+}
+
+/* Resolution change magic */
+void qt_mac_display_change_callbk(CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void *)
+{
+#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
+ const bool resized = flags & kCGDisplayDesktopShapeChangedFlag;
+#else
+ Q_UNUSED(flags);
+ const bool resized = true;
+#endif
+ if (resized && qApp) {
+ if (QDesktopWidget *dw = qApp->desktop()) {
+ QResizeEvent *re = new QResizeEvent(dw->size(), dw->size());
+ QApplication::postEvent(dw, re);
+ QCoreGraphicsPaintEngine::cleanUpMacColorSpaces();
+ }
+ }
+}
+
+#ifdef DEBUG_PLATFORM_SETTINGS
+static void qt_mac_debug_palette(const QPalette &pal, const QPalette &pal2, const QString &where)
+{
+ const char *const groups[] = {"Active", "Disabled", "Inactive" };
+ const char *const roles[] = { "WindowText", "Button", "Light", "Midlight", "Dark", "Mid",
+ "Text", "BrightText", "ButtonText", "Base", "Window", "Shadow",
+ "Highlight", "HighlightedText", "Link", "LinkVisited" };
+ if (!where.isNull())
+ qDebug("qt-internal: %s", where.toLatin1().constData());
+ for(int grp = 0; grp < QPalette::NColorGroups; grp++) {
+ for(int role = 0; role < QPalette::NColorRoles; role++) {
+ QBrush b = pal.brush((QPalette::ColorGroup)grp, (QPalette::ColorRole)role);
+ QPixmap pm = b.texture();
+ qDebug(" %s::%s %d::%d::%d [%p]%s", groups[grp], roles[role], b.color().red(),
+ b.color().green(), b.color().blue(), pm.isNull() ? 0 : &pm,
+ pal2.brush((QPalette::ColorGroup)grp, (QPalette::ColorRole)role) != b ? " (*)" : "");
+ }
+ }
+
+}
+#else
+#define qt_mac_debug_palette(x, y, z)
+#endif
+
+//raise a notification
+#ifndef QT_MAC_USE_COCOA
+static NMRec qt_mac_notification = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+#endif
+void qt_mac_send_notification()
+{
+#ifndef QT_MAC_USE_COCOA
+ //send it
+ qt_mac_notification.nmMark = 1; //non-zero magic number
+ qt_mac_notification.qType = nmType;
+ NMInstall(&qt_mac_notification);
+#else
+ QMacCocoaAutoReleasePool pool;
+ [[NSApplication sharedApplication] requestUserAttention:NSInformationalRequest];
+#endif
+}
+
+void qt_mac_cancel_notification()
+{
+#ifndef QT_MAC_USE_COCOA
+ NMRemove(&qt_mac_notification);
+#else
+ QMacCocoaAutoReleasePool pool;
+ [[NSApplication sharedApplication] cancelUserAttentionRequest:NSInformationalRequest];
+#endif
+}
+
+#ifndef QT_MAC_USE_COCOA
+//find widget (and part) at a given point
+static short qt_mac_window_at(int x, int y, QWidget **w=0)
+{
+ Point p;
+ p.h = x;
+ p.v = y;
+ OSWindowRef wp;
+ WindowPartCode wpc;
+ OSStatus err = FindWindowOfClass(&p, kAllWindowClasses, &wp, &wpc);
+ if(err != noErr) {
+ if(w)
+ (*w) = 0;
+ return wpc;
+ }
+ if(w) {
+ if(wp) {
+ *w = qt_mac_find_window(wp);
+#if 0
+ if(!*w)
+ qWarning("QApplication: qt_mac_window_at: Couldn't find %d",(int)wp);
+#endif
+ } else {
+ *w = 0;
+ }
+ }
+ return wpc;
+}
+
+#endif
+
+void qt_mac_set_app_icon(const QPixmap &pixmap)
+{
+#ifndef QT_MAC_USE_COCOA
+ if(pixmap.isNull()) {
+ RestoreApplicationDockTileImage();
+ } else {
+ CGImageRef img = (CGImageRef)pixmap.macCGHandle();
+ SetApplicationDockTileImage(img);
+ CGImageRelease(img);
+ }
+#else
+ QMacCocoaAutoReleasePool pool;
+ NSImage *image = NULL;
+ if (pixmap.isNull()) {
+ // Get Application icon from bundle
+ image = [[NSImage imageNamed:@"NSApplicationIcon"] retain]; // released below
+ } else {
+ image = static_cast<NSImage *>(qt_mac_create_nsimage(pixmap));
+ }
+
+ [NSApp setApplicationIconImage:image];
+ [image release];
+#endif
+}
+
+Q_GUI_EXPORT void qt_mac_set_press_and_hold_context(bool b)
+{
+ Q_UNUSED(b);
+ qWarning("qt_mac_set_press_and_hold_context: This functionality is no longer available");
+}
+
+bool qt_nograb() // application no-grab option
+{
+#if defined(QT_DEBUG)
+ return appNoGrab;
+#else
+ return false;
+#endif
+}
+
+void qt_mac_update_os_settings()
+{
+ if (!qApp)
+ return;
+ if (!QApplication::startingUp()) {
+ static bool needToPolish = true;
+ if (needToPolish) {
+ QApplication::style()->polish(qApp);
+ needToPolish = false;
+ }
+ }
+ //focus mode
+ /* First worked as of 10.2.3 */
+ QSettings appleSettings(QLatin1String("apple.com"));
+ QVariant appleValue = appleSettings.value(QLatin1String("AppleKeyboardUIMode"), 0);
+ qt_tab_all_widgets = (appleValue.toInt() & 0x2);
+ //paging mode
+ /* First worked as of 10.2.3 */
+ appleValue = appleSettings.value(QLatin1String("AppleScrollerPagingBehavior"), false);
+ qt_scrollbar_jump_to_pos = appleValue.toBool();
+ //collapse
+ /* First worked as of 10.3.3 */
+ appleValue = appleSettings.value(QLatin1String("AppleMiniaturizeOnDoubleClick"), true);
+ qt_mac_collapse_on_dblclick = appleValue.toBool();
+
+ // Anti-aliasing threshold
+ appleValue = appleSettings.value(QLatin1String("AppleAntiAliasingThreshold"));
+ if (appleValue.isValid())
+ qt_antialiasing_threshold = appleValue.toInt();
+
+#ifdef DEBUG_PLATFORM_SETTINGS
+ qDebug("qt_mac_update_os_settings *********************************************************************");
+#endif
+ { // setup the global palette
+ QColor qc;
+ (void) QApplication::style(); // trigger creation of application style and system palettes
+ QPalette pal = *QApplicationPrivate::sys_pal;
+
+ pal.setBrush( QPalette::Active, QPalette::Highlight, qcolorForTheme(kThemeBrushPrimaryHighlightColor) );
+ pal.setBrush( QPalette::Inactive, QPalette::Highlight, qcolorForTheme(kThemeBrushSecondaryHighlightColor) );
+
+ pal.setBrush( QPalette::Disabled, QPalette::Highlight, qcolorForTheme(kThemeBrushSecondaryHighlightColor) );
+ pal.setBrush( QPalette::Active, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonActiveDarkShadow) );
+
+ pal.setBrush( QPalette::Inactive, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonInactiveDarkShadow) );
+ pal.setBrush( QPalette::Disabled, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonInactiveDarkShadow) );
+
+ qc = qcolorForThemeTextColor(kThemeTextColorDialogActive);
+ pal.setColor(QPalette::Active, QPalette::Text, qc);
+ pal.setColor(QPalette::Active, QPalette::WindowText, qc);
+ pal.setColor(QPalette::Active, QPalette::HighlightedText, qc);
+
+ qc = qcolorForThemeTextColor(kThemeTextColorDialogInactive);
+ pal.setColor(QPalette::Inactive, QPalette::Text, qc);
+ pal.setColor(QPalette::Inactive, QPalette::WindowText, qc);
+ pal.setColor(QPalette::Inactive, QPalette::HighlightedText, qc);
+ pal.setColor(QPalette::Disabled, QPalette::Text, qc);
+ pal.setColor(QPalette::Disabled, QPalette::WindowText, qc);
+ pal.setColor(QPalette::Disabled, QPalette::HighlightedText, qc);
+ pal.setBrush(QPalette::ToolTipBase, QColor(255, 255, 199));
+
+ if (!QApplicationPrivate::sys_pal || *QApplicationPrivate::sys_pal != pal) {
+ QApplicationPrivate::setSystemPalette(pal);
+ QApplication::setPalette(pal);
+ }
+#ifdef DEBUG_PLATFORM_SETTINGS
+ qt_mac_debug_palette(pal, QApplication::palette(), "Global Palette");
+#endif
+ }
+
+ QFont fnt = qfontForThemeFont(kThemeApplicationFont);
+#ifdef DEBUG_PLATFORM_SETTINGS
+ qDebug("qt-internal: Font for Application [%s::%d::%d::%d]",
+ fnt.family().toLatin1().constData(), fnt.pointSize(), fnt.bold(), fnt.italic());
+#endif
+ if (!QApplicationPrivate::sys_font || *QApplicationPrivate::sys_font != fnt)
+ QApplicationPrivate::setSystemFont(fnt);
+
+ { //setup the fonts
+ struct FontMap {
+ FontMap(const char *qc, short fk) : qt_class(qc), font_key(fk) { }
+ const char *const qt_class;
+ short font_key;
+ } mac_widget_fonts[] = {
+ FontMap("QPushButton", kThemePushButtonFont),
+ FontMap("QListView", kThemeViewsFont),
+ FontMap("QListBox", kThemeViewsFont),
+ FontMap("QTitleBar", kThemeWindowTitleFont),
+ FontMap("QMenuBar", kThemeMenuTitleFont),
+ FontMap("QMenu", kThemeMenuItemFont),
+ FontMap("QComboMenuItem", kThemeSystemFont),
+ FontMap("QHeaderView", kThemeSmallSystemFont),
+ FontMap("Q3Header", kThemeSmallSystemFont),
+ FontMap("QTipLabel", kThemeSmallSystemFont),
+ FontMap("QLabel", kThemeSystemFont),
+ FontMap("QToolButton", kThemeSmallSystemFont),
+ FontMap("QMenuItem", kThemeMenuItemFont), // It doesn't exist, but its unique.
+ FontMap("QComboLineEdit", kThemeViewsFont), // It doesn't exist, but its unique.
+ FontMap("QSmallFont", kThemeSmallSystemFont), // It doesn't exist, but its unique.
+ FontMap("QMiniFont", kThemeMiniSystemFont), // It doesn't exist, but its unique.
+ FontMap(0, 0) };
+ for(int i = 0; mac_widget_fonts[i].qt_class; i++) {
+ QFont fnt = qfontForThemeFont(mac_widget_fonts[i].font_key);
+ bool set_font = true;
+ FontHash *hash = qt_app_fonts_hash();
+ if (!hash->isEmpty()) {
+ FontHash::const_iterator it
+ = hash->constFind(mac_widget_fonts[i].qt_class);
+ if (it != hash->constEnd())
+ set_font = (fnt != *it);
+ }
+ if (set_font) {
+ QApplication::setFont(fnt, mac_widget_fonts[i].qt_class);
+#ifdef DEBUG_PLATFORM_SETTINGS
+ qDebug("qt-internal: Font for %s [%s::%d::%d::%d]", mac_widget_fonts[i].qt_class,
+ fnt.family().toLatin1().constData(), fnt.pointSize(), fnt.bold(), fnt.italic());
+#endif
+ }
+ }
+ }
+ QApplicationPrivate::initializeWidgetPaletteHash();
+#ifdef DEBUG_PLATFORM_SETTINGS
+ qDebug("qt_mac_update_os_settings END !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+#endif
+}
+
+void QApplicationPrivate::initializeWidgetPaletteHash()
+{
+ { //setup the palette
+ struct PaletteMap {
+ inline PaletteMap(const char *qc, ThemeBrush a, ThemeBrush i) :
+ qt_class(qc), active(a), inactive(i) { }
+ const char *const qt_class;
+ ThemeBrush active, inactive;
+ } mac_widget_colors[] = {
+ PaletteMap("QToolButton", kThemeTextColorBevelButtonActive, kThemeTextColorBevelButtonInactive),
+ PaletteMap("QAbstractButton", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
+ PaletteMap("QHeaderView", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
+ PaletteMap("Q3Header", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
+ PaletteMap("QComboBox", kThemeTextColorPopupButtonActive, kThemeTextColorPopupButtonInactive),
+ PaletteMap("QAbstractItemView", kThemeTextColorListView, kThemeTextColorDialogInactive),
+ PaletteMap("QMessageBoxLabel", kThemeTextColorAlertActive, kThemeTextColorAlertInactive),
+ PaletteMap("QTabBar", kThemeTextColorTabFrontActive, kThemeTextColorTabFrontInactive),
+ PaletteMap("QLabel", kThemeTextColorPlacardActive, kThemeTextColorPlacardInactive),
+ PaletteMap("QGroupBox", kThemeTextColorPlacardActive, kThemeTextColorPlacardInactive),
+ PaletteMap("QMenu", kThemeTextColorPopupLabelActive, kThemeTextColorPopupLabelInactive),
+ PaletteMap("QTextEdit", 0, 0),
+ PaletteMap("QTextControl", 0, 0),
+ PaletteMap("QLineEdit", 0, 0),
+ PaletteMap(0, 0, 0) };
+ QColor qc;
+ for(int i = 0; mac_widget_colors[i].qt_class; i++) {
+ QPalette pal;
+ if (mac_widget_colors[i].active != 0) {
+ qc = qcolorForThemeTextColor(mac_widget_colors[i].active);
+ pal.setColor(QPalette::Active, QPalette::Text, qc);
+ pal.setColor(QPalette::Active, QPalette::WindowText, qc);
+ pal.setColor(QPalette::Active, QPalette::HighlightedText, qc);
+ qc = qcolorForThemeTextColor(mac_widget_colors[i].inactive);
+ pal.setColor(QPalette::Inactive, QPalette::Text, qc);
+ pal.setColor(QPalette::Disabled, QPalette::Text, qc);
+ pal.setColor(QPalette::Inactive, QPalette::WindowText, qc);
+ pal.setColor(QPalette::Disabled, QPalette::WindowText, qc);
+ pal.setColor(QPalette::Inactive, QPalette::HighlightedText, qc);
+ pal.setColor(QPalette::Disabled, QPalette::HighlightedText, qc);
+ }
+ if (!strcmp(mac_widget_colors[i].qt_class, "QMenu")) {
+ qc = qcolorForThemeTextColor(kThemeTextColorMenuItemActive);
+ pal.setBrush(QPalette::ButtonText, qc);
+ qc = qcolorForThemeTextColor(kThemeTextColorMenuItemSelected);
+ pal.setBrush(QPalette::HighlightedText, qc);
+ qc = qcolorForThemeTextColor(kThemeTextColorMenuItemDisabled);
+ pal.setBrush(QPalette::Disabled, QPalette::Text, qc);
+ } else if (!strcmp(mac_widget_colors[i].qt_class, "QAbstractButton")
+ || !strcmp(mac_widget_colors[i].qt_class, "QHeaderView")
+ || !strcmp(mac_widget_colors[i].qt_class, "Q3Header")) { //special
+ pal.setColor(QPalette::Disabled, QPalette::ButtonText,
+ pal.color(QPalette::Disabled, QPalette::Text));
+ pal.setColor(QPalette::Inactive, QPalette::ButtonText,
+ pal.color(QPalette::Inactive, QPalette::Text));
+ pal.setColor(QPalette::Active, QPalette::ButtonText,
+ pal.color(QPalette::Active, QPalette::Text));
+ } else if (!strcmp(mac_widget_colors[i].qt_class, "QAbstractItemView")) {
+ pal.setBrush(QPalette::Active, QPalette::Highlight,
+ qcolorForTheme(kThemeBrushAlternatePrimaryHighlightColor));
+ qc = qcolorForThemeTextColor(kThemeTextColorMenuItemSelected);
+ pal.setBrush(QPalette::Active, QPalette::HighlightedText, qc);
+#if 1
+ pal.setBrush(QPalette::Inactive, QPalette::Text,
+ pal.brush(QPalette::Active, QPalette::Text));
+ pal.setBrush(QPalette::Inactive, QPalette::HighlightedText,
+ pal.brush(QPalette::Active, QPalette::Text));
+#endif
+ } else if (!strcmp(mac_widget_colors[i].qt_class, "QTextEdit")
+ || !strcmp(mac_widget_colors[i].qt_class, "QTextControl")) {
+ pal.setBrush(QPalette::Inactive, QPalette::Text,
+ pal.brush(QPalette::Active, QPalette::Text));
+ pal.setBrush(QPalette::Inactive, QPalette::HighlightedText,
+ pal.brush(QPalette::Active, QPalette::Text));
+ } else if (!strcmp(mac_widget_colors[i].qt_class, "QLineEdit")) {
+ pal.setBrush(QPalette::Disabled, QPalette::Base,
+ pal.brush(QPalette::Active, QPalette::Base));
+ }
+
+ bool set_palette = true;
+ PaletteHash *phash = qt_app_palettes_hash();
+ if (!phash->isEmpty()) {
+ PaletteHash::const_iterator it
+ = phash->constFind(mac_widget_colors[i].qt_class);
+ if (it != phash->constEnd())
+ set_palette = (pal != *it);
+ }
+ if (set_palette) {
+ QApplication::setPalette(pal, mac_widget_colors[i].qt_class);
+#ifdef DEBUG_PLATFORM_SETTINGS
+ qt_mac_debug_palette(pal, QApplication::palette(), QLatin1String("Palette for ") + QString::fromLatin1(mac_widget_colors[i].qt_class));
+#endif
+ }
+ }
+ }
+}
+
+static void qt_mac_event_release(EventRef &event)
+{
+ ReleaseEvent(event);
+ event = 0;
+}
+#ifndef QT_MAC_USE_COCOA
+static void qt_mac_event_release(QWidget *w, EventRef &event)
+{
+ if (event) {
+ QWidget *widget = 0;
+ if (GetEventParameter(event, kEventParamQWidget, typeQWidget, 0, sizeof(widget), 0, &widget) == noErr
+ && w == widget) {
+ if (IsEventInQueue(GetMainEventQueue(), event))
+ RemoveEventFromQueue(GetMainEventQueue(), event);
+ qt_mac_event_release(event);
+ }
+ }
+}
+
+static bool qt_mac_event_remove(EventRef &event)
+{
+ if (event) {
+ if (IsEventInQueue(GetMainEventQueue(), event))
+ RemoveEventFromQueue(GetMainEventQueue(), event);
+ qt_mac_event_release(event);
+ return true;
+ }
+ return false;
+}
+#endif
+
+/* sheets */
+#ifndef QT_MAC_USE_COCOA
+static EventRef request_showsheet_pending = 0;
+#endif
+void qt_event_request_showsheet(QWidget *w)
+{
+ Q_ASSERT(qt_mac_is_macsheet(w));
+#ifdef QT_MAC_USE_COCOA
+ [NSApp beginSheet:qt_mac_window_for(w) modalForWindow:qt_mac_window_for(w->parentWidget())
+ modalDelegate:nil didEndSelector:nil contextInfo:0];
+#else
+ qt_mac_event_remove(request_showsheet_pending);
+ CreateEvent(0, kEventClassQt, kEventQtRequestShowSheet, GetCurrentEventTime(),
+ kEventAttributeUserEvent, &request_showsheet_pending);
+ SetEventParameter(request_showsheet_pending, kEventParamQWidget, typeQWidget, sizeof(w), &w);
+ PostEventToQueue(GetMainEventQueue(), request_showsheet_pending, kEventPriorityStandard);
+#endif
+}
+
+static void qt_post_window_change_event(QWidget *widget)
+{
+ qt_widget_private(widget)->needWindowChange = true;
+ QEvent *glWindowChangeEvent = new QEvent(QEvent::MacGLWindowChange);
+ QApplication::postEvent(widget, glWindowChangeEvent);
+}
+
+/*
+ Posts updates to all child and grandchild OpenGL widgets for the given widget.
+*/
+static void qt_mac_update_child_gl_widgets(QWidget *widget)
+{
+ // Update all OpenGL child widgets for the given widget.
+ QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget)->glWidgets;
+ QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
+ QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();
+
+ for (;it != end; ++it) {
+ qt_post_window_change_event(it->widget);
+ }
+}
+
+/*
+ Sends updates to all child and grandchild gl widgets that have updates pending.
+*/
+void qt_mac_send_posted_gl_updates(QWidget *widget)
+{
+ QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget)->glWidgets;
+ QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
+ QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();
+
+ for (;it != end; ++it) {
+ QWidget *glWidget = it->widget;
+ if (qt_widget_private(glWidget)->needWindowChange) {
+ QEvent glChangeEvent(QEvent::MacGLWindowChange);
+ QApplication::sendEvent(glWidget, &glChangeEvent);
+ }
+ }
+}
+
+/*
+ Posts updates to all OpenGL widgets within the window that the given widget intersects.
+*/
+static void qt_mac_update_intersected_gl_widgets(QWidget *widget)
+{
+#ifndef QT_MAC_USE_COCOA
+ QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget->window())->glWidgets;
+ if (glWidgets.isEmpty())
+ return;
+
+ // Exit if the window has not been created yet (mapToGlobal/size will force create it)
+ if (widget->testAttribute(Qt::WA_WState_Created) == false || HIViewGetWindow(qt_mac_nativeview_for(widget)) == 0)
+ return;
+
+ const QRect globalWidgetRect = QRect(widget->mapToGlobal(QPoint(0, 0)), widget->size());
+
+ QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
+ QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();
+
+ for (;it != end; ++it){
+ QWidget *glWidget = it->widget;
+ const QRect globalGlWidgetRect = QRect(glWidget->mapToGlobal(QPoint(0, 0)), glWidget->size());
+ if (globalWidgetRect.intersects(globalGlWidgetRect)) {
+ qt_post_window_change_event(glWidget);
+ it->lastUpdateWidget = widget;
+ } else if (it->lastUpdateWidget == widget) {
+ // Update the gl wigets that the widget intersected the last time around,
+ // and that we are not intersecting now. This prevents paint errors when the
+ // intersecting widget leaves a gl widget.
+ qt_post_window_change_event(glWidget);
+ it->lastUpdateWidget = 0;
+ }
+ }
+#else
+ Q_UNUSED(widget);
+#endif
+}
+
+/*
+ Posts a kEventQtRequestWindowChange event to the main Carbon event queue.
+*/
+static EventRef request_window_change_pending = 0;
+Q_GUI_EXPORT void qt_event_request_window_change()
+{
+ if(request_window_change_pending)
+ return;
+
+ CreateEvent(0, kEventClassQt, kEventQtRequestWindowChange, GetCurrentEventTime(),
+ kEventAttributeUserEvent, &request_window_change_pending);
+ PostEventToQueue(GetMainEventQueue(), request_window_change_pending, kEventPriorityHigh);
+}
+
+/* window changing. This is a hack around Apple's missing functionality, pending the toolbox
+ team fix. --Sam */
+Q_GUI_EXPORT void qt_event_request_window_change(QWidget *widget)
+{
+ if (!widget)
+ return;
+
+ // Post a kEventQtRequestWindowChange event. This event is semi-public,
+ // don't remove this line!
+ qt_event_request_window_change();
+
+ // Post update request on gl widgets unconditionally.
+ if (qt_widget_private(widget)->isGLWidget == true) {
+ qt_post_window_change_event(widget);
+ return;
+ }
+
+ qt_mac_update_child_gl_widgets(widget);
+ qt_mac_update_intersected_gl_widgets(widget);
+}
+
+/* activation */
+static struct {
+ QPointer<QWidget> widget;
+ EventRef event;
+ EventLoopTimerRef timer;
+ EventLoopTimerUPP timerUPP;
+} request_activate_pending = { 0, 0, 0, 0 };
+bool qt_event_remove_activate()
+{
+ if (request_activate_pending.timer) {
+ RemoveEventLoopTimer(request_activate_pending.timer);
+ request_activate_pending.timer = 0;
+ }
+ if (request_activate_pending.event)
+ qt_mac_event_release(request_activate_pending.event);
+ return true;
+}
+
+void qt_event_activate_timer_callbk(EventLoopTimerRef r, void *)
+{
+ EventLoopTimerRef otc = request_activate_pending.timer;
+ qt_event_remove_activate();
+ if (r == otc && !request_activate_pending.widget.isNull()) {
+ const QWidget *tlw = request_activate_pending.widget->window();
+ Qt::WindowType wt = tlw->windowType();
+ if (tlw->isVisible()
+ && ((wt != Qt::Desktop && wt != Qt::Popup && wt != Qt::Tool) || tlw->isModal())) {
+ CreateEvent(0, kEventClassQt, kEventQtRequestActivate, GetCurrentEventTime(),
+ kEventAttributeUserEvent, &request_activate_pending.event);
+ PostEventToQueue(GetMainEventQueue(), request_activate_pending.event, kEventPriorityHigh);
+ }
+ }
+}
+
+void qt_event_request_activate(QWidget *w)
+{
+ if (w == request_activate_pending.widget)
+ return;
+
+ /* We put these into a timer because due to order of events being sent we need to be sure this
+ comes from inside of the event loop */
+ qt_event_remove_activate();
+ if (!request_activate_pending.timerUPP)
+ request_activate_pending.timerUPP = NewEventLoopTimerUPP(qt_event_activate_timer_callbk);
+ request_activate_pending.widget = w;
+ InstallEventLoopTimer(GetMainEventLoop(), 0, 0, request_activate_pending.timerUPP, 0, &request_activate_pending.timer);
+}
+
+
+/* menubars */
+#ifndef QT_MAC_USE_COCOA
+static EventRef request_menubarupdate_pending = 0;
+#endif
+void qt_event_request_menubarupdate()
+{
+#ifndef QT_MAC_USE_COCOA
+ if (request_menubarupdate_pending) {
+ if (IsEventInQueue(GetMainEventQueue(), request_menubarupdate_pending))
+ return;
+#ifdef DEBUG_DROPPED_EVENTS
+ qDebug("%s:%d Whoa, we dropped an event on the floor!", __FILE__, __LINE__);
+#endif
+ }
+
+ CreateEvent(0, kEventClassQt, kEventQtRequestMenubarUpdate, GetCurrentEventTime(),
+ kEventAttributeUserEvent, &request_menubarupdate_pending);
+ PostEventToQueue(GetMainEventQueue(), request_menubarupdate_pending, kEventPriorityHigh);
+#else
+ // Just call this. The request has the benefit that we don't call this multiple times, but
+ // we can optimize this.
+ QMenuBar::macUpdateMenuBar();
+#endif
+}
+
+#ifndef QT_MAC_USE_COCOA
+//context menu
+static EventRef request_context_pending = 0;
+static void qt_event_request_context(QWidget *w=0, EventRef *where=0)
+{
+ if (!where)
+ where = &request_context_pending;
+ if (*where)
+ return;
+ CreateEvent(0, kEventClassQt, kEventQtRequestContext, GetCurrentEventTime(),
+ kEventAttributeUserEvent, where);
+ if (w)
+ SetEventParameter(*where, kEventParamQWidget, typeQWidget, sizeof(w), &w);
+ PostEventToQueue(GetMainEventQueue(), *where, kEventPriorityStandard);
+}
+#endif
+
+void QApplicationPrivate::createEventDispatcher()
+{
+ Q_Q(QApplication);
+ if (q->type() != QApplication::Tty)
+ eventDispatcher = new QEventDispatcherMac(q);
+ else
+ eventDispatcher = new QEventDispatcherUNIX(q);
+}
+
+/* clipboard */
+void qt_event_send_clipboard_changed()
+{
+#ifndef QT_MAC_USE_COCOA
+ AppleEvent ae;
+ if (AECreateAppleEvent(kEventClassQt, typeAEClipboardChanged, 0, kAutoGenerateReturnID, kAnyTransactionID, &ae) != noErr)
+ qDebug("Can't happen!!");
+ AppleEvent reply;
+ AESend(&ae, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, 0, 0);
+#endif
+}
+
+/* app menu */
+static QMenu *qt_mac_dock_menu = 0;
+Q_GUI_EXPORT void qt_mac_set_dock_menu(QMenu *menu)
+{
+ qt_mac_dock_menu = menu;
+#ifdef QT_MAC_USE_COCOA
+ [NSApp setDockMenu:menu->macMenu()];
+#else
+ SetApplicationDockTileMenu(menu->macMenu());
+#endif
+}
+
+/* events that hold pointers to widgets, must be cleaned up like this */
+void qt_mac_event_release(QWidget *w)
+{
+ if (w) {
+#ifndef QT_MAC_USE_COCOA
+ qt_mac_event_release(w, request_showsheet_pending);
+ qt_mac_event_release(w, request_context_pending);
+#endif
+ if (w == qt_mac_dock_menu) {
+ qt_mac_dock_menu = 0;
+#ifndef QT_MAC_USE_COCOA
+ SetApplicationDockTileMenu(0);
+#else
+ [NSApp setDockMenu:0];
+#endif
+ }
+ }
+}
+
+struct QMacAppleEventTypeSpec {
+ AEEventClass mac_class;
+ AEEventID mac_id;
+} app_apple_events[] = {
+ { kCoreEventClass, kAEQuitApplication },
+ { kCoreEventClass, kAEOpenDocuments },
+ { kInternetEventClass, kAEGetURL },
+};
+
+#ifndef QT_MAC_USE_COCOA
+
+#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
+enum
+{
+ kEventMouseScroll = 11,
+ kEventParamMouseWheelSmoothVerticalDelta = 'saxy',
+ kEventParamMouseWheelSmoothHorizontalDelta = 'saxx',
+};
+#endif
+
+/* watched events */
+static EventTypeSpec app_events[] = {
+ { kEventClassQt, kEventQtRequestWindowChange },
+ { kEventClassQt, kEventQtRequestShowSheet },
+ { kEventClassQt, kEventQtRequestContext },
+ { kEventClassQt, kEventQtRequestActivate },
+ { kEventClassQt, kEventQtRequestMenubarUpdate },
+
+ { kEventClassWindow, kEventWindowActivated },
+ { kEventClassWindow, kEventWindowDeactivated },
+
+ { kEventClassMouse, kEventMouseScroll },
+ { kEventClassMouse, kEventMouseWheelMoved },
+ { kEventClassMouse, kEventMouseDown },
+ { kEventClassMouse, kEventMouseUp },
+ { kEventClassMouse, kEventMouseDragged },
+ { kEventClassMouse, kEventMouseMoved },
+
+ { kEventClassTablet, kEventTabletProximity },
+
+ { kEventClassApplication, kEventAppActivated },
+ { kEventClassApplication, kEventAppDeactivated },
+ { kEventClassApplication, kEventAppAvailableWindowBoundsChanged },
+
+ // { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent },
+ { kEventClassKeyboard, kEventRawKeyModifiersChanged },
+ { kEventClassKeyboard, kEventRawKeyRepeat },
+ { kEventClassKeyboard, kEventRawKeyUp },
+ { kEventClassKeyboard, kEventRawKeyDown },
+
+ { kEventClassCommand, kEventCommandProcess },
+
+ { kEventClassAppleEvent, kEventAppleEvent },
+
+ { kAppearanceEventClass, kAEAppearanceChanged }
+};
+
+void qt_init_app_proc_handler()
+{
+ InstallEventHandler(GetApplicationEventTarget(), app_proc_handlerUPP,
+ GetEventTypeCount(app_events), app_events, (void *)qApp,
+ &app_proc_handler);
+}
+#endif // QT_MAC_USE_COCOA
+
+static void qt_init_tablet_proximity_handler()
+{
+ EventTypeSpec tabletProximityEvent = { kEventClassTablet, kEventTabletProximity };
+ InstallEventHandler(GetEventMonitorTarget(), tablet_proximity_UPP,
+ 1, &tabletProximityEvent, qApp, &tablet_proximity_handler);
+}
+
+static void qt_release_tablet_proximity_handler()
+{
+ RemoveEventHandler(tablet_proximity_handler);
+}
+
+QString QApplicationPrivate::appName() const
+{
+ static QString applName;
+ if (applName.isEmpty()) {
+ applName = QCoreApplicationPrivate::macMenuBarName();
+ ProcessSerialNumber psn;
+ if (applName.isEmpty() && qt_is_gui_used && GetCurrentProcess(&psn) == noErr) {
+ QCFString cfstr;
+ CopyProcessName(&psn, &cfstr);
+ applName = cfstr;
+ }
+ }
+ return applName;
+}
+
+void qt_release_app_proc_handler()
+{
+#ifndef QT_MAC_USE_COCOA
+ if (app_proc_handler) {
+ RemoveEventHandler(app_proc_handler);
+ app_proc_handler = 0;
+ }
+#endif
+}
+
+void qt_color_profile_changed(CFNotificationCenterRef, void *, CFStringRef, const void *,
+ CFDictionaryRef)
+{
+ QCoreGraphicsPaintEngine::cleanUpMacColorSpaces();
+}
+/* platform specific implementations */
+void qt_init(QApplicationPrivate *priv, int)
+{
+ if (qt_is_gui_used) {
+ CGDisplayRegisterReconfigurationCallback(qt_mac_display_change_callbk, 0);
+ CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter();
+ CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
+ kCMDeviceUnregisteredNotification, 0,
+ CFNotificationSuspensionBehaviorDeliverImmediately);
+ CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
+ kCMDefaultDeviceNotification, 0,
+ CFNotificationSuspensionBehaviorDeliverImmediately);
+ CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
+ kCMDeviceProfilesNotification, 0,
+ CFNotificationSuspensionBehaviorDeliverImmediately);
+ CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
+ kCMDefaultDeviceProfileNotification, 0,
+ CFNotificationSuspensionBehaviorDeliverImmediately);
+ ProcessSerialNumber psn;
+ if (GetCurrentProcess(&psn) == noErr) {
+ // Jambi needs to transform itself since most people aren't "used"
+ // to putting things in bundles, but other people may actually not
+ // want to tranform the process (running as a helper or something)
+ // so don't do that for them. This means checking both LSUIElement
+ // and LSBackgroundOnly. If you set them both... well, you
+ // shouldn't do that.
+
+ bool forceTransform = true;
+ CFTypeRef value = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(),
+ CFSTR("LSUIElement"));
+ if (value) {
+ CFTypeID valueType = CFGetTypeID(value);
+ // Officially it's supposed to be a string, a boolean makes sense, so we'll check.
+ // A number less so, but OK.
+ if (valueType == CFStringGetTypeID())
+ forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
+ else if (valueType == CFBooleanGetTypeID())
+ forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
+ else if (valueType == CFNumberGetTypeID()) {
+ int valueAsInt;
+ CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberIntType, &valueAsInt);
+ forceTransform = !valueAsInt;
+ }
+ }
+
+ if (forceTransform) {
+ value = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(),
+ CFSTR("LSBackgroundOnly"));
+ if (value) {
+ CFTypeID valueType = CFGetTypeID(value);
+ if (valueType == CFBooleanGetTypeID())
+ forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
+ else if (valueType == CFStringGetTypeID())
+ forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
+ else if (valueType == CFNumberGetTypeID()) {
+ int valueAsInt;
+ CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberIntType, &valueAsInt);
+ forceTransform = !valueAsInt;
+ }
+ }
+ }
+
+
+ if (forceTransform) {
+ TransformProcessType(&psn, kProcessTransformToForegroundApplication);
+ }
+ }
+ }
+
+ char **argv = priv->argv;
+
+ // Get command line params
+ if (int argc = priv->argc) {
+ int i, j = 1;
+ QString passed_psn;
+ for(i=1; i < argc; i++) {
+ if (argv[i] && *argv[i] != '-') {
+ argv[j++] = argv[i];
+ continue;
+ }
+ QByteArray arg(argv[i]);
+#if defined(QT_DEBUG)
+ if (arg == "-nograb")
+ appNoGrab = !appNoGrab;
+ else
+#endif // QT_DEBUG
+ if (arg.left(5) == "-psn_") {
+ passed_psn = QString::fromLatin1(arg.mid(6));
+ } else {
+ argv[j++] = argv[i];
+ }
+ }
+ if (j < priv->argc) {
+ priv->argv[j] = 0;
+ priv->argc = j;
+ }
+
+ //special hack to change working directory (for an app bundle) when running from finder
+ if (!passed_psn.isNull() && QDir::currentPath() == QLatin1String("/")) {
+ QCFType<CFURLRef> bundleURL(CFBundleCopyBundleURL(CFBundleGetMainBundle()));
+ QString qbundlePath = QCFString(CFURLCopyFileSystemPath(bundleURL,
+ kCFURLPOSIXPathStyle));
+ if (qbundlePath.endsWith(QLatin1String(".app")))
+ QDir::setCurrent(qbundlePath.section(QLatin1Char('/'), 0, -2));
+ }
+ }
+
+ QMacPasteboardMime::initialize();
+
+ qApp->setObjectName(priv->appName());
+ if (qt_is_gui_used) {
+ QColormap::initialize();
+ QFont::initialize();
+ QCursorData::initialize();
+ QCoreGraphicsPaintEngine::initialize();
+#ifndef QT_NO_ACCESSIBILITY
+ QAccessible::initialize();
+#endif
+ QMacInputContext::initialize();
+ QApplicationPrivate::inputContext = new QMacInputContext;
+
+ if (QApplication::desktopSettingsAware())
+ qt_mac_update_os_settings();
+#ifndef QT_MAC_USE_COCOA
+ if (!app_proc_handler) {
+ app_proc_handlerUPP = NewEventHandlerUPP(QApplicationPrivate::globalEventProcessor);
+ qt_init_app_proc_handler();
+ }
+
+#endif
+ if (!app_proc_ae_handlerUPP && !QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
+ app_proc_ae_handlerUPP = AEEventHandlerUPP(QApplicationPrivate::globalAppleEventProcessor);
+ for(uint i = 0; i < sizeof(app_apple_events) / sizeof(QMacAppleEventTypeSpec); ++i) {
+ // Install apple event handler, but avoid overwriting an already
+ // existing handler (it means a 3rd party application has installed one):
+ SRefCon refCon = 0;
+ AEEventHandlerUPP current_handler = NULL;
+ AEGetEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id, &current_handler, &refCon, false);
+ if (!current_handler)
+ AEInstallEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id,
+ app_proc_ae_handlerUPP, SRefCon(qApp), false);
+ }
+ }
+
+ if (QApplicationPrivate::app_style) {
+ QEvent ev(QEvent::Style);
+ qt_sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
+ }
+ }
+ if (QApplication::desktopSettingsAware())
+ QApplicationPrivate::qt_mac_apply_settings();
+
+ // Cocoa application delegate
+#ifdef QT_MAC_USE_COCOA
+ NSApplication *cocoaApp = [QNSApplication sharedApplication];
+ qt_redirectNSApplicationSendEvent();
+
+ QMacCocoaAutoReleasePool pool;
+ id oldDelegate = [cocoaApp delegate];
+ QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *newDelegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
+ Q_ASSERT(newDelegate);
+ [newDelegate setQtPrivate:priv];
+ // Only do things that make sense to do once, otherwise we crash.
+ if (oldDelegate != newDelegate && !QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
+ [newDelegate setReflectionDelegate:oldDelegate];
+ [cocoaApp setDelegate:newDelegate];
+
+ QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader = [[QT_MANGLE_NAMESPACE(QCocoaMenuLoader) alloc] init];
+ if ([NSBundle loadNibNamed:@"qt_menu" owner:qtMenuLoader] == false) {
+ qFatal("Qt internal error: qt_menu.nib could not be loaded. The .nib file"
+ " should be placed in QtGui.framework/Versions/Current/Resources/ "
+ " or in the resources directory of your application bundle.");
+ }
+
+ [cocoaApp setMenu:[qtMenuLoader menu]];
+ [newDelegate setMenuLoader:qtMenuLoader];
+ [qtMenuLoader release];
+ }
+#endif
+ // Register for Carbon tablet proximity events on the event monitor target.
+ // This means that we should receive proximity events even when we aren't the active application.
+ if (!tablet_proximity_handler) {
+ tablet_proximity_UPP = NewEventHandlerUPP(QApplicationPrivate::tabletProximityCallback);
+ qt_init_tablet_proximity_handler();
+ }
+ priv->native_modal_dialog_active = false;
+
+ qt_mac_read_fontsmoothing_settings();
+}
+
+void qt_release_apple_event_handler()
+{
+ if(app_proc_ae_handlerUPP) {
+ for(uint i = 0; i < sizeof(app_apple_events) / sizeof(QMacAppleEventTypeSpec); ++i)
+ AERemoveEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id,
+ app_proc_ae_handlerUPP, true);
+ DisposeAEEventHandlerUPP(app_proc_ae_handlerUPP);
+ app_proc_ae_handlerUPP = 0;
+ }
+}
+
+/*****************************************************************************
+ qt_cleanup() - cleans up when the application is finished
+ *****************************************************************************/
+
+void qt_cleanup()
+{
+ CGDisplayRemoveReconfigurationCallback(qt_mac_display_change_callbk, 0);
+ CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter();
+ CFNotificationCenterRemoveObserver(center, qApp, kCMDeviceUnregisteredNotification, 0);
+ CFNotificationCenterRemoveObserver(center, qApp, kCMDefaultDeviceNotification, 0);
+ CFNotificationCenterRemoveObserver(center, qApp, kCMDeviceProfilesNotification, 0);
+ CFNotificationCenterRemoveObserver(center, qApp, kCMDefaultDeviceProfileNotification, 0);
+
+#ifndef QT_MAC_USE_COCOA
+ qt_release_app_proc_handler();
+ if (app_proc_handlerUPP) {
+ DisposeEventHandlerUPP(app_proc_handlerUPP);
+ app_proc_handlerUPP = 0;
+ }
+#endif
+ qt_release_apple_event_handler();
+ qt_release_tablet_proximity_handler();
+ if (tablet_proximity_UPP)
+ DisposeEventHandlerUPP(tablet_proximity_UPP);
+
+ QPixmapCache::clear();
+ if (qt_is_gui_used) {
+#ifndef QT_NO_ACCESSIBILITY
+ QAccessible::cleanup();
+#endif
+ QMacInputContext::cleanup();
+ QCursorData::cleanup();
+ QFont::cleanup();
+ QColormap::cleanup();
+ if (qt_mac_safe_pdev) {
+ delete qt_mac_safe_pdev;
+ qt_mac_safe_pdev = 0;
+ }
+ extern void qt_mac_unregister_widget(); // qapplication_mac.cpp
+ qt_mac_unregister_widget();
+ }
+}
+
+/*****************************************************************************
+ Platform specific global and internal functions
+ *****************************************************************************/
+void qt_updated_rootinfo()
+{
+}
+
+bool qt_wstate_iconified(WId)
+{
+ return false;
+}
+
+/*****************************************************************************
+ Platform specific QApplication members
+ *****************************************************************************/
+extern QWidget * mac_mouse_grabber;
+extern QWidget * mac_keyboard_grabber;
+
+#ifdef QT3_SUPPORT
+void QApplication::setMainWidget(QWidget *mainWidget)
+{
+ QApplicationPrivate::main_widget = mainWidget;
+ if (QApplicationPrivate::main_widget && windowIcon().isNull()
+ && QApplicationPrivate::main_widget->testAttribute(Qt::WA_SetWindowIcon))
+ setWindowIcon(QApplicationPrivate::main_widget->windowIcon());
+}
+#endif
+#ifndef QT_NO_CURSOR
+
+/*****************************************************************************
+ QApplication cursor stack
+ *****************************************************************************/
+
+void QApplication::setOverrideCursor(const QCursor &cursor)
+{
+ qApp->d_func()->cursor_list.prepend(cursor);
+
+#ifdef QT_MAC_USE_COCOA
+ qt_mac_update_cursor();
+#else
+ if (qApp && qApp->activeWindow())
+ qt_mac_set_cursor(&qApp->d_func()->cursor_list.first());
+#endif
+}
+
+void QApplication::restoreOverrideCursor()
+{
+ if (qApp->d_func()->cursor_list.isEmpty())
+ return;
+ qApp->d_func()->cursor_list.removeFirst();
+
+#ifdef QT_MAC_USE_COCOA
+ qt_mac_update_cursor();
+#else
+ if (qApp && qApp->activeWindow()) {
+ const QCursor def(Qt::ArrowCursor);
+ qt_mac_set_cursor(qApp->d_func()->cursor_list.isEmpty() ? &def : &qApp->d_func()->cursor_list.first());
+ }
+#endif
+}
+#endif // QT_NO_CURSOR
+
+QWidget *QApplication::topLevelAt(const QPoint &p)
+{
+#ifndef QT_MAC_USE_COCOA
+ QWidget *widget;
+ qt_mac_window_at(p.x(), p.y(), &widget);
+ return widget;
+#else
+ // Use a cache to avoid iterate through the whole list of windows for all
+ // calls to to topLevelAt. We e.g. do this for each and every mouse
+ // move since we need to find the widget under mouse:
+ if (topLevelAt_cache && topLevelAt_cache->frameGeometry().contains(p))
+ return topLevelAt_cache;
+
+ // INVARIANT: Cache miss. Go through the list if windows instead:
+ QMacCocoaAutoReleasePool pool;
+ NSPoint cocoaPoint = flipPoint(p);
+ NSInteger windowCount;
+ NSCountWindows(&windowCount);
+ if (windowCount <= 0)
+ return 0; // There's no window to find!
+
+ QVarLengthArray<NSInteger> windowList(windowCount);
+ NSWindowList(windowCount, windowList.data());
+ int firstQtWindowFound = -1;
+ for (int i = 0; i < windowCount; ++i) {
+ NSWindow *window = [NSApp windowWithWindowNumber:windowList[i]];
+ if (window) {
+ QWidget *candidateWindow = [window QT_MANGLE_NAMESPACE(qt_qwidget)];
+ if (candidateWindow && firstQtWindowFound == -1)
+ firstQtWindowFound = i;
+
+ if (NSPointInRect(cocoaPoint, [window frame])) {
+ // Check to see if there's a hole in the window where the mask is.
+ // If there is, we should just continue to see if there is a window below.
+ if (candidateWindow && !candidateWindow->mask().isEmpty()) {
+ QPoint localPoint = candidateWindow->mapFromGlobal(p);
+ if (!candidateWindow->mask().contains(localPoint))
+ continue;
+ else
+ return candidateWindow;
+ } else {
+ if (i == firstQtWindowFound) {
+ // The cache will only work when the window under mouse is
+ // top most (that is, not partially obscured by other windows.
+ // And we only set it if no mask is present to optimize for the common case:
+ topLevelAt_cache = candidateWindow;
+ }
+ return candidateWindow;
+ }
+ }
+ }
+ }
+
+ topLevelAt_cache = 0;
+ return 0;
+#endif
+}
+
+/*****************************************************************************
+ Main event loop
+ *****************************************************************************/
+
+bool QApplicationPrivate::modalState()
+{
+ return app_do_modal;
+}
+
+#ifdef QT_MAC_USE_COCOA
+#endif
+
+void QApplicationPrivate::enterModal_sys(QWidget *widget)
+{
+#ifdef DEBUG_MODAL_EVENTS
+ Q_ASSERT(widget);
+ qDebug("Entering modal state with %s::%s::%p (%d)", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(),
+ widget, qt_modal_stack ? (int)qt_modal_stack->count() : -1);
+#endif
+ if (!qt_modal_stack)
+ qt_modal_stack = new QWidgetList;
+
+ dispatchEnterLeave(0, qt_last_mouse_receiver);
+ qt_last_mouse_receiver = 0;
+
+ qt_modal_stack->insert(0, widget);
+ if (!app_do_modal)
+ qt_event_request_menubarupdate();
+ app_do_modal = true;
+ qt_button_down = 0;
+
+#ifdef QT_MAC_USE_COCOA
+ if (!qt_mac_is_macsheet(widget))
+ QEventDispatcherMacPrivate::beginModalSession(widget);
+#endif
+}
+
+void QApplicationPrivate::leaveModal_sys(QWidget *widget)
+{
+ if (qt_modal_stack && qt_modal_stack->removeAll(widget)) {
+#ifdef DEBUG_MODAL_EVENTS
+ qDebug("Leaving modal state with %s::%s::%p (%d)", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(),
+ widget, qt_modal_stack->count());
+#endif
+ if (qt_modal_stack->isEmpty()) {
+ delete qt_modal_stack;
+ qt_modal_stack = 0;
+ QPoint p(QCursor::pos());
+ app_do_modal = false;
+ QWidget* w = 0;
+ if (QWidget *grabber = QWidget::mouseGrabber())
+ w = grabber;
+ else
+ w = QApplication::widgetAt(p.x(), p.y());
+ dispatchEnterLeave(w, qt_last_mouse_receiver); // send synthetic enter event
+ qt_last_mouse_receiver = w;
+ }
+#ifdef QT_MAC_USE_COCOA
+ if (!qt_mac_is_macsheet(widget))
+ QEventDispatcherMacPrivate::endModalSession(widget);
+#endif
+ }
+#ifdef DEBUG_MODAL_EVENTS
+ else qDebug("Failure to remove %s::%s::%p -- %p", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(), widget, qt_modal_stack);
+#endif
+ app_do_modal = (qt_modal_stack != 0);
+ if (!app_do_modal)
+ qt_event_request_menubarupdate();
+}
+
+QWidget *QApplicationPrivate::tryModalHelper_sys(QWidget *top)
+{
+#ifndef QT_MAC_USE_COCOA
+ if(top && qt_mac_is_macsheet(top) && !IsWindowVisible(qt_mac_window_for(top))) {
+ if(OSWindowRef wp = GetFrontWindowOfClass(kSheetWindowClass, true)) {
+ if(QWidget *sheet = qt_mac_find_window(wp))
+ top = sheet;
+ }
+ }
+#endif
+ return top;
+}
+
+#ifndef QT_MAC_USE_COCOA
+static bool qt_try_modal(QWidget *widget, EventRef event)
+{
+ QWidget * top = 0;
+
+ if (QApplicationPrivate::tryModalHelper(widget, &top))
+ return true;
+
+ // INVARIANT: widget is modally shaddowed within its
+ // window, and should therefore not handle the event.
+ // However, if the window is not active, the event
+ // might suggest that we should bring it to front:
+
+ bool block_event = false;
+
+ if (event) {
+ switch (GetEventClass(event)) {
+ case kEventClassMouse:
+ case kEventClassKeyboard:
+ block_event = true;
+ break;
+ }
+ }
+
+ QWidget *activeWidget = QApplication::activeWindow();
+ if ((!activeWidget || QApplicationPrivate::isBlockedByModal(activeWidget)) &&
+ top->isWindow() && block_event && !QApplicationPrivate::native_modal_dialog_active)
+ top->raise();
+
+#ifdef DEBUG_MODAL_EVENTS
+ qDebug("%s:%d -- final decision! (%s)", __FILE__, __LINE__, block_event ? "false" : "true");
+#endif
+ return !block_event;
+}
+#endif
+
+OSStatus QApplicationPrivate::tabletProximityCallback(EventHandlerCallRef, EventRef carbonEvent,
+ void *)
+{
+ OSType eventClass = GetEventClass(carbonEvent);
+ UInt32 eventKind = GetEventKind(carbonEvent);
+ if (eventClass != kEventClassTablet || eventKind != kEventTabletProximity)
+ return eventNotHandledErr;
+
+ // Get the current point of the device and its unique ID.
+ ::TabletProximityRec proxRec;
+ GetEventParameter(carbonEvent, kEventParamTabletProximityRec, typeTabletProximityRec, 0,
+ sizeof(proxRec), 0, &proxRec);
+ qt_dispatchTabletProximityEvent(proxRec);
+ return noErr;
+}
+
+OSStatus
+QApplicationPrivate::globalEventProcessor(EventHandlerCallRef er, EventRef event, void *data)
+{
+#ifndef QT_MAC_USE_COCOA
+ QApplication *app = (QApplication *)data;
+ QScopedLoopLevelCounter loopLevelCounter(app->d_func()->threadData);
+ long result;
+ if (app->filterEvent(&event, &result))
+ return result;
+ if(app->macEventFilter(er, event)) //someone else ate it
+ return noErr;
+ QPointer<QWidget> widget;
+
+ /*We assume all events are handled and in
+ the code below we set it to false when we know we didn't handle it, this
+ will let rogue events through (shouldn't really happen, but better safe
+ than sorry) */
+ bool handled_event=true;
+ UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
+ switch(eclass)
+ {
+ case kEventClassQt:
+ if(ekind == kEventQtRequestShowSheet) {
+ request_showsheet_pending = 0;
+ QWidget *widget = 0;
+ GetEventParameter(event, kEventParamQWidget, typeQWidget, 0,
+ sizeof(widget), 0, &widget);
+ if(widget) {
+ if (widget->macEvent(er, event))
+ return noErr;
+ WindowPtr window = qt_mac_window_for(widget);
+ bool just_show = !qt_mac_is_macsheet(widget);
+ if(!just_show) {
+ OSStatus err = ShowSheetWindow(window, qt_mac_window_for(widget->parentWidget()));
+ if(err != noErr)
+ qWarning("Qt: QWidget: Unable to show as sheet %s::%s [%ld]", widget->metaObject()->className(),
+ widget->objectName().toLocal8Bit().constData(), long(err));
+ just_show = true;
+ }
+ if(just_show) //at least the window will be visible, but the sheet flag doesn't work sadly (probalby too many sheets)
+ ShowHide(window, true);
+ }
+ } else if(ekind == kEventQtRequestWindowChange) {
+ qt_mac_event_release(request_window_change_pending);
+ } else if(ekind == kEventQtRequestMenubarUpdate) {
+ qt_mac_event_release(request_menubarupdate_pending);
+ QMenuBar::macUpdateMenuBar();
+ } else if(ekind == kEventQtRequestActivate) {
+ qt_mac_event_release(request_activate_pending.event);
+ if(request_activate_pending.widget) {
+ QWidget *tlw = request_activate_pending.widget->window();
+ if (tlw->macEvent(er, event))
+ return noErr;
+ request_activate_pending.widget = 0;
+ tlw->activateWindow();
+ SelectWindow(qt_mac_window_for(tlw));
+ }
+ } else if(ekind == kEventQtRequestContext) {
+ bool send = false;
+ if ((send = (event == request_context_pending)))
+ qt_mac_event_release(request_context_pending);
+ if(send) {
+ //figure out which widget to send it to
+ QPoint where = QCursor::pos();
+ QWidget *widget = 0;
+ GetEventParameter(event, kEventParamQWidget, typeQWidget, 0,
+ sizeof(widget), 0, &widget);
+ if(!widget) {
+ if(qt_button_down)
+ widget = qt_button_down;
+ else
+ widget = QApplication::widgetAt(where.x(), where.y());
+ }
+ if(widget && !isBlockedByModal(widget)) {
+ if (widget->macEvent(er, event))
+ return noErr;
+ QPoint plocal(widget->mapFromGlobal(where));
+ const Qt::KeyboardModifiers keyboardModifiers = qt_mac_get_modifiers(GetCurrentEventKeyModifiers());
+ QContextMenuEvent qme(QContextMenuEvent::Mouse, plocal, where, keyboardModifiers);
+ QApplication::sendEvent(widget, &qme);
+ if(qme.isAccepted()) { //once this happens the events before are pitched
+ qt_button_down = 0;
+ qt_mac_dblclick.last_widget = 0;
+ }
+ } else {
+ handled_event = false;
+ }
+ }
+ } else {
+ handled_event = false;
+ }
+ break;
+ case kEventClassTablet:
+ switch (ekind) {
+ case kEventTabletProximity:
+ // Get the current point of the device and its unique ID.
+ ::TabletProximityRec proxRec;
+ GetEventParameter(event, kEventParamTabletProximityRec, typeTabletProximityRec, 0,
+ sizeof(proxRec), 0, &proxRec);
+ qt_dispatchTabletProximityEvent(proxRec);
+ }
+ break;
+ case kEventClassMouse:
+ {
+ static const int kEventParamQAppSeenMouseEvent = 'QASM';
+ // Check if we've seen the event, if we have we shouldn't process
+ // it again as it may lead to spurious "double events"
+ bool seenEvent;
+ if (GetEventParameter(event, kEventParamQAppSeenMouseEvent,
+ typeBoolean, 0, sizeof(bool), 0, &seenEvent) == noErr) {
+ if (seenEvent)
+ return eventNotHandledErr;
+ }
+ seenEvent = true;
+ SetEventParameter(event, kEventParamQAppSeenMouseEvent, typeBoolean,
+ sizeof(bool), &seenEvent);
+
+ Point where;
+ bool inNonClientArea = false;
+ GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, 0,
+ sizeof(where), 0, &where);
+#if defined(DEBUG_MOUSE_MAPS)
+ const char *edesc = 0;
+ switch(ekind) {
+ case kEventMouseDown: edesc = "MouseButtonPress"; break;
+ case kEventMouseUp: edesc = "MouseButtonRelease"; break;
+ case kEventMouseDragged: case kEventMouseMoved: edesc = "MouseMove"; break;
+ case kEventMouseScroll: edesc = "MouseWheelScroll"; break;
+ case kEventMouseWheelMoved: edesc = "MouseWheelMove"; break;
+ }
+ if(ekind == kEventMouseDown || ekind == kEventMouseUp)
+ qDebug("Handling mouse: %s", edesc);
+#endif
+ QEvent::Type etype = QEvent::None;
+ Qt::KeyboardModifiers modifiers;
+ {
+ UInt32 mac_modifiers = 0;
+ GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, 0,
+ sizeof(mac_modifiers), 0, &mac_modifiers);
+ modifiers = qt_mac_get_modifiers(mac_modifiers);
+ }
+ Qt::MouseButtons buttons;
+ {
+ UInt32 mac_buttons = 0;
+ GetEventParameter(event, kEventParamMouseChord, typeUInt32, 0,
+ sizeof(mac_buttons), 0, &mac_buttons);
+ if (ekind != kEventMouseWheelMoved)
+ buttons = qt_mac_get_buttons(mac_buttons);
+ else
+ buttons = QApplication::mouseButtons();
+ }
+
+ int wheel_deltaX = 0;
+ int wheel_deltaY = 0;
+ static EventRef compatibilityEvent = 0;
+
+ if (ekind == kEventMouseScroll) {
+ // kEventMouseScroll is the new way of dealing with mouse wheel
+ // events (kEventMouseWheelMoved was the old). kEventMouseScroll results
+ // in much smoother scrolling when using Mighty Mouse or TrackPad. For
+ // compatibility with older applications, carbon will also send us
+ // kEventMouseWheelMoved events if we dont eat this event
+ // (actually two events; one for horizontal and one for vertical).
+ // As a results of this, and to make sure we dont't receive duplicate events,
+ // we try to detect when this happend by checking the 'compatibilityEvent'.
+ // Since delta is delivered as pixels rather than degrees, we need to
+ // convert from pixels to degrees in a sensible manner.
+ // It looks like 1/4 degrees per pixel behaves most native.
+ // (NB: Qt expects the unit for delta to be 8 per degree):
+ const int pixelsToDegrees = 2;
+ SInt32 mdelt = 0;
+ GetEventParameter(event, kEventParamMouseWheelSmoothHorizontalDelta, typeSInt32, 0,
+ sizeof(mdelt), 0, &mdelt);
+ wheel_deltaX = mdelt * pixelsToDegrees;
+ mdelt = 0;
+ GetEventParameter(event, kEventParamMouseWheelSmoothVerticalDelta, typeSInt32, 0,
+ sizeof(mdelt), 0, &mdelt);
+ wheel_deltaY = mdelt * pixelsToDegrees;
+ GetEventParameter(event, kEventParamEventRef, typeEventRef, 0,
+ sizeof(compatibilityEvent), 0, &compatibilityEvent);
+ } else if (ekind == kEventMouseWheelMoved) {
+ if (event != compatibilityEvent) {
+ compatibilityEvent = 0;
+ int mdelt = 0;
+ GetEventParameter(event, kEventParamMouseWheelDelta, typeSInt32, 0,
+ sizeof(mdelt), 0, &mdelt);
+ EventMouseWheelAxis axis;
+ GetEventParameter(event, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0,
+ sizeof(axis), 0, &axis);
+
+ // Remove acceleration, and use either -120 or 120 as delta:
+ if (axis == kEventMouseWheelAxisX)
+ wheel_deltaX = qBound(-120, int(mdelt * 10000), 120);
+ else
+ wheel_deltaY = qBound(-120, int(mdelt * 10000), 120);
+ }
+ }
+
+ Qt::MouseButton button = Qt::NoButton;
+ if(ekind == kEventMouseDown || ekind == kEventMouseUp) {
+ EventMouseButton mac_button = 0;
+ GetEventParameter(event, kEventParamMouseButton, typeMouseButton, 0,
+ sizeof(mac_button), 0, &mac_button);
+ button = qt_mac_get_button(mac_button);
+ }
+
+ switch(ekind) {
+ case kEventMouseDown:
+ etype = QEvent::MouseButtonPress;
+ break;
+ case kEventMouseUp:
+ etype = QEvent::MouseButtonRelease;
+ break;
+ case kEventMouseDragged:
+ case kEventMouseMoved:
+ etype = QEvent::MouseMove;
+ break;
+ }
+
+ const bool inPopupMode = app->d_func()->inPopupMode();
+
+ // A click outside a popup closes the popup. Make sure
+ // that no events are generated for the release part of that click.
+ // (The press goes to the popup and closes it.)
+ if (etype == QEvent::MouseButtonPress) {
+ qt_mac_previous_press_in_popup_mode = inPopupMode;
+ } else if (qt_mac_previous_press_in_popup_mode && !inPopupMode && etype == QEvent::MouseButtonRelease) {
+ qt_mac_previous_press_in_popup_mode = false;
+ handled_event = true;
+#if defined(DEBUG_MOUSE_MAPS)
+ qDebug("Bail out early due to qt_mac_previous_press_in_popup_mode");
+#endif
+ break; // break from case kEventClassMouse
+ }
+
+ //figure out which widget to send it to
+ if(inPopupMode) {
+ QWidget *popup = qApp->activePopupWidget();
+ if (qt_button_down && qt_button_down->window() == popup) {
+ widget = qt_button_down;
+ } else {
+ QPoint pos = popup->mapFromGlobal(QPoint(where.h, where.v));
+ widget = popup->childAt(pos);
+ }
+ if(!widget)
+ widget = popup;
+ } else {
+ if(mac_mouse_grabber) {
+ widget = mac_mouse_grabber;
+ } else if (qt_button_down) {
+ widget = qt_button_down;
+ } else {
+ {
+ WindowPtr window = 0;
+ if(GetEventParameter(event, kEventParamWindowRef, typeWindowRef, 0,
+ sizeof(window), 0, &window) != noErr)
+ FindWindowOfClass(&where, kAllWindowClasses, &window, 0);
+ if(window) {
+ HIViewRef hiview;
+ if(HIViewGetViewForMouseEvent(HIViewGetRoot(window), event, &hiview) == noErr) {
+ widget = QWidget::find((WId)hiview);
+ if (widget) {
+ // Make sure we didn't pass over a widget with a "fake hole" in it.
+ QWidget *otherWidget = QApplication::widgetAt(where.h, where.v);
+ if (otherWidget && otherWidget->testAttribute(Qt::WA_MouseNoMask))
+ widget = otherWidget;
+ }
+ }
+ }
+ }
+ if(!widget) //fallback
+ widget = QApplication::widgetAt(where.h, where.v);
+ if(ekind == kEventMouseUp && widget) {
+ short part = qt_mac_window_at(where.h, where.v);
+ if(part == inDrag) {
+ UInt32 count = 0;
+ GetEventParameter(event, kEventParamClickCount, typeUInt32, NULL,
+ sizeof(count), NULL, &count);
+ if(count == 2 && qt_mac_collapse_on_dblclick) {
+ if (widget->macEvent(er, event))
+ return noErr;
+ widget->setWindowState(widget->windowState() | Qt::WindowMinimized);
+ //we send a hide to be like X11/Windows
+ QEvent e(QEvent::Hide);
+ QApplication::sendSpontaneousEvent(widget, &e);
+ break;
+ }
+ }
+ }
+ }
+ }
+ if (widget && widget->macEvent(er, event))
+ return noErr;
+ WindowPartCode wpc = qt_mac_window_at(where.h, where.v, 0);
+ if (wpc == inProxyIcon && modifiers == Qt::ControlModifier && buttons != Qt::NoButton) {
+ QIconDragEvent e;
+ QApplication::sendSpontaneousEvent(widget, &e);
+ if (e.isAccepted()) {
+ return noErr; // IconDrag ate it.
+ }
+ }
+ if (inPopupMode == false
+ && (qt_button_down == 0 || qt_button_down_in_content == false)
+ && (wpc != inContent && wpc != inStructure)) {
+ inNonClientArea = true;
+ switch (etype) {
+ case QEvent::MouseButtonPress: {
+ UInt32 count = 0;
+ GetEventParameter(event, kEventParamClickCount, typeUInt32, 0,
+ sizeof(count), 0, &count);
+ if(count % 2 || count == 0) {
+ etype = QEvent::NonClientAreaMouseButtonPress;
+ } else {
+ etype = QEvent::NonClientAreaMouseButtonDblClick;
+ }} break;
+ case QEvent::MouseButtonRelease:
+ etype = QEvent::NonClientAreaMouseButtonRelease;
+ break;
+ case QEvent::MouseMove:
+ if (widget == 0 || widget->hasMouseTracking())
+ etype = QEvent::NonClientAreaMouseMove;
+ break;
+ default:
+ break;
+ }
+ }
+
+ if(qt_mac_find_window((FrontWindow()))) { //set the cursor up
+ QCursor cursor(Qt::ArrowCursor);
+ QWidget *cursor_widget = widget;
+ if(cursor_widget && cursor_widget == qt_button_down && ekind == kEventMouseUp)
+ cursor_widget = QApplication::widgetAt(where.h, where.v);
+ if(cursor_widget) { //only over the app, do we set a cursor..
+ if(!qApp->d_func()->cursor_list.isEmpty()) {
+ cursor = qApp->d_func()->cursor_list.first();
+ } else {
+ for(; cursor_widget; cursor_widget = cursor_widget->parentWidget()) {
+ QWExtra *extra = cursor_widget->d_func()->extraData();
+ if(extra && extra->curs && cursor_widget->isEnabled()) {
+ cursor = *extra->curs;
+ break;
+ }
+ }
+ }
+ }
+ qt_mac_set_cursor(&cursor);
+ }
+
+ //This mouse button state stuff looks like this on purpose
+ //although it looks hacky it is VERY intentional..
+ if(widget && app_do_modal && !qt_try_modal(widget, event)) {
+ if(ekind == kEventMouseDown && qt_mac_is_macsheet(QApplication::activeModalWidget()))
+ QApplication::activeModalWidget()->parentWidget()->activateWindow(); //sheets have a parent
+ handled_event = false;
+#if defined(DEBUG_MOUSE_MAPS)
+ qDebug("Bail out early due to qt_try_modal");
+#endif
+ break;
+ }
+
+ UInt32 tabletEventType = 0;
+ GetEventParameter(event, kEventParamTabletEventType, typeUInt32, 0,
+ sizeof(tabletEventType), 0, &tabletEventType);
+ if (tabletEventType == kEventTabletPoint) {
+ TabletPointRec tabletPointRec;
+ GetEventParameter(event, kEventParamTabletPointRec, typeTabletPointRec, 0,
+ sizeof(tabletPointRec), 0, &tabletPointRec);
+ QEvent::Type t = QEvent::TabletMove; //default
+ int new_tablet_button_state = tabletPointRec.buttons ? 1 : 0;
+ if (new_tablet_button_state != tablet_button_state)
+ if (new_tablet_button_state)
+ t = QEvent::TabletPress;
+ else
+ t = QEvent::TabletRelease;
+ tablet_button_state = new_tablet_button_state;
+
+ QMacTabletHash *tabletHash = qt_mac_tablet_hash();
+ if (!tabletHash->contains(tabletPointRec.deviceID) && t != QEvent::TabletRelease) {
+ // Never discard TabletRelease events as they may be delivered *after* TabletLeaveProximity events
+ qWarning("handleTabletEvent: This tablet device is unknown"
+ " (received no proximity event for it). Discarding event.");
+ return false;
+ }
+ QTabletDeviceData &deviceData = tabletHash->operator[](tabletPointRec.deviceID);
+ if (t == QEvent::TabletPress) {
+ deviceData.widgetToGetPress = widget;
+ } else if (t == QEvent::TabletRelease && deviceData.widgetToGetPress) {
+ widget = deviceData.widgetToGetPress;
+ deviceData.widgetToGetPress = 0;
+ }
+
+ if (widget) {
+ int tiltX = ((int)tabletPointRec.tiltX)/(32767/64); // 32K -> 60
+ int tiltY = ((int)tabletPointRec.tiltY)/(-32767/64); // 32K -> 60
+ HIPoint hiPoint;
+ GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, 0, sizeof(HIPoint), 0, &hiPoint);
+ QPointF hiRes(hiPoint.x, hiPoint.y);
+ QPoint global(where.h, where.v);
+
+
+
+ QPoint local(widget->mapFromGlobal(global));
+ int z = 0;
+ qreal rotation = 0.0;
+ qreal tp = 0.0;
+ // Again from the Wacom.h header
+
+ if (deviceData.capabilityMask & 0x0200) // Z-axis
+ z = tabletPointRec.absZ;
+
+ if (deviceData.capabilityMask & 0x0800) // Tangential pressure
+ tp = tabletPointRec.tangentialPressure / 32767.0;
+
+ if (deviceData.capabilityMask & 0x2000) // Rotation
+ rotation = qreal(tabletPointRec.rotation) / 64.0;
+
+ QTabletEvent e(t, local, global, hiRes, deviceData.tabletDeviceType,
+ deviceData.tabletPointerType,
+ qreal(tabletPointRec.pressure / qreal(0xffff)), tiltX, tiltY,
+ tp, rotation, z, modifiers, deviceData.tabletUniqueID);
+ QApplication::sendSpontaneousEvent(widget, &e);
+ if (e.isAccepted()) {
+ if (t == QEvent::TabletPress) {
+ qt_button_down = widget;
+ } else if (t == QEvent::TabletRelease) {
+ qt_button_down = 0;
+ }
+#if defined(DEBUG_MOUSE_MAPS)
+ qDebug("Bail out early due to tablet acceptance");
+#endif
+ break;
+ }
+ }
+ }
+
+ if(ekind == kEventMouseDown) {
+ qt_mac_no_click_through_mode = false;
+ const short windowPart = qt_mac_window_at(where.h, where.v, 0);
+ // Menubar almost always wins.
+ if (!inPopupMode && windowPart == inMenuBar) {
+ MenuSelect(where); //allow menu tracking
+ return noErr;
+ }
+
+ if (widget && !(GetCurrentKeyModifiers() & cmdKey)) {
+ extern bool qt_isGenuineQWidget(const QWidget *); // qwidget_mac.cpp
+ QWidget *window = widget->window();
+ bool genuineQtWidget = qt_isGenuineQWidget(widget); // the widget, not the window.
+ window->raise();
+
+ bool needActivate = (window->windowType() != Qt::Desktop)
+ && (window->windowType() != Qt::Popup)
+ && !qt_mac_is_macsheet(window);
+ if (needActivate && (!window->isModal() && qobject_cast<QDockWidget *>(window)))
+ needActivate = false;
+
+ if (genuineQtWidget && needActivate)
+ needActivate = !window->isActiveWindow()
+ || !IsWindowActive(qt_mac_window_for(window));
+
+ if (needActivate) {
+ window->activateWindow();
+ if (!qt_mac_can_clickThrough(widget)) {
+ qt_mac_no_click_through_mode = true;
+ handled_event = false;
+#if defined(DEBUG_MOUSE_MAPS)
+ qDebug("Bail out early due to qt_mac_canClickThrough %s::%s", widget->metaObject()->className(),
+ widget->objectName().toLocal8Bit().constData());
+#endif
+ break;
+ }
+ }
+ }
+
+ if(qt_mac_dblclick.last_widget &&
+ qt_mac_dblclick.last_x != -1 && qt_mac_dblclick.last_y != -1 &&
+ QRect(qt_mac_dblclick.last_x-2, qt_mac_dblclick.last_y-2, 4, 4).contains(QPoint(where.h, where.v))) {
+ if(qt_mac_dblclick.use_qt_time_limit) {
+ EventTime now = GetEventTime(event);
+ if(qt_mac_dblclick.last_time != -2 && qt_mac_dblclick.last_widget == widget &&
+ now - qt_mac_dblclick.last_time <= ((double)QApplicationPrivate::mouse_double_click_time)/1000 &&
+ qt_mac_dblclick.last_button == button)
+ etype = QEvent::MouseButtonDblClick;
+ } else {
+ UInt32 count = 0;
+ GetEventParameter(event, kEventParamClickCount, typeUInt32, 0,
+ sizeof(count), 0, &count);
+ if(!(count % 2) && qt_mac_dblclick.last_modifiers == modifiers &&
+ qt_mac_dblclick.last_widget == widget && qt_mac_dblclick.last_button == button)
+ etype = QEvent::MouseButtonDblClick;
+ }
+ if(etype == QEvent::MouseButtonDblClick)
+ qt_mac_dblclick.last_widget = 0;
+ }
+ if(etype != QEvent::MouseButtonDblClick) {
+ qt_mac_dblclick.last_x = where.h;
+ qt_mac_dblclick.last_y = where.v;
+ } else {
+ qt_mac_dblclick.last_x = qt_mac_dblclick.last_y = -1;
+ }
+ } else if(qt_mac_no_click_through_mode) {
+ if(ekind == kEventMouseUp)
+ qt_mac_no_click_through_mode = false;
+ handled_event = false;
+#if defined(DEBUG_MOUSE_MAPS)
+ qDebug("Bail out early due to qt_mac_no_click_through_mode");
+#endif
+ break;
+ }
+
+ QPointer<QWidget> leaveAfterRelease = 0;
+ switch(ekind) {
+ case kEventMouseUp:
+ if (!buttons) {
+ if (!inPopupMode && !QWidget::mouseGrabber())
+ leaveAfterRelease = qt_button_down;
+ qt_button_down = 0;
+ }
+ break;
+ case kEventMouseDown: {
+ if (!qt_button_down)
+ qt_button_down = widget;
+ WindowPartCode wpc = qt_mac_window_at(where.h, where.v, 0);
+ qt_button_down_in_content = (wpc == inContent || wpc == inStructure);
+ break; }
+ }
+
+ // Check if we should send enter/leave events:
+ switch(ekind) {
+ case kEventMouseDragged:
+ case kEventMouseMoved:
+ case kEventMouseUp:
+ case kEventMouseDown: {
+ // If we are in popup mode, widget will point to the current popup no matter
+ // where the mouse cursor is. In that case find out if the mouse cursor is
+ // really over the popup in order to send correct enter / leave envents.
+ QWidget * const enterLeaveWidget = (inPopupMode || ekind == kEventMouseUp) ?
+ QApplication::widgetAt(where.h, where.v) : static_cast<QWidget*>(widget);
+
+ if ((QWidget *) qt_last_mouse_receiver != enterLeaveWidget || inNonClientArea) {
+#ifdef DEBUG_MOUSE_MAPS
+ qDebug("Entering: %p - %s (%s), Leaving %s (%s)", (QWidget*)enterLeaveWidget,
+ enterLeaveWidget ? enterLeaveWidget->metaObject()->className() : "none",
+ enterLeaveWidget ? enterLeaveWidget->objectName().toLocal8Bit().constData() : "",
+ qt_last_mouse_receiver ? qt_last_mouse_receiver->metaObject()->className() : "none",
+ qt_last_mouse_receiver ? qt_last_mouse_receiver->objectName().toLocal8Bit().constData() : "");
+#endif
+
+ QWidget * const mouseGrabber = QWidget::mouseGrabber();
+
+ if (inPopupMode) {
+ QWidget *enter = enterLeaveWidget;
+ QWidget *leave = qt_last_mouse_receiver;
+ if (mouseGrabber) {
+ QWidget * const popupWidget = qApp->activePopupWidget();
+ if (leave == popupWidget)
+ enter = mouseGrabber;
+ if (enter == popupWidget)
+ leave = mouseGrabber;
+ if ((enter == mouseGrabber && leave == popupWidget)
+ || (leave == mouseGrabber && enter == popupWidget)) {
+ QApplicationPrivate::dispatchEnterLeave(enter, leave);
+ qt_last_mouse_receiver = enter;
+ }
+ } else {
+ QApplicationPrivate::dispatchEnterLeave(enter, leave);
+ qt_last_mouse_receiver = enter;
+ }
+ } else if ((!qt_button_down || !qt_last_mouse_receiver) && !mouseGrabber && !leaveAfterRelease) {
+ QApplicationPrivate::dispatchEnterLeave(enterLeaveWidget, qt_last_mouse_receiver);
+ qt_last_mouse_receiver = enterLeaveWidget;
+ }
+ }
+ break; }
+ }
+
+ if(widget) {
+ QPoint p(where.h, where.v);
+ QPoint plocal(widget->mapFromGlobal(p));
+ if(etype == QEvent::MouseButtonPress) {
+ qt_mac_dblclick.last_widget = widget;
+ qt_mac_dblclick.last_modifiers = modifiers;
+ qt_mac_dblclick.last_button = button;
+ qt_mac_dblclick.last_time = GetEventTime(event);
+ }
+
+ if (wheel_deltaX || wheel_deltaY) {
+#ifndef QT_NO_WHEELEVENT
+ if (wheel_deltaX) {
+ QWheelEvent qwe(plocal, p, wheel_deltaX, buttons, modifiers, Qt::Horizontal);
+ QApplication::sendSpontaneousEvent(widget, &qwe);
+ if (!qwe.isAccepted() && QApplicationPrivate::focus_widget && QApplicationPrivate::focus_widget != widget) {
+ QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(p), p,
+ wheel_deltaX, buttons, modifiers, Qt::Horizontal);
+ QApplication::sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
+ if (!qwe2.isAccepted())
+ handled_event = false;
+ }
+ }
+ if (wheel_deltaY) {
+ QWheelEvent qwe(plocal, p, wheel_deltaY, buttons, modifiers, Qt::Vertical);
+ QApplication::sendSpontaneousEvent(widget, &qwe);
+ if (!qwe.isAccepted() && QApplicationPrivate::focus_widget && QApplicationPrivate::focus_widget != widget) {
+ QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(p), p,
+ wheel_deltaY, buttons, modifiers, Qt::Vertical);
+ QApplication::sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
+ if (!qwe2.isAccepted())
+ handled_event = false;
+ }
+ }
+#endif // QT_NO_WHEELEVENT
+ } else {
+#ifdef QMAC_SPEAK_TO_ME
+ const int speak_keys = Qt::AltModifier | Qt::ShiftModifier;
+ if(etype == QMouseEvent::MouseButtonDblClick && ((modifiers & speak_keys) == speak_keys)) {
+ QVariant v = widget->property("displayText");
+ if(!v.isValid()) v = widget->property("text");
+ if(!v.isValid()) v = widget->property("windowTitle");
+ if(v.isValid()) {
+ QString s = v.toString();
+ s.replace(QRegExp(QString::fromLatin1("(\\&|\\<[^\\>]*\\>)")), QLatin1String(""));
+ SpeechChannel ch;
+ NewSpeechChannel(0, &ch);
+ SpeakText(ch, s.toLatin1().constData(), s.length());
+ DisposeSpeechChannel(ch);
+ }
+ }
+#endif
+ Qt::MouseButton buttonToSend = button;
+ static bool lastButtonTranslated = false;
+ if(ekind == kEventMouseDown &&
+ button == Qt::LeftButton && (modifiers & Qt::MetaModifier)) {
+ buttonToSend = Qt::RightButton;
+ lastButtonTranslated = true;
+ } else if(ekind == kEventMouseUp && lastButtonTranslated) {
+ buttonToSend = Qt::RightButton;
+ lastButtonTranslated = false;
+ }
+ QMouseEvent qme(etype, plocal, p, buttonToSend, buttons, modifiers);
+ QApplication::sendSpontaneousEvent(widget, &qme);
+ if(!qme.isAccepted() || inNonClientArea)
+ handled_event = false;
+ }
+
+ if (leaveAfterRelease) {
+ QWidget *enter = QApplication::widgetAt(where.h, where.v);
+ QApplicationPrivate::dispatchEnterLeave(enter, leaveAfterRelease);
+ qt_last_mouse_receiver = enter;
+ leaveAfterRelease = 0;
+ }
+
+ if(ekind == kEventMouseDown &&
+ ((button == Qt::RightButton) ||
+ (button == Qt::LeftButton && (modifiers & Qt::MetaModifier))))
+ qt_event_request_context();
+
+#ifdef DEBUG_MOUSE_MAPS
+ const char *event_desc = edesc;
+ if(etype == QEvent::MouseButtonDblClick)
+ event_desc = "Double Click";
+ else if(etype == QEvent::NonClientAreaMouseButtonPress)
+ event_desc = "NonClientMousePress";
+ else if(etype == QEvent::NonClientAreaMouseButtonRelease)
+ event_desc = "NonClientMouseRelease";
+ else if(etype == QEvent::NonClientAreaMouseMove)
+ event_desc = "NonClientMouseMove";
+ else if(etype == QEvent::NonClientAreaMouseButtonDblClick)
+ event_desc = "NonClientMouseDblClick";
+ qDebug("%d %d (%d %d) - Would send (%s) event to %p %s %s (%d 0x%08x 0x%08x %d)", p.x(), p.y(),
+ plocal.x(), plocal.y(), event_desc, (QWidget*)widget,
+ widget ? widget->objectName().toLocal8Bit().constData() : "*Unknown*",
+ widget ? widget->metaObject()->className() : "*Unknown*",
+ button, (int)buttons, (int)modifiers, wheel_deltaX);
+#endif
+ } else {
+ handled_event = false;
+ }
+ break;
+ }
+ case kEventClassTextInput:
+ case kEventClassKeyboard: {
+ EventRef key_event = event;
+ if(eclass == kEventClassTextInput) {
+ Q_ASSERT(ekind == kEventTextInputUnicodeForKeyEvent);
+ OSStatus err = GetEventParameter(event, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0,
+ sizeof(key_event), 0, &key_event);
+ Q_ASSERT(err == noErr);
+ Q_UNUSED(err);
+ }
+ const UInt32 key_ekind = GetEventKind(key_event);
+ Q_ASSERT(GetEventClass(key_event) == kEventClassKeyboard);
+
+ if(key_ekind == kEventRawKeyDown)
+ qt_keymapper_private()->updateKeyMap(er, key_event, data);
+ if(mac_keyboard_grabber)
+ widget = mac_keyboard_grabber;
+ else if (app->activePopupWidget())
+ widget = (app->activePopupWidget()->focusWidget() ?
+ app->activePopupWidget()->focusWidget() : app->activePopupWidget());
+ else if(QApplication::focusWidget())
+ widget = QApplication::focusWidget();
+ else
+ widget = app->activeWindow();
+
+ if (widget) {
+ if (widget->macEvent(er, event))
+ return noErr;
+ } else {
+ // Darn, I need to update tho modifier state, even though
+ // Qt itself isn't getting them, otherwise the keyboard state get inconsistent.
+ if (key_ekind == kEventRawKeyModifiersChanged) {
+ UInt32 modifiers = 0;
+ GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
+ sizeof(modifiers), 0, &modifiers);
+ extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object); // qkeymapper_mac.cpp
+ // Just send it to the qApp for the time being.
+ qt_mac_send_modifiers_changed(modifiers, qApp);
+ }
+ handled_event = false;
+ break;
+ }
+
+ if(app_do_modal && !qt_try_modal(widget, key_event))
+ break;
+ if (eclass == kEventClassTextInput) {
+ handled_event = false;
+ } else {
+ handled_event = qt_keymapper_private()->translateKeyEvent(widget, er, key_event, data,
+ widget == mac_keyboard_grabber);
+ }
+ break; }
+ case kEventClassWindow: {
+ WindowRef wid = 0;
+ GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
+ sizeof(WindowRef), 0, &wid);
+ widget = qt_mac_find_window(wid);
+ if (widget && widget->macEvent(er, event))
+ return noErr;
+ if(ekind == kEventWindowActivated) {
+ if(QApplicationPrivate::app_style) {
+ QEvent ev(QEvent::Style);
+ QApplication::sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
+ }
+
+ if(widget && app_do_modal && !qt_try_modal(widget, event))
+ break;
+
+ if(widget && widget->window()->isVisible()) {
+ QWidget *tlw = widget->window();
+ if(tlw->isWindow() && !(tlw->windowType() == Qt::Popup)
+ && !qt_mac_is_macdrawer(tlw)
+ && (!tlw->parentWidget() || tlw->isModal()
+ || !(tlw->windowType() == Qt::Tool))) {
+ bool just_send_event = false;
+ {
+ WindowActivationScope scope;
+ if(GetWindowActivationScope((WindowRef)wid, &scope) == noErr &&
+ scope == kWindowActivationScopeIndependent) {
+ if(GetFrontWindowOfClass(kAllWindowClasses, true) != wid)
+ just_send_event = true;
+ }
+ }
+ if(just_send_event) {
+ QEvent e(QEvent::WindowActivate);
+ QApplication::sendSpontaneousEvent(widget, &e);
+ } else {
+ app->setActiveWindow(tlw);
+ }
+ }
+ QMenuBar::macUpdateMenuBar();
+ }
+ } else if(ekind == kEventWindowDeactivated) {
+ if(widget && QApplicationPrivate::active_window == widget)
+ app->setActiveWindow(0);
+ } else {
+ handled_event = false;
+ }
+ break; }
+ case kEventClassApplication:
+ if(ekind == kEventAppActivated) {
+ if(QApplication::desktopSettingsAware())
+ qt_mac_update_os_settings();
+ if(qt_clipboard) { //manufacture an event so the clipboard can see if it has changed
+ QEvent ev(QEvent::Clipboard);
+ QApplication::sendSpontaneousEvent(qt_clipboard, &ev);
+ }
+ if(app) {
+ QEvent ev(QEvent::ApplicationActivate);
+ QApplication::sendSpontaneousEvent(app, &ev);
+ }
+ if(!app->activeWindow()) {
+ WindowPtr wp = ActiveNonFloatingWindow();
+ if(QWidget *tmp_w = qt_mac_find_window(wp))
+ app->setActiveWindow(tmp_w);
+ }
+ QMenuBar::macUpdateMenuBar();
+ } else if(ekind == kEventAppDeactivated) {
+ //qt_mac_no_click_through_mode = false;
+ while(app->d_func()->inPopupMode())
+ app->activePopupWidget()->close();
+ if(app) {
+ QEvent ev(QEvent::ApplicationDeactivate);
+ QApplication::sendSpontaneousEvent(app, &ev);
+ }
+ app->setActiveWindow(0);
+ } else if(ekind == kEventAppAvailableWindowBoundsChanged) {
+ QDesktopWidgetImplementation::instance()->onResize();
+ } else {
+ handled_event = false;
+ }
+ break;
+ case kAppearanceEventClass:
+ if(ekind == kAEAppearanceChanged) {
+ if(QApplication::desktopSettingsAware())
+ qt_mac_update_os_settings();
+ if(QApplicationPrivate::app_style) {
+ QEvent ev(QEvent::Style);
+ QApplication::sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
+ }
+ } else {
+ handled_event = false;
+ }
+ break;
+ case kEventClassAppleEvent:
+ if(ekind == kEventAppleEvent) {
+ EventRecord erec;
+ if(!ConvertEventRefToEventRecord(event, &erec))
+ qDebug("Qt: internal: WH0A, unexpected condition reached. %s:%d", __FILE__, __LINE__);
+ else if(AEProcessAppleEvent(&erec) != noErr)
+ handled_event = false;
+ } else {
+ handled_event = false;
+ }
+ break;
+ case kEventClassCommand:
+ if(ekind == kEventCommandProcess) {
+ HICommand cmd;
+ GetEventParameter(event, kEventParamDirectObject, typeHICommand,
+ 0, sizeof(cmd), 0, &cmd);
+ handled_event = false;
+ if(!cmd.menu.menuRef && GetApplicationDockTileMenu()) {
+ EventRef copy = CopyEvent(event);
+ HICommand copy_cmd;
+ GetEventParameter(event, kEventParamDirectObject, typeHICommand,
+ 0, sizeof(copy_cmd), 0, &copy_cmd);
+ copy_cmd.menu.menuRef = GetApplicationDockTileMenu();
+ SetEventParameter(copy, kEventParamDirectObject, typeHICommand, sizeof(copy_cmd), &copy_cmd);
+ if(SendEventToMenu(copy, copy_cmd.menu.menuRef) == noErr)
+ handled_event = true;
+ }
+ if(!handled_event) {
+ if(cmd.commandID == kHICommandQuit) {
+ // Quitting the application is not Qt's responsibility if
+ // used in a plugin or just embedded into a native application.
+ // In that case, let the event pass down to the native apps event handler.
+ if (!QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
+ handled_event = true;
+ HiliteMenu(0);
+ bool handle_quit = true;
+ if(QApplicationPrivate::modalState()) {
+ int visible = 0;
+ const QWidgetList tlws = QApplication::topLevelWidgets();
+ for(int i = 0; i < tlws.size(); ++i) {
+ if(tlws.at(i)->isVisible())
+ ++visible;
+ }
+ handle_quit = (visible <= 1);
+ }
+ if(handle_quit) {
+ QCloseEvent ev;
+ QApplication::sendSpontaneousEvent(app, &ev);
+ if(ev.isAccepted())
+ app->quit();
+ } else {
+ QApplication::beep();
+ }
+ }
+ } else if(cmd.commandID == kHICommandSelectWindow) {
+ if((GetCurrentKeyModifiers() & cmdKey))
+ handled_event = true;
+ } else if(cmd.commandID == kHICommandAbout) {
+ QMessageBox::aboutQt(0);
+ HiliteMenu(0);
+ handled_event = true;
+ }
+ }
+ }
+ break;
+ }
+
+#ifdef DEBUG_EVENTS
+ qDebug("%shandled event %c%c%c%c %d", handled_event ? "(*) " : "",
+ char(eclass >> 24), char((eclass >> 16) & 255), char((eclass >> 8) & 255),
+ char(eclass & 255), (int)ekind);
+#endif
+ if(!handled_event) //let the event go through
+ return eventNotHandledErr;
+ return noErr; //we eat the event
+#else
+ Q_UNUSED(er);
+ Q_UNUSED(event);
+ Q_UNUSED(data);
+ return eventNotHandledErr;
+#endif
+}
+
+#ifdef QT_MAC_USE_COCOA
+void QApplicationPrivate::qt_initAfterNSAppStarted()
+{
+ setupAppleEvents();
+ qt_mac_update_cursor();
+}
+
+void QApplicationPrivate::setupAppleEvents()
+{
+ // This function is called from the event dispatcher when NSApplication has
+ // finished initialization, which appears to be just after [NSApplication run] has
+ // started to execute. By setting up our apple events handlers this late, we override
+ // the ones set up by NSApplication.
+
+ // If Qt is used as a plugin, we let the 3rd party application handle events
+ // like quit and open file events. Otherwise, if we install our own handlers, we
+ // easily end up breaking functionallity the 3rd party application depend on:
+ if (QApplication::testAttribute(Qt::AA_MacPluginApplication))
+ return;
+
+ QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *newDelegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
+ NSAppleEventManager *eventManager = [NSAppleEventManager sharedAppleEventManager];
+ [eventManager setEventHandler:newDelegate andSelector:@selector(appleEventQuit:withReplyEvent:)
+ forEventClass:kCoreEventClass andEventID:kAEQuitApplication];
+ [eventManager setEventHandler:newDelegate andSelector:@selector(getUrl:withReplyEvent:)
+ forEventClass:kInternetEventClass andEventID:kAEGetURL];
+}
+#endif
+
+// In Carbon this is your one stop for apple events.
+// In Cocoa, it ISN'T. This is the catch-all Apple Event handler that exists
+// for the time between instantiating the NSApplication, but before the
+// NSApplication has installed it's OWN Apple Event handler. When Cocoa has
+// that set up, we remove this. So, if you are debugging problems, you likely
+// want to check out QCocoaApplicationDelegate instead.
+OSStatus QApplicationPrivate::globalAppleEventProcessor(const AppleEvent *ae, AppleEvent *, long handlerRefcon)
+{
+ QApplication *app = (QApplication *)handlerRefcon;
+ bool handled_event=false;
+ OSType aeID=typeWildCard, aeClass=typeWildCard;
+ AEGetAttributePtr(ae, keyEventClassAttr, typeType, 0, &aeClass, sizeof(aeClass), 0);
+ AEGetAttributePtr(ae, keyEventIDAttr, typeType, 0, &aeID, sizeof(aeID), 0);
+ if(aeClass == kCoreEventClass) {
+ switch(aeID) {
+ case kAEQuitApplication: {
+ extern bool qt_mac_quit_menu_item_enabled; // qmenu_mac.cpp
+ if (qt_mac_quit_menu_item_enabled) {
+ QCloseEvent ev;
+ QApplication::sendSpontaneousEvent(app, &ev);
+ if(ev.isAccepted()) {
+ handled_event = true;
+ app->quit();
+ }
+ } else {
+ QApplication::beep(); // Sorry, you can't quit right now.
+ }
+ break; }
+ case kAEOpenDocuments: {
+ AEDescList docs;
+ if(AEGetParamDesc(ae, keyDirectObject, typeAEList, &docs) == noErr) {
+ long cnt = 0;
+ AECountItems(&docs, &cnt);
+ UInt8 *str_buffer = NULL;
+ for(int i = 0; i < cnt; i++) {
+ FSRef ref;
+ if(AEGetNthPtr(&docs, i+1, typeFSRef, 0, 0, &ref, sizeof(ref), 0) != noErr)
+ continue;
+ if(!str_buffer)
+ str_buffer = (UInt8 *)malloc(1024);
+ FSRefMakePath(&ref, str_buffer, 1024);
+ QFileOpenEvent ev(QString::fromUtf8((const char *)str_buffer));
+ QApplication::sendSpontaneousEvent(app, &ev);
+ }
+ if(str_buffer)
+ free(str_buffer);
+ }
+ break; }
+ default:
+ break;
+ }
+ } else if (aeClass == kInternetEventClass) {
+ switch (aeID) {
+ case kAEGetURL: {
+ char urlData[1024];
+ Size actualSize;
+ if (AEGetParamPtr(ae, keyDirectObject, typeChar, 0, urlData,
+ sizeof(urlData) - 1, &actualSize) == noErr) {
+ urlData[actualSize] = 0;
+ QFileOpenEvent ev(QUrl(QString::fromUtf8(urlData)));
+ QApplication::sendSpontaneousEvent(app, &ev);
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ }
+#ifdef DEBUG_EVENTS
+ qDebug("Qt: internal: %shandled Apple event! %c%c%c%c %c%c%c%c", handled_event ? "(*)" : "",
+ char(aeID >> 24), char((aeID >> 16) & 255), char((aeID >> 8) & 255),char(aeID & 255),
+ char(aeClass >> 24), char((aeClass >> 16) & 255), char((aeClass >> 8) & 255),char(aeClass & 255));
+#else
+ if(!handled_event) //let the event go through
+ return eventNotHandledErr;
+ return noErr; //we eat the event
+#endif
+}
+
+/*!
+ \fn bool QApplication::macEventFilter(EventHandlerCallRef caller, EventRef event)
+
+ \warning This virtual function is only used under Mac OS X, and behaves different
+ depending on if Qt is based on Carbon or Cocoa.
+
+ For the Carbon port, If you create an application that inherits QApplication and reimplement
+ this function, you get direct access to all Carbon Events that Qt registers
+ for from Mac OS X with this function being called with the \a caller and
+ the \a event.
+
+ For the Cocoa port, If you create an application that inherits QApplication and reimplement
+ this function, you get direct access to all Cocoa Events that Qt receives
+ from Mac OS X with this function being called with the \a caller being 0 and
+ the \a event being an NSEvent pointer:
+
+ NSEvent *e = reinterpret_cast<NSEvent *>(event);
+
+ Return true if you want to stop the event from being processed.
+ Return false for normal event dispatching. The default
+ implementation returns false.
+
+ \sa macEventFilter(void *nsevent)
+*/
+bool QApplication::macEventFilter(EventHandlerCallRef, EventRef)
+{
+ return false;
+}
+
+/*!
+ \internal
+*/
+void QApplicationPrivate::openPopup(QWidget *popup)
+{
+ if (!QApplicationPrivate::popupWidgets) // create list
+ QApplicationPrivate::popupWidgets = new QWidgetList;
+ QApplicationPrivate::popupWidgets->append(popup); // add to end of list
+
+ // popups are not focus-handled by the window system (the first
+ // popup grabbed the keyboard), so we have to do that manually: A
+ // new popup gets the focus
+ if (popup->focusWidget()) {
+ popup->focusWidget()->setFocus(Qt::PopupFocusReason);
+ } else if (QApplicationPrivate::popupWidgets->count() == 1) { // this was the first popup
+ popup->setFocus(Qt::PopupFocusReason);
+ }
+}
+
+/*!
+ \internal
+*/
+void QApplicationPrivate::closePopup(QWidget *popup)
+{
+ Q_Q(QApplication);
+ if (!QApplicationPrivate::popupWidgets)
+ return;
+
+ QApplicationPrivate::popupWidgets->removeAll(popup);
+ if (popup == qt_button_down)
+ qt_button_down = 0;
+ if (QApplicationPrivate::popupWidgets->isEmpty()) { // this was the last popup
+ delete QApplicationPrivate::popupWidgets;
+ QApplicationPrivate::popupWidgets = 0;
+
+ // Special case for Tool windows: since they are activated and deactived together
+ // with a normal window they never become the QApplicationPrivate::active_window.
+ QWidget *appFocusWidget = QApplication::focusWidget();
+ if (appFocusWidget && appFocusWidget->window()->windowType() == Qt::Tool) {
+ appFocusWidget->setFocus(Qt::PopupFocusReason);
+ } else if (QApplicationPrivate::active_window) {
+ if (QWidget *fw = QApplicationPrivate::active_window->focusWidget()) {
+ if (fw != QApplication::focusWidget()) {
+ fw->setFocus(Qt::PopupFocusReason);
+ } else {
+ QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
+ q->sendEvent(fw, &e);
+ }
+ }
+ }
+ } else {
+ // popups are not focus-handled by the window system (the
+ // first popup grabbed the keyboard), so we have to do that
+ // manually: A popup was closed, so the previous popup gets
+ // the focus.
+ QWidget* aw = QApplicationPrivate::popupWidgets->last();
+ if (QWidget *fw = aw->focusWidget())
+ fw->setFocus(Qt::PopupFocusReason);
+ }
+}
+
+void QApplication::beep()
+{
+ qt_mac_beep();
+}
+
+void QApplication::alert(QWidget *widget, int duration)
+{
+ if (!QApplicationPrivate::checkInstance("alert"))
+ return;
+
+ QWidgetList windowsToMark;
+ if (!widget)
+ windowsToMark += topLevelWidgets();
+ else
+ windowsToMark.append(widget->window());
+
+ bool needNotification = false;
+ for (int i = 0; i < windowsToMark.size(); ++i) {
+ QWidget *window = windowsToMark.at(i);
+ if (!window->isActiveWindow() && window->isVisible()) {
+ needNotification = true; // yeah, we may set it multiple times, but that's OK.
+ if (duration != 0) {
+ QTimer *timer = new QTimer(qApp);
+ timer->setSingleShot(true);
+ connect(timer, SIGNAL(timeout()), qApp, SLOT(_q_alertTimeOut()));
+ if (QTimer *oldTimer = qApp->d_func()->alertTimerHash.value(widget)) {
+ qApp->d_func()->alertTimerHash.remove(widget);
+ delete oldTimer;
+ }
+ qApp->d_func()->alertTimerHash.insert(widget, timer);
+ timer->start(duration);
+ }
+ }
+ }
+ if (needNotification)
+ qt_mac_send_notification();
+}
+
+void QApplicationPrivate::_q_alertTimeOut()
+{
+ if (QTimer *timer = qobject_cast<QTimer *>(q_func()->sender())) {
+ QHash<QWidget *, QTimer *>::iterator it = alertTimerHash.begin();
+ while (it != alertTimerHash.end()) {
+ if (it.value() == timer) {
+ alertTimerHash.erase(it);
+ timer->deleteLater();
+ break;
+ }
+ ++it;
+ }
+ if (alertTimerHash.isEmpty()) {
+ qt_mac_cancel_notification();
+ }
+ }
+}
+
+void QApplication::setCursorFlashTime(int msecs)
+{
+ QApplicationPrivate::cursor_flash_time = msecs;
+}
+
+int QApplication::cursorFlashTime()
+{
+ return QApplicationPrivate::cursor_flash_time;
+}
+
+void QApplication::setDoubleClickInterval(int ms)
+{
+ qt_mac_dblclick.use_qt_time_limit = true;
+ QApplicationPrivate::mouse_double_click_time = ms;
+}
+
+int QApplication::doubleClickInterval()
+{
+ if (!qt_mac_dblclick.use_qt_time_limit) { //get it from the system
+ QSettings appleSettings(QLatin1String("apple.com"));
+ /* First worked as of 10.3.3 */
+ double dci = appleSettings.value(QLatin1String("com/apple/mouse/doubleClickThreshold"), 0.5).toDouble();
+ return int(dci * 1000);
+ }
+ return QApplicationPrivate::mouse_double_click_time;
+}
+
+void QApplication::setKeyboardInputInterval(int ms)
+{
+ QApplicationPrivate::keyboard_input_time = ms;
+}
+
+int QApplication::keyboardInputInterval()
+{
+ // FIXME: get from the system
+ return QApplicationPrivate::keyboard_input_time;
+}
+
+#ifndef QT_NO_WHEELEVENT
+void QApplication::setWheelScrollLines(int n)
+{
+ QApplicationPrivate::wheel_scroll_lines = n;
+}
+
+int QApplication::wheelScrollLines()
+{
+ return QApplicationPrivate::wheel_scroll_lines;
+}
+#endif
+
+void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
+{
+ switch (effect) {
+ case Qt::UI_FadeMenu:
+ QApplicationPrivate::fade_menu = enable;
+ break;
+ case Qt::UI_AnimateMenu:
+ QApplicationPrivate::animate_menu = enable;
+ break;
+ case Qt::UI_FadeTooltip:
+ QApplicationPrivate::fade_tooltip = enable;
+ break;
+ case Qt::UI_AnimateTooltip:
+ QApplicationPrivate::animate_tooltip = enable;
+ break;
+ case Qt::UI_AnimateCombo:
+ QApplicationPrivate::animate_combo = enable;
+ break;
+ case Qt::UI_AnimateToolBox:
+ QApplicationPrivate::animate_toolbox = enable;
+ break;
+ case Qt::UI_General:
+ QApplicationPrivate::fade_tooltip = true;
+ break;
+ default:
+ QApplicationPrivate::animate_ui = enable;
+ break;
+ }
+
+ if (enable)
+ QApplicationPrivate::animate_ui = true;
+}
+
+bool QApplication::isEffectEnabled(Qt::UIEffect effect)
+{
+ if (QColormap::instance().depth() < 16 || !QApplicationPrivate::animate_ui)
+ return false;
+
+ switch(effect) {
+ case Qt::UI_AnimateMenu:
+ return QApplicationPrivate::animate_menu;
+ case Qt::UI_FadeMenu:
+ return QApplicationPrivate::fade_menu;
+ case Qt::UI_AnimateCombo:
+ return QApplicationPrivate::animate_combo;
+ case Qt::UI_AnimateTooltip:
+ return QApplicationPrivate::animate_tooltip;
+ case Qt::UI_FadeTooltip:
+ return QApplicationPrivate::fade_tooltip;
+ case Qt::UI_AnimateToolBox:
+ return QApplicationPrivate::animate_toolbox;
+ default:
+ break;
+ }
+ return QApplicationPrivate::animate_ui;
+}
+
+/*!
+ \internal
+*/
+bool QApplicationPrivate::qt_mac_apply_settings()
+{
+ QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
+ settings.beginGroup(QLatin1String("Qt"));
+
+ /*
+ Qt settings. This is how they are written into the datastream.
+ Palette/ * - QPalette
+ font - QFont
+ libraryPath - QStringList
+ style - QString
+ doubleClickInterval - int
+ cursorFlashTime - int
+ wheelScrollLines - int
+ colorSpec - QString
+ defaultCodec - QString
+ globalStrut/width - int
+ globalStrut/height - int
+ GUIEffects - QStringList
+ Font Substitutions/ * - QStringList
+ Font Substitutions/... - QStringList
+ */
+
+ // read library (ie. plugin) path list
+ QString libpathkey =
+ QString::fromLatin1("%1.%2/libraryPath")
+ .arg(QT_VERSION >> 16)
+ .arg((QT_VERSION & 0xff00) >> 8);
+ QStringList pathlist = settings.value(libpathkey).toString().split(QLatin1Char(':'));
+ if (!pathlist.isEmpty()) {
+ QStringList::ConstIterator it = pathlist.begin();
+ while(it != pathlist.end())
+ QApplication::addLibraryPath(*it++);
+ }
+
+ QString defaultcodec = settings.value(QLatin1String("defaultCodec"), QVariant(QLatin1String("none"))).toString();
+ if (defaultcodec != QLatin1String("none")) {
+ QTextCodec *codec = QTextCodec::codecForName(defaultcodec.toLatin1().constData());
+ if (codec)
+ QTextCodec::setCodecForTr(codec);
+ }
+
+ if (qt_is_gui_used) {
+ QString str;
+ QStringList strlist;
+ int num;
+
+ // read new palette
+ int i;
+ QPalette pal(QApplication::palette());
+ strlist = settings.value(QLatin1String("Palette/active")).toStringList();
+ if (strlist.count() == QPalette::NColorRoles) {
+ for (i = 0; i < QPalette::NColorRoles; i++)
+ pal.setColor(QPalette::Active, (QPalette::ColorRole) i,
+ QColor(strlist[i]));
+ }
+ strlist = settings.value(QLatin1String("Palette/inactive")).toStringList();
+ if (strlist.count() == QPalette::NColorRoles) {
+ for (i = 0; i < QPalette::NColorRoles; i++)
+ pal.setColor(QPalette::Inactive, (QPalette::ColorRole) i,
+ QColor(strlist[i]));
+ }
+ strlist = settings.value(QLatin1String("Palette/disabled")).toStringList();
+ if (strlist.count() == QPalette::NColorRoles) {
+ for (i = 0; i < QPalette::NColorRoles; i++)
+ pal.setColor(QPalette::Disabled, (QPalette::ColorRole) i,
+ QColor(strlist[i]));
+ }
+
+ if (pal != QApplication::palette())
+ QApplication::setPalette(pal);
+
+ // read new font
+ QFont font(QApplication::font());
+ str = settings.value(QLatin1String("font")).toString();
+ if (!str.isEmpty()) {
+ font.fromString(str);
+ if (font != QApplication::font())
+ QApplication::setFont(font);
+ }
+
+ // read new QStyle
+ QString stylename = settings.value(QLatin1String("style")).toString();
+ if (! stylename.isNull() && ! stylename.isEmpty()) {
+ QStyle *style = QStyleFactory::create(stylename);
+ if (style)
+ QApplication::setStyle(style);
+ else
+ stylename = QLatin1String("default");
+ } else {
+ stylename = QLatin1String("default");
+ }
+
+ num = settings.value(QLatin1String("doubleClickInterval"),
+ QApplication::doubleClickInterval()).toInt();
+ QApplication::setDoubleClickInterval(num);
+
+ num = settings.value(QLatin1String("cursorFlashTime"),
+ QApplication::cursorFlashTime()).toInt();
+ QApplication::setCursorFlashTime(num);
+
+#ifndef QT_NO_WHEELEVENT
+ num = settings.value(QLatin1String("wheelScrollLines"),
+ QApplication::wheelScrollLines()).toInt();
+ QApplication::setWheelScrollLines(num);
+#endif
+
+ QString colorspec = settings.value(QLatin1String("colorSpec"),
+ QVariant(QLatin1String("default"))).toString();
+ if (colorspec == QLatin1String("normal"))
+ QApplication::setColorSpec(QApplication::NormalColor);
+ else if (colorspec == QLatin1String("custom"))
+ QApplication::setColorSpec(QApplication::CustomColor);
+ else if (colorspec == QLatin1String("many"))
+ QApplication::setColorSpec(QApplication::ManyColor);
+ else if (colorspec != QLatin1String("default"))
+ colorspec = QLatin1String("default");
+
+ int w = settings.value(QLatin1String("globalStrut/width")).toInt();
+ int h = settings.value(QLatin1String("globalStrut/height")).toInt();
+ QSize strut(w, h);
+ if (strut.isValid())
+ QApplication::setGlobalStrut(strut);
+
+ QStringList effects = settings.value(QLatin1String("GUIEffects")).toStringList();
+ if (!effects.isEmpty()) {
+ if (effects.contains(QLatin1String("none")))
+ QApplication::setEffectEnabled(Qt::UI_General, false);
+ if (effects.contains(QLatin1String("general")))
+ QApplication::setEffectEnabled(Qt::UI_General, true);
+ if (effects.contains(QLatin1String("animatemenu")))
+ QApplication::setEffectEnabled(Qt::UI_AnimateMenu, true);
+ if (effects.contains(QLatin1String("fademenu")))
+ QApplication::setEffectEnabled(Qt::UI_FadeMenu, true);
+ if (effects.contains(QLatin1String("animatecombo")))
+ QApplication::setEffectEnabled(Qt::UI_AnimateCombo, true);
+ if (effects.contains(QLatin1String("animatetooltip")))
+ QApplication::setEffectEnabled(Qt::UI_AnimateTooltip, true);
+ if (effects.contains(QLatin1String("fadetooltip")))
+ QApplication::setEffectEnabled(Qt::UI_FadeTooltip, true);
+ if (effects.contains(QLatin1String("animatetoolbox")))
+ QApplication::setEffectEnabled(Qt::UI_AnimateToolBox, true);
+ } else {
+ QApplication::setEffectEnabled(Qt::UI_General, true);
+ }
+
+ settings.beginGroup(QLatin1String("Font Substitutions"));
+ QStringList fontsubs = settings.childKeys();
+ if (!fontsubs.isEmpty()) {
+ QStringList::Iterator it = fontsubs.begin();
+ for (; it != fontsubs.end(); ++it) {
+ QString fam = QString::fromLatin1((*it).toLatin1().constData());
+ QStringList subs = settings.value(fam).toStringList();
+ QFont::insertSubstitutions(fam, subs);
+ }
+ }
+ settings.endGroup();
+ }
+
+ settings.endGroup();
+ return true;
+}
+
+// DRSWAT
+
+bool QApplicationPrivate::canQuit()
+{
+#ifndef QT_MAC_USE_COCOA
+ return true;
+#else
+ Q_Q(QApplication);
+#ifdef QT_MAC_USE_COCOA
+ [[NSApp mainMenu] cancelTracking];
+#else
+ HiliteMenu(0);
+#endif
+
+ bool handle_quit = true;
+ if (QApplicationPrivate::modalState() && [[[[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate]
+ menuLoader] quitMenuItem] isEnabled]) {
+ int visible = 0;
+ const QWidgetList tlws = QApplication::topLevelWidgets();
+ for(int i = 0; i < tlws.size(); ++i) {
+ if (tlws.at(i)->isVisible())
+ ++visible;
+ }
+ handle_quit = (visible <= 1);
+ }
+ if (handle_quit) {
+ QCloseEvent ev;
+ QApplication::sendSpontaneousEvent(q, &ev);
+ if (ev.isAccepted()) {
+ return true;
+ }
+ }
+ return false;
+#endif
+}
+
+void onApplicationWindowChangedActivation(QWidget *widget, bool activated)
+{
+#if QT_MAC_USE_COCOA
+ if (!widget)
+ return;
+
+ if (activated) {
+ if (QApplicationPrivate::app_style) {
+ QEvent ev(QEvent::Style);
+ qt_sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
+ }
+ qApp->setActiveWindow(widget);
+ } else { // deactivated
+ if (QApplicationPrivate::active_window == widget)
+ qApp->setActiveWindow(0);
+ }
+
+ QMenuBar::macUpdateMenuBar();
+ qt_mac_update_cursor();
+#else
+ Q_UNUSED(widget);
+ Q_UNUSED(activated);
+#endif
+}
+
+
+void onApplicationChangedActivation( bool activated )
+{
+#if QT_MAC_USE_COCOA
+ QApplication *app = qApp;
+
+//NSLog(@"App Changed Activation\n");
+
+ if ( activated ) {
+ if (QApplication::desktopSettingsAware())
+ qt_mac_update_os_settings();
+
+ if (qt_clipboard) { //manufacture an event so the clipboard can see if it has changed
+ QEvent ev(QEvent::Clipboard);
+ qt_sendSpontaneousEvent(qt_clipboard, &ev);
+ }
+
+ if (app) {
+ QEvent ev(QEvent::ApplicationActivate);
+ qt_sendSpontaneousEvent(app, &ev);
+ }
+
+ if (!app->activeWindow()) {
+ OSWindowRef wp = [NSApp keyWindow];
+ if (QWidget *tmp_w = qt_mac_find_window(wp))
+ app->setActiveWindow(tmp_w);
+ }
+ QMenuBar::macUpdateMenuBar();
+ qt_mac_update_cursor();
+ } else { // de-activated
+ QApplicationPrivate *priv = [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] qAppPrivate];
+ while (priv->inPopupMode())
+ app->activePopupWidget()->close();
+ if (app) {
+ QEvent ev(QEvent::ApplicationDeactivate);
+ qt_sendSpontaneousEvent(app, &ev);
+ }
+ app->setActiveWindow(0);
+ }
+#else
+ Q_UNUSED(activated);
+#endif
+}
+
+void QApplicationPrivate::initializeMultitouch_sys()
+{ }
+void QApplicationPrivate::cleanupMultitouch_sys()
+{ }
+
+QT_END_NAMESPACE
diff --git a/src/gui/kernel/qapplication_p.h b/src/gui/kernel/qapplication_p.h
new file mode 100644
index 0000000000..954c6deb90
--- /dev/null
+++ b/src/gui/kernel/qapplication_p.h
@@ -0,0 +1,683 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QAPPLICATION_P_H
+#define QAPPLICATION_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
+// and many other. This header file may change from version to version
+// without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include "QtGui/qapplication.h"
+#include "QtGui/qevent.h"
+#include "QtGui/qfont.h"
+#include "QtGui/qcursor.h"
+#include "QtGui/qregion.h"
+#include "QtCore/qmutex.h"
+#include "QtCore/qtranslator.h"
+#include "QtCore/qbasictimer.h"
+#include "QtCore/qhash.h"
+#include "QtCore/qpointer.h"
+#include "private/qcoreapplication_p.h"
+#include "QtGui/private/qshortcutmap_p.h"
+#include <private/qthread_p.h>
+#include "QtCore/qpoint.h"
+#include <QTime>
+#ifdef Q_WS_QWS
+#include "QtGui/qscreen_qws.h"
+#include <private/qgraphicssystem_qws_p.h>
+#endif
+#ifdef Q_OS_SYMBIAN
+#include <w32std.h>
+#endif
+#ifdef Q_WS_QPA
+#include <QWindowSystemInterface>
+#include "qwindowsysteminterface_qpa_p.h"
+#include "QtGui/qplatformintegration_qpa.h"
+#endif
+
+QT_BEGIN_NAMESPACE
+
+class QClipboard;
+class QGraphicsScene;
+class QGraphicsSystem;
+class QInputContext;
+class QObject;
+class QWidget;
+class QSocketNotifier;
+#ifndef QT_NO_GESTURES
+class QGestureManager;
+#endif
+
+extern bool qt_is_gui_used;
+#ifndef QT_NO_CLIPBOARD
+extern QClipboard *qt_clipboard;
+#endif
+
+#if defined (Q_OS_WIN32) || defined (Q_OS_CYGWIN) || defined(Q_OS_WINCE)
+extern QSysInfo::WinVersion qt_winver;
+enum { QT_TABLET_NPACKETQSIZE = 128 };
+# ifdef Q_OS_WINCE
+ extern DWORD qt_cever;
+# endif
+#elif defined (Q_OS_MAC)
+extern QSysInfo::MacVersion qt_macver;
+#endif
+#if defined(Q_WS_QWS)
+class QWSManager;
+class QDirectPainter;
+struct QWSServerCleaner { ~QWSServerCleaner(); };
+#endif
+
+#ifndef QT_NO_TABLET
+struct QTabletDeviceData
+{
+#ifndef Q_WS_MAC
+ int minPressure;
+ int maxPressure;
+ int minTanPressure;
+ int maxTanPressure;
+ int minX, maxX, minY, maxY, minZ, maxZ;
+ inline QPointF scaleCoord(int coordX, int coordY, int outOriginX, int outExtentX,
+ int outOriginY, int outExtentY) const;
+#endif
+
+#if defined(Q_WS_X11) || (defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA))
+ QPointer<QWidget> widgetToGetPress;
+#endif
+
+#ifdef Q_WS_X11
+ int deviceType;
+ enum {
+ TOTAL_XINPUT_EVENTS = 64
+ };
+ void *device;
+ int eventCount;
+ long unsigned int eventList[TOTAL_XINPUT_EVENTS]; // XEventClass is in fact a long unsigned int
+
+ int xinput_motion;
+ int xinput_key_press;
+ int xinput_key_release;
+ int xinput_button_press;
+ int xinput_button_release;
+ int xinput_proximity_in;
+ int xinput_proximity_out;
+#elif defined(Q_WS_WIN)
+ qint64 llId;
+ int currentDevice;
+ int currentPointerType;
+#elif defined(Q_WS_MAC)
+ quint64 tabletUniqueID;
+ int tabletDeviceType;
+ int tabletPointerType;
+ int capabilityMask;
+#endif
+};
+
+static inline int sign(int x)
+{
+ return x >= 0 ? 1 : -1;
+}
+
+#ifndef Q_WS_MAC
+inline QPointF QTabletDeviceData::scaleCoord(int coordX, int coordY,
+ int outOriginX, int outExtentX,
+ int outOriginY, int outExtentY) const
+{
+ QPointF ret;
+
+ if (sign(outExtentX) == sign(maxX))
+ ret.setX(((coordX - minX) * qAbs(outExtentX) / qAbs(qreal(maxX - minX))) + outOriginX);
+ else
+ ret.setX(((qAbs(maxX) - (coordX - minX)) * qAbs(outExtentX) / qAbs(qreal(maxX - minX)))
+ + outOriginX);
+
+ if (sign(outExtentY) == sign(maxY))
+ ret.setY(((coordY - minY) * qAbs(outExtentY) / qAbs(qreal(maxY - minY))) + outOriginY);
+ else
+ ret.setY(((qAbs(maxY) - (coordY - minY)) * qAbs(outExtentY) / qAbs(qreal(maxY - minY)))
+ + outOriginY);
+
+ return ret;
+}
+#endif
+
+typedef QList<QTabletDeviceData> QTabletDeviceDataList;
+QTabletDeviceDataList *qt_tablet_devices();
+# if defined(Q_WS_MAC)
+typedef QHash<int, QTabletDeviceData> QMacTabletHash;
+QMacTabletHash *qt_mac_tablet_hash();
+# endif
+#endif
+
+#ifdef QT3_SUPPORT
+extern "C" {
+ typedef bool (*Ptrqt_tryAccelEvent)(QWidget *w, QKeyEvent *e);
+ typedef bool (*Ptrqt_tryComposeUnicode)(QWidget *w, QKeyEvent *e);
+ typedef bool (*Ptrqt_dispatchAccelEvent)(QWidget *w, QKeyEvent *e);
+}
+#endif
+
+#if defined(Q_WS_WIN)
+typedef BOOL (WINAPI *PtrRegisterTouchWindow)(HWND, ULONG);
+typedef BOOL (WINAPI *PtrGetTouchInputInfo)(HANDLE, UINT, PVOID, int);
+typedef BOOL (WINAPI *PtrCloseTouchInputHandle)(HANDLE);
+
+#ifndef QT_NO_GESTURES
+typedef BOOL (WINAPI *PtrGetGestureInfo)(HANDLE, PVOID);
+typedef BOOL (WINAPI *PtrGetGestureExtraArgs)(HANDLE, UINT, PBYTE);
+typedef BOOL (WINAPI *PtrCloseGestureInfoHandle)(HANDLE);
+typedef BOOL (WINAPI *PtrSetGestureConfig)(HWND, DWORD, UINT, PVOID, UINT);
+typedef BOOL (WINAPI *PtrGetGestureConfig)(HWND, DWORD, DWORD, PUINT, PVOID, UINT);
+
+typedef BOOL (WINAPI *PtrBeginPanningFeedback)(HWND);
+typedef BOOL (WINAPI *PtrUpdatePanningFeedback)(HWND, LONG, LONG, BOOL);
+typedef BOOL (WINAPI *PtrEndPanningFeedback)(HWND, BOOL);
+
+#ifndef WM_GESTURE
+# define WM_GESTURE 0x0119
+
+# define GID_BEGIN 1
+# define GID_END 2
+# define GID_ZOOM 3
+# define GID_PAN 4
+# define GID_ROTATE 5
+# define GID_TWOFINGERTAP 6
+# define GID_ROLLOVER 7
+
+typedef struct tagGESTUREINFO
+{
+ UINT cbSize;
+ DWORD dwFlags;
+ DWORD dwID;
+ HWND hwndTarget;
+ POINTS ptsLocation;
+ DWORD dwInstanceID;
+ DWORD dwSequenceID;
+ ULONGLONG ullArguments;
+ UINT cbExtraArgs;
+} GESTUREINFO;
+
+# define GC_PAN 0x00000001
+# define GC_PAN_WITH_SINGLE_FINGER_VERTICALLY 0x00000002
+# define GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY 0x00000004
+
+# define GC_ZOOM 0x00000001
+# define GC_ROTATE 0x00000001
+
+typedef struct tagGESTURECONFIG
+{
+ DWORD dwID;
+ DWORD dwWant;
+ DWORD dwBlock;
+} GESTURECONFIG;
+
+# define GID_ROTATE_ANGLE_FROM_ARGUMENT(arg) ((((double)(arg) / 65535.0) * 4.0 * 3.14159265) - 2.0*3.14159265)
+
+#endif // WM_GESTURE
+
+#if defined(Q_WS_WINCE_WM) && defined(QT_WINCE_GESTURES)
+#undef GID_ZOOM
+#define GID_ZOOM 0xf000
+#undef GID_ROTATE
+#define GID_ROTATE 0xf001
+#undef GID_TWOFINGERTAP
+#define GID_TWOFINGERTAP 0xf002
+#undef GID_ROLLOVER
+#define GID_ROLLOVER 0xf003
+#endif
+
+#endif // QT_NO_GESTURES
+
+#endif // Q_WS_WIN
+
+class QScopedLoopLevelCounter
+{
+ QThreadData *threadData;
+public:
+ QScopedLoopLevelCounter(QThreadData *threadData)
+ : threadData(threadData)
+ { ++threadData->loopLevel; }
+ ~QScopedLoopLevelCounter()
+ { --threadData->loopLevel; }
+};
+
+typedef QHash<QByteArray, QFont> FontHash;
+FontHash *qt_app_fonts_hash();
+
+typedef QHash<QByteArray, QPalette> PaletteHash;
+PaletteHash *qt_app_palettes_hash();
+
+class Q_GUI_EXPORT QApplicationPrivate : public QCoreApplicationPrivate
+{
+ Q_DECLARE_PUBLIC(QApplication)
+public:
+ QApplicationPrivate(int &argc, char **argv, QApplication::Type type, int flags);
+ ~QApplicationPrivate();
+
+#if defined(Q_WS_X11)
+#ifndef QT_NO_SETTINGS
+ static bool x11_apply_settings();
+#endif
+ static void reset_instance_pointer();
+#elif defined(Q_WS_QWS)
+ static bool qws_apply_settings();
+ static QWidget *findWidget(const QObjectList&, const QPoint &, bool rec);
+#endif
+ static bool quitOnLastWindowClosed;
+ static void emitLastWindowClosed();
+#ifdef Q_WS_WINCE
+ static int autoMaximizeThreshold;
+#endif
+ static bool autoSipEnabled;
+ static QString desktopStyleKey();
+
+ static QGraphicsSystem *graphicsSystem()
+#if defined(Q_WS_QWS)
+ { return QScreen::instance()->graphicsSystem(); }
+#else
+ { return graphics_system; }
+#endif
+
+#if defined(Q_WS_QPA)
+ static QPlatformIntegration *platformIntegration()
+ { return platform_integration; }
+
+ static QAbstractEventDispatcher *qt_qpa_core_dispatcher()
+ { return QCoreApplication::instance()->d_func()->threadData->eventDispatcher; }
+#endif
+
+ void createEventDispatcher();
+ QString appName() const;
+ static void dispatchEnterLeave(QWidget *enter, QWidget *leave);
+
+ //modality
+ static void enterModal(QWidget*);
+ static void leaveModal(QWidget*);
+ static void enterModal_sys(QWidget*);
+ static void leaveModal_sys(QWidget*);
+ static bool isBlockedByModal(QWidget *widget);
+ static bool modalState();
+ static bool tryModalHelper(QWidget *widget, QWidget **rettop = 0);
+#ifdef Q_WS_MAC
+ static QWidget *tryModalHelper_sys(QWidget *top);
+ bool canQuit();
+#endif
+
+ bool notify_helper(QObject *receiver, QEvent * e);
+
+ void construct(
+#ifdef Q_WS_X11
+ Display *dpy = 0, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0
+#endif
+ );
+ void initialize();
+ void process_cmdline();
+
+#if defined(Q_WS_X11)
+ static void x11_initialize_style();
+#endif
+
+ enum KeyPlatform {
+ KB_Win = 1,
+ KB_Mac = 2,
+ KB_X11 = 4,
+ KB_KDE = 8,
+ KB_Gnome = 16,
+ KB_CDE = 32,
+ KB_S60 = 64,
+ KB_All = 0xffff
+ };
+
+ static uint currentPlatform();
+ bool inPopupMode() const;
+ void closePopup(QWidget *popup);
+ void openPopup(QWidget *popup);
+ static void setFocusWidget(QWidget *focus, Qt::FocusReason reason);
+ static QWidget *focusNextPrevChild_helper(QWidget *toplevel, bool next);
+
+#ifndef QT_NO_SESSIONMANAGER
+ QSessionManager *session_manager;
+ QString session_id;
+ QString session_key;
+ bool is_session_restored;
+#endif
+
+#ifndef QT_NO_CURSOR
+ QList<QCursor> cursor_list;
+#endif
+#ifndef QT_NO_GRAPHICSVIEW
+ // Maintain a list of all scenes to ensure font and palette propagation to
+ // all scenes.
+ QList<QGraphicsScene *> scene_list;
+#endif
+
+ QBasicTimer toolTipWakeUp, toolTipFallAsleep;
+ QPoint toolTipPos, toolTipGlobalPos, hoverGlobalPos;
+ QPointer<QWidget> toolTipWidget;
+#ifndef QT_NO_SHORTCUT
+ QShortcutMap shortcutMap;
+#endif
+
+#ifdef QT3_SUPPORT
+ bool qt_compat_used;
+ bool qt_compat_resolved;
+ Ptrqt_tryAccelEvent qt_tryAccelEvent;
+ Ptrqt_tryComposeUnicode qt_tryComposeUnicode;
+ Ptrqt_dispatchAccelEvent qt_dispatchAccelEvent;
+
+ bool use_compat() {
+ return qt_tryAccelEvent
+ && qt_tryComposeUnicode
+ && qt_dispatchAccelEvent;
+ }
+#endif
+ static QInputContext *inputContext;
+
+ static Qt::MouseButtons mouse_buttons;
+ static Qt::KeyboardModifiers modifier_buttons;
+
+ static QSize app_strut;
+ static QWidgetList *popupWidgets;
+ static QStyle *app_style;
+ static int app_cspec;
+ static QPalette *app_pal;
+ static QPalette *sys_pal;
+ static QPalette *set_pal;
+ static QGraphicsSystem *graphics_system;
+ static QString graphics_system_name;
+ static bool runtime_graphics_system;
+#ifdef Q_WS_QPA
+ static QPlatformIntegration *platform_integration;
+#endif
+
+private:
+ static QFont *app_font; // private for a reason! Always use QApplication::font() instead!
+public:
+ static QFont *sys_font;
+ static QFont *set_font;
+ static QWidget *main_widget;
+ static QWidget *focus_widget;
+ static QWidget *hidden_focus_widget;
+ static QWidget *active_window;
+ static QIcon *app_icon;
+ static bool obey_desktop_settings;
+ static int cursor_flash_time;
+ static int mouse_double_click_time;
+ static int keyboard_input_time;
+#ifndef QT_NO_WHEELEVENT
+ static int wheel_scroll_lines;
+#endif
+
+ static bool animate_ui;
+ static bool animate_menu;
+ static bool animate_tooltip;
+ static bool animate_combo;
+ static bool fade_menu;
+ static bool fade_tooltip;
+ static bool animate_toolbox;
+ static bool widgetCount; // Coupled with -widgetcount switch
+ static bool load_testability; // Coupled with -testability switch
+ static QString qmljs_debug_arguments; // a string containing arguments for js/qml debugging.
+ static QString qmljsDebugArgumentsString(); // access string from other libraries
+
+#ifdef Q_WS_MAC
+ static bool native_modal_dialog_active;
+#endif
+
+ static void setSystemPalette(const QPalette &pal);
+ static void setPalette_helper(const QPalette &palette, const char* className, bool clearWidgetPaletteHash);
+ static void initializeWidgetPaletteHash();
+ static void setSystemFont(const QFont &font);
+
+#if defined(Q_WS_X11)
+ static void applyX11SpecificCommandLineArguments(QWidget *main_widget);
+#elif defined(Q_WS_QWS)
+ static void applyQWSSpecificCommandLineArguments(QWidget *main_widget);
+#endif
+
+#ifdef Q_WS_MAC
+ static OSStatus globalEventProcessor(EventHandlerCallRef, EventRef, void *);
+ static OSStatus globalAppleEventProcessor(const AppleEvent *, AppleEvent *, long);
+ static OSStatus tabletProximityCallback(EventHandlerCallRef, EventRef, void *);
+#ifdef QT_MAC_USE_COCOA
+ static void qt_initAfterNSAppStarted();
+ static void setupAppleEvents();
+#endif
+ static bool qt_mac_apply_settings();
+#endif
+
+#ifdef Q_WS_QPA
+ static void processMouseEvent(QWindowSystemInterfacePrivate::MouseEvent *e);
+ static void processKeyEvent(QWindowSystemInterfacePrivate::KeyEvent *e);
+ static void processWheelEvent(QWindowSystemInterfacePrivate::WheelEvent *e);
+ static void processTouchEvent(QWindowSystemInterfacePrivate::TouchEvent *e);
+
+ static void processCloseEvent(QWindowSystemInterfacePrivate::CloseEvent *e);
+
+ static void processGeometryChangeEvent(QWindowSystemInterfacePrivate::GeometryChangeEvent *e);
+
+ static void processEnterEvent(QWindowSystemInterfacePrivate::EnterEvent *e);
+ static void processLeaveEvent(QWindowSystemInterfacePrivate::LeaveEvent *e);
+
+ static void processActivatedEvent(QWindowSystemInterfacePrivate::ActivatedWindowEvent *e);
+
+ static void processWindowSystemEvent(QWindowSystemInterfacePrivate::WindowSystemEvent *e);
+
+// static void reportScreenCount(int count);
+ static void reportScreenCount(QWindowSystemInterfacePrivate::ScreenCountEvent *e);
+// static void reportGeometryChange(int screenIndex);
+ static void reportGeometryChange(QWindowSystemInterfacePrivate::ScreenGeometryEvent *e);
+// static void reportAvailableGeometryChange(int screenIndex);
+ static void reportAvailableGeometryChange(QWindowSystemInterfacePrivate::ScreenAvailableGeometryEvent *e);
+
+#endif
+
+#ifdef Q_WS_QWS
+ QPointer<QWSManager> last_manager;
+ QWSServerCleaner qwsServerCleaner;
+# ifndef QT_NO_DIRECTPAINTER
+ QMap<WId, QDirectPainter *> *directPainters;
+# endif
+ QRect maxWindowRect(const QScreen *screen) const { return maxWindowRects[screen]; }
+ void setMaxWindowRect(const QScreen *screen, int screenNo, const QRect &rect);
+ void setScreenTransformation(QScreen *screen, int screenNo, int transformation);
+#endif
+
+ static QApplicationPrivate *instance() { return self; }
+
+ static QString styleOverride;
+
+#ifdef QT_KEYPAD_NAVIGATION
+ static QWidget *oldEditFocus;
+ static Qt::NavigationMode navigationMode;
+#endif
+
+#if defined(Q_WS_MAC) || defined(Q_WS_X11)
+ void _q_alertTimeOut();
+ QHash<QWidget *, QTimer *> alertTimerHash;
+#endif
+#ifndef QT_NO_STYLE_STYLESHEET
+ static QString styleSheet;
+#endif
+ static QPointer<QWidget> leaveAfterRelease;
+ static QWidget *pickMouseReceiver(QWidget *candidate, const QPoint &globalPos, QPoint &pos,
+ QEvent::Type type, Qt::MouseButtons buttons,
+ QWidget *buttonDown, QWidget *alienWidget);
+ static bool sendMouseEvent(QWidget *receiver, QMouseEvent *event, QWidget *alienWidget,
+ QWidget *native, QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
+ bool spontaneous = true);
+#ifdef Q_OS_SYMBIAN
+ static void setNavigationMode(Qt::NavigationMode mode);
+ static TUint resolveS60ScanCode(TInt scanCode, TUint keysym);
+ QSet<WId> nativeWindows;
+
+ int symbianProcessWsEvent(const QSymbianEvent *symbianEvent);
+ int symbianHandleCommand(const QSymbianEvent *symbianEvent);
+ int symbianResourceChange(const QSymbianEvent *symbianEvent);
+
+ void _q_aboutToQuit();
+#endif
+#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined (Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
+ void sendSyntheticEnterLeave(QWidget *widget);
+#endif
+
+#ifndef QT_NO_GESTURES
+ QGestureManager *gestureManager;
+ QWidget *gestureWidget;
+#endif
+#if defined(Q_WS_X11) || defined(Q_WS_WIN)
+ QPixmap *move_cursor;
+ QPixmap *copy_cursor;
+ QPixmap *link_cursor;
+#endif
+#if defined(Q_WS_WIN)
+ QPixmap *ignore_cursor;
+#endif
+ QPixmap getPixmapCursor(Qt::CursorShape cshape);
+
+ QMap<int, QWeakPointer<QWidget> > widgetForTouchPointId;
+ QMap<int, QTouchEvent::TouchPoint> appCurrentTouchPoints;
+ static void updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent);
+ void initializeMultitouch();
+ void initializeMultitouch_sys();
+ void cleanupMultitouch();
+ void cleanupMultitouch_sys();
+ int findClosestTouchPointId(const QPointF &screenPos);
+ void appendTouchPoint(const QTouchEvent::TouchPoint &touchPoint);
+ void removeTouchPoint(int touchPointId);
+ static void translateRawTouchEvent(QWidget *widget,
+ QTouchEvent::DeviceType deviceType,
+ const QList<QTouchEvent::TouchPoint> &touchPoints);
+
+#if defined(Q_WS_WIN)
+ static bool HasTouchSupport;
+ static PtrRegisterTouchWindow RegisterTouchWindow;
+ static PtrGetTouchInputInfo GetTouchInputInfo;
+ static PtrCloseTouchInputHandle CloseTouchInputHandle;
+
+ QHash<DWORD, int> touchInputIDToTouchPointID;
+ bool translateTouchEvent(const MSG &msg);
+
+#ifndef QT_NO_GESTURES
+ PtrGetGestureInfo GetGestureInfo;
+ PtrGetGestureExtraArgs GetGestureExtraArgs;
+ PtrCloseGestureInfoHandle CloseGestureInfoHandle;
+ PtrSetGestureConfig SetGestureConfig;
+ PtrGetGestureConfig GetGestureConfig;
+ PtrBeginPanningFeedback BeginPanningFeedback;
+ PtrUpdatePanningFeedback UpdatePanningFeedback;
+ PtrEndPanningFeedback EndPanningFeedback;
+#endif // QT_NO_GESTURES
+#endif
+
+#ifdef QT_RX71_MULTITOUCH
+ bool hasRX71MultiTouch;
+
+ struct RX71TouchPointState {
+ QSocketNotifier *socketNotifier;
+ QTouchEvent::TouchPoint touchPoint;
+
+ int minX, maxX, scaleX;
+ int minY, maxY, scaleY;
+ int minZ, maxZ;
+ };
+ QList<RX71TouchPointState> allRX71TouchPoints;
+
+ bool readRX71MultiTouchEvents(int deviceNumber);
+ void fakeMouseEventFromRX71TouchEvent();
+ void _q_readRX71MultiTouchEvents();
+#endif
+
+#if defined(Q_OS_SYMBIAN)
+ int pressureSupported;
+ int maxTouchPressure;
+ QList<QTouchEvent::TouchPoint> appAllTouchPoints;
+
+ bool useTranslucentEGLSurfaces;
+#endif
+
+private:
+#ifdef Q_WS_QWS
+ QMap<const QScreen*, QRect> maxWindowRects;
+#endif
+
+#ifdef Q_OS_SYMBIAN
+ QHash<TInt, TUint> scanCodeCache;
+#endif
+
+ static QApplicationPrivate *self;
+
+ static void giveFocusAccordingToFocusPolicy(QWidget *w,
+ Qt::FocusPolicy focusPolicy,
+ Qt::FocusReason focusReason);
+ static bool shouldSetFocus(QWidget *w, Qt::FocusPolicy policy);
+
+
+ static bool isAlien(QWidget *);
+};
+
+Q_GUI_EXPORT void qt_translateRawTouchEvent(QWidget *window,
+ QTouchEvent::DeviceType deviceType,
+ const QList<QTouchEvent::TouchPoint> &touchPoints);
+
+#if defined(Q_WS_WIN)
+ extern void qt_win_set_cursor(QWidget *, bool);
+#elif defined(Q_WS_X11)
+ extern void qt_x11_enforce_cursor(QWidget *, bool);
+ extern void qt_x11_enforce_cursor(QWidget *);
+#elif defined(Q_OS_SYMBIAN)
+ extern void qt_symbian_set_cursor(QWidget *, bool);
+#elif defined (Q_WS_QPA)
+ extern void qt_qpa_set_cursor(QWidget *, bool);
+#endif
+
+QT_END_NAMESPACE
+
+#endif // QAPPLICATION_P_H
diff --git a/src/gui/kernel/qapplication_qpa.cpp b/src/gui/kernel/qapplication_qpa.cpp
new file mode 100644
index 0000000000..b754cf7de8
--- /dev/null
+++ b/src/gui/kernel/qapplication_qpa.cpp
@@ -0,0 +1,965 @@
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qapplication_p.h"
+#include "qcolormap.h"
+#include "qpixmapcache.h"
+#if !defined(QT_NO_GLIB)
+#include "qeventdispatcher_glib_qpa_p.h"
+#endif
+#include "qeventdispatcher_qpa_p.h"
+#ifndef QT_NO_CURSOR
+#include "private/qcursor_p.h"
+#endif
+
+#include "private/qwidget_p.h"
+#include "private/qevent_p.h"
+
+#include "qgenericpluginfactory_qpa.h"
+#include "qplatformintegrationfactory_qpa_p.h"
+#include <qdesktopwidget.h>
+
+#include <qinputcontext.h>
+#include <QPlatformCursor>
+#include <qdebug.h>
+#include <QWindowSystemInterface>
+#include "qwindowsysteminterface_qpa_p.h"
+#include <QPlatformIntegration>
+
+#include "qdesktopwidget_qpa_p.h"
+
+QT_BEGIN_NAMESPACE
+
+static QString appName;
+static QString appFont;
+
+QWidget *qt_button_down = 0; // widget got last button-down
+
+static bool app_do_modal = false;
+extern QWidgetList *qt_modal_stack; // stack of modal widgets
+
+int qt_last_x = 0;
+int qt_last_y = 0;
+QPointer<QWidget> qt_last_mouse_receiver = 0;
+
+static Qt::MouseButtons buttons = Qt::NoButton;
+static ulong mousePressTime;
+static Qt::MouseButton mousePressButton = Qt::NoButton;
+static int mousePressX;
+static int mousePressY;
+static int mouse_double_click_distance = 5;
+
+void QApplicationPrivate::processWindowSystemEvent(QWindowSystemInterfacePrivate::WindowSystemEvent *e)
+{
+ switch(e->type) {
+ case QWindowSystemInterfacePrivate::Mouse:
+ QApplicationPrivate::processMouseEvent(static_cast<QWindowSystemInterfacePrivate::MouseEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::Wheel:
+ QApplicationPrivate::processWheelEvent(static_cast<QWindowSystemInterfacePrivate::WheelEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::Key:
+ QApplicationPrivate::processKeyEvent(static_cast<QWindowSystemInterfacePrivate::KeyEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::Touch:
+ QApplicationPrivate::processTouchEvent(static_cast<QWindowSystemInterfacePrivate::TouchEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::GeometryChange:
+ QApplicationPrivate::processGeometryChangeEvent(static_cast<QWindowSystemInterfacePrivate::GeometryChangeEvent*>(e));
+ break;
+ case QWindowSystemInterfacePrivate::Enter:
+ QApplicationPrivate::processEnterEvent(static_cast<QWindowSystemInterfacePrivate::EnterEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::Leave:
+ QApplicationPrivate::processLeaveEvent(static_cast<QWindowSystemInterfacePrivate::LeaveEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::ActivatedWindow:
+ QApplicationPrivate::processActivatedEvent(static_cast<QWindowSystemInterfacePrivate::ActivatedWindowEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::Close:
+ QApplicationPrivate::processCloseEvent(
+ static_cast<QWindowSystemInterfacePrivate::CloseEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::ScreenCountChange:
+ QApplicationPrivate::reportScreenCount(
+ static_cast<QWindowSystemInterfacePrivate::ScreenCountEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::ScreenGeometry:
+ QApplicationPrivate::reportGeometryChange(
+ static_cast<QWindowSystemInterfacePrivate::ScreenGeometryEvent *>(e));
+ break;
+ case QWindowSystemInterfacePrivate::ScreenAvailableGeometry:
+ QApplicationPrivate::reportAvailableGeometryChange(
+ static_cast<QWindowSystemInterfacePrivate::ScreenAvailableGeometryEvent *>(e));
+ break;
+ default:
+ qWarning() << "Unknown user input event type:" << e->type;
+ break;
+ }
+}
+
+QString QApplicationPrivate::appName() const
+{
+ return QT_PREPEND_NAMESPACE(appName);
+}
+
+void QApplicationPrivate::createEventDispatcher()
+{
+ Q_Q(QApplication);
+#if !defined(QT_NO_GLIB)
+ if (qgetenv("QT_NO_GLIB").isEmpty() && QEventDispatcherGlib::versionSupported())
+ eventDispatcher = new QPAEventDispatcherGlib(q);
+ else
+#endif
+ eventDispatcher = new QEventDispatcherQPA(q);
+}
+
+static bool qt_try_modal(QWidget *widget, QEvent::Type type)
+{
+ QWidget * top = 0;
+
+ if (QApplicationPrivate::tryModalHelper(widget, &top))
+ return true;
+
+ bool block_event = false;
+ bool paint_event = false;
+
+ switch (type) {
+#if 0
+ case QEvent::Focus:
+ if (!static_cast<QWSFocusEvent*>(event)->simpleData.get_focus)
+ break;
+ // drop through
+#endif
+ case QEvent::MouseButtonPress: // disallow mouse/key events
+ case QEvent::MouseButtonRelease:
+ case QEvent::MouseMove:
+ case QEvent::KeyPress:
+ case QEvent::KeyRelease:
+ block_event = true;
+ break;
+ default:
+ break;
+ }
+
+ if ((block_event || paint_event) && top->parentWidget() == 0)
+ top->raise();
+
+ return !block_event;
+}
+
+
+
+void QApplicationPrivate::enterModal_sys(QWidget *widget)
+{
+ if (!qt_modal_stack)
+ qt_modal_stack = new QWidgetList;
+ qt_modal_stack->insert(0, widget);
+ app_do_modal = true;
+}
+
+void QApplicationPrivate::leaveModal_sys(QWidget *widget )
+{
+ if (qt_modal_stack && qt_modal_stack->removeAll(widget)) {
+ if (qt_modal_stack->isEmpty()) {
+ delete qt_modal_stack;
+ qt_modal_stack = 0;
+ }
+ }
+ app_do_modal = qt_modal_stack != 0;
+}
+
+bool QApplicationPrivate::modalState()
+{
+ return app_do_modal;
+}
+
+void QApplicationPrivate::closePopup(QWidget *popup)
+{
+ Q_Q(QApplication);
+ if (!popupWidgets)
+ return;
+ popupWidgets->removeAll(popup);
+
+//###
+// if (popup == qt_popup_down) {
+// qt_button_down = 0;
+// qt_popup_down = 0;
+// }
+
+ if (QApplicationPrivate::popupWidgets->count() == 0) { // this was the last popup
+ delete QApplicationPrivate::popupWidgets;
+ QApplicationPrivate::popupWidgets = 0;
+
+ //### replay mouse event?
+
+ //### transfer/release mouse grab
+
+ //### transfer/release keyboard grab
+
+ //give back focus
+
+ if (active_window) {
+ if (QWidget *fw = active_window->focusWidget()) {
+ if (fw != QApplication::focusWidget()) {
+ fw->setFocus(Qt::PopupFocusReason);
+ } else {
+ QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
+ q->sendEvent(fw, &e);
+ }
+ }
+ }
+
+ } else {
+ // A popup was closed, so the previous popup gets the focus.
+
+ QWidget* aw = QApplicationPrivate::popupWidgets->last();
+ if (QWidget *fw = aw->focusWidget())
+ fw->setFocus(Qt::PopupFocusReason);
+
+ //### regrab the keyboard and mouse in case 'popup' lost the grab
+
+
+ }
+
+}
+
+static int openPopupCount = 0;
+void QApplicationPrivate::openPopup(QWidget *popup)
+{
+ openPopupCount++;
+ if (!popupWidgets) { // create list
+ popupWidgets = new QWidgetList;
+
+ /* only grab if you are the first/parent popup */
+ //#### ->grabMouse(popup,true);
+ //#### ->grabKeyboard(popup,true);
+ //### popupGrabOk = true;
+ }
+ popupWidgets->append(popup); // add to end of list
+
+ // popups are not focus-handled by the window system (the first
+ // popup grabbed the keyboard), so we have to do that manually: A
+ // new popup gets the focus
+ if (popup->focusWidget()) {
+ popup->focusWidget()->setFocus(Qt::PopupFocusReason);
+ } else if (popupWidgets->count() == 1) { // this was the first popup
+ if (QWidget *fw = QApplication::focusWidget()) {
+ QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
+ QApplication::sendEvent(fw, &e);
+ }
+ }
+}
+
+void QApplicationPrivate::initializeMultitouch_sys()
+{
+}
+
+void QApplicationPrivate::cleanupMultitouch_sys()
+{
+}
+
+void QApplicationPrivate::initializeWidgetPaletteHash()
+{
+}
+
+void QApplication::setCursorFlashTime(int msecs)
+{
+ QApplicationPrivate::cursor_flash_time = msecs;
+}
+
+int QApplication::cursorFlashTime()
+{
+ return QApplicationPrivate::cursor_flash_time;
+}
+
+void QApplication::setDoubleClickInterval(int ms)
+{
+ QApplicationPrivate::mouse_double_click_time = ms;
+}
+
+int QApplication::doubleClickInterval()
+{
+ return QApplicationPrivate::mouse_double_click_time;
+}
+
+void QApplication::setKeyboardInputInterval(int ms)
+{
+ QApplicationPrivate::keyboard_input_time = ms;
+}
+
+int QApplication::keyboardInputInterval()
+{
+ return QApplicationPrivate::keyboard_input_time;
+}
+
+#ifndef QT_NO_WHEELEVENT
+void QApplication::setWheelScrollLines(int lines)
+{
+ QApplicationPrivate::wheel_scroll_lines = lines;
+}
+
+int QApplication::wheelScrollLines()
+{
+ return QApplicationPrivate::wheel_scroll_lines;
+}
+#endif
+
+void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
+{
+ switch (effect) {
+ case Qt::UI_AnimateMenu:
+ QApplicationPrivate::animate_menu = enable;
+ break;
+ case Qt::UI_FadeMenu:
+ if (enable)
+ QApplicationPrivate::animate_menu = true;
+ QApplicationPrivate::fade_menu = enable;
+ break;
+ case Qt::UI_AnimateCombo:
+ QApplicationPrivate::animate_combo = enable;
+ break;
+ case Qt::UI_AnimateTooltip:
+ QApplicationPrivate::animate_tooltip = enable;
+ break;
+ case Qt::UI_FadeTooltip:
+ if (enable)
+ QApplicationPrivate::animate_tooltip = true;
+ QApplicationPrivate::fade_tooltip = enable;
+ break;
+ case Qt::UI_AnimateToolBox:
+ QApplicationPrivate::animate_toolbox = enable;
+ break;
+ default:
+ QApplicationPrivate::animate_ui = enable;
+ break;
+ }
+}
+
+bool QApplication::isEffectEnabled(Qt::UIEffect effect)
+{
+ if (QColormap::instance().depth() < 16 || !QApplicationPrivate::animate_ui)
+ return false;
+
+ switch(effect) {
+ case Qt::UI_AnimateMenu:
+ return QApplicationPrivate::animate_menu;
+ case Qt::UI_FadeMenu:
+ return QApplicationPrivate::fade_menu;
+ case Qt::UI_AnimateCombo:
+ return QApplicationPrivate::animate_combo;
+ case Qt::UI_AnimateTooltip:
+ return QApplicationPrivate::animate_tooltip;
+ case Qt::UI_FadeTooltip:
+ return QApplicationPrivate::fade_tooltip;
+ case Qt::UI_AnimateToolBox:
+ return QApplicationPrivate::animate_toolbox;
+ default:
+ return QApplicationPrivate::animate_ui;
+ }
+}
+
+#ifndef QT_NO_CURSOR
+void QApplication::setOverrideCursor(const QCursor &cursor)
+{
+ qApp->d_func()->cursor_list.prepend(cursor);
+ qt_qpa_set_cursor(0, false);
+}
+
+void QApplication::restoreOverrideCursor()
+{
+ if (qApp->d_func()->cursor_list.isEmpty())
+ return;
+ qApp->d_func()->cursor_list.removeFirst();
+ qt_qpa_set_cursor(0, false);
+}
+
+#endif// QT_NO_CURSOR
+
+QWidget *QApplication::topLevelAt(const QPoint &pos)
+{
+ QPlatformIntegration *pi = QApplicationPrivate::platformIntegration();
+
+ QList<QPlatformScreen *> screens = pi->screens();
+ QList<QPlatformScreen *>::const_iterator screen = screens.constBegin();
+ QList<QPlatformScreen *>::const_iterator end = screens.constEnd();
+
+ // The first screen in a virtual environment should know about all top levels
+ if (pi->isVirtualDesktop()) {
+ QWidget *w = (*screen)->topLevelAt(pos);
+ return w;
+ }
+
+ while (screen != end) {
+ if ((*screen)->geometry().contains(pos))
+ return (*screen)->topLevelAt(pos);
+ ++screen;
+ }
+ return 0;
+}
+
+void QApplication::beep()
+{
+}
+
+void QApplication::alert(QWidget *, int)
+{
+}
+
+QPlatformNativeInterface *QApplication::platformNativeInterface()
+{
+ QPlatformIntegration *pi = QApplicationPrivate::platformIntegration();
+ return pi->nativeInterface();
+}
+
+static void init_platform(const QString &name, const QString &platformPluginPath)
+{
+ QApplicationPrivate::platform_integration = QPlatformIntegrationFactory::create(name, platformPluginPath);
+ if (!QApplicationPrivate::platform_integration) {
+ QStringList keys = QPlatformIntegrationFactory::keys(platformPluginPath);
+ QString fatalMessage =
+ QString::fromLatin1("Failed to load platform plugin \"%1\". Available platforms are: \n").arg(name);
+ foreach(QString key, keys) {
+ fatalMessage.append(key + QString::fromLatin1("\n"));
+ }
+ qFatal("%s", fatalMessage.toLocal8Bit().constData());
+
+ }
+
+}
+
+
+static void cleanup_platform()
+{
+ delete QApplicationPrivate::platform_integration;
+ QApplicationPrivate::platform_integration = 0;
+}
+
+static void init_plugins(const QList<QByteArray> pluginList)
+{
+ for (int i = 0; i < pluginList.count(); ++i) {
+ QByteArray pluginSpec = pluginList.at(i);
+ qDebug() << "init_plugins" << i << pluginSpec;
+ int colonPos = pluginSpec.indexOf(':');
+ QObject *plugin;
+ if (colonPos < 0)
+ plugin = QGenericPluginFactory::create(QLatin1String(pluginSpec), QString());
+ else
+ plugin = QGenericPluginFactory::create(QLatin1String(pluginSpec.mid(0, colonPos)),
+ QLatin1String(pluginSpec.mid(colonPos+1)));
+ qDebug() << " created" << plugin;
+ }
+}
+
+#ifndef QT_NO_QWS_INPUTMETHODS
+class QDummyInputContext : public QInputContext
+{
+public:
+ explicit QDummyInputContext(QObject* parent = 0) : QInputContext(parent) {}
+ ~QDummyInputContext() {}
+ QString identifierName() { return QString(); }
+ QString language() { return QString(); }
+
+ void reset() {}
+ bool isComposing() const { return false; }
+
+};
+#endif // QT_NO_QWS_INPUTMETHODS
+
+void qt_init(QApplicationPrivate *priv, int type)
+{
+ Q_UNUSED(type);
+
+ qApp->setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
+ char *p;
+ char **argv = priv->argv;
+ int argc = priv->argc;
+
+ if (argv && *argv) { //apparently, we allow people to pass 0 on the other platforms
+ p = strrchr(argv[0], '/');
+ appName = QString::fromLocal8Bit(p ? p + 1 : argv[0]);
+ }
+
+ QList<QByteArray> pluginList;
+ QString platformPluginPath = QLatin1String(qgetenv("QT_QPA_PLATFORM_PLUGIN_PATH"));
+ QByteArray platformName;
+#ifdef QT_QPA_DEFAULT_PLATFORM_NAME
+ platformName = QT_QPA_DEFAULT_PLATFORM_NAME;
+#endif
+ QByteArray platformNameEnv = qgetenv("QT_QPA_PLATFORM");
+ if (!platformNameEnv.isEmpty()) {
+ platformName = platformNameEnv;
+ }
+
+ // Get command line params
+
+ int j = argc ? 1 : 0;
+ for (int i=1; i<argc; i++) {
+ if (argv[i] && *argv[i] != '-') {
+ argv[j++] = argv[i];
+ continue;
+ }
+ QByteArray arg = argv[i];
+ if (arg == "-fn" || arg == "-font") {
+ if (++i < argc)
+ appFont = QString::fromLocal8Bit(argv[i]);
+ } else if (arg == "-platformpluginpath") {
+ if (++i < argc)
+ platformPluginPath = QLatin1String(argv[i]);
+ } else if (arg == "-platform") {
+ if (++i < argc)
+ platformName = argv[i];
+ } else if (arg == "-plugin") {
+ if (++i < argc)
+ pluginList << argv[i];
+ } else {
+ argv[j++] = argv[i];
+ }
+ }
+
+ if (j < priv->argc) {
+ priv->argv[j] = 0;
+ priv->argc = j;
+ }
+
+#if 0
+ QByteArray pluginEnv = qgetenv("QT_QPA_PLUGINS");
+ if (!pluginEnv.isEmpty()) {
+ pluginList.append(pluginEnv.split(';'));
+ }
+#endif
+
+ init_platform(QLatin1String(platformName), platformPluginPath);
+ init_plugins(pluginList);
+
+ QColormap::initialize();
+ QFont::initialize();
+#ifndef QT_NO_CURSOR
+// QCursorData::initialize();
+#endif
+
+ qApp->setObjectName(appName);
+
+#ifndef QT_NO_QWS_INPUTMETHODS
+ qApp->setInputContext(new QDummyInputContext(qApp));
+#endif
+}
+
+void qt_cleanup()
+{
+ cleanup_platform();
+
+ QPixmapCache::clear();
+#ifndef QT_NO_CURSOR
+ QCursorData::cleanup();
+#endif
+ QFont::cleanup();
+ QColormap::cleanup();
+ delete QApplicationPrivate::inputContext;
+ QApplicationPrivate::inputContext = 0;
+
+ QApplicationPrivate::active_window = 0; //### this should not be necessary
+}
+
+
+#ifdef QT3_SUPPORT
+void QApplication::setMainWidget(QWidget *mainWidget)
+{
+ QApplicationPrivate::main_widget = mainWidget;
+ if (QApplicationPrivate::main_widget && windowIcon().isNull()
+ && QApplicationPrivate::main_widget->testAttribute(Qt::WA_SetWindowIcon))
+ setWindowIcon(QApplicationPrivate::main_widget->windowIcon());
+}
+#endif
+
+void QApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::MouseEvent *e)
+{
+ // qDebug() << "handleMouseEvent" << tlw << ev.pos() << ev.globalPos() << hex << ev.buttons();
+ static QWeakPointer<QWidget> implicit_mouse_grabber;
+
+ QEvent::Type type;
+ // move first
+ Qt::MouseButtons stateChange = e->buttons ^ buttons;
+ if (e->globalPos != QPoint(qt_last_x, qt_last_y) && (stateChange != Qt::NoButton)) {
+ QWindowSystemInterfacePrivate::MouseEvent * newMouseEvent =
+ new QWindowSystemInterfacePrivate::MouseEvent(e->widget.data(), e->timestamp, e->localPos, e->globalPos, e->buttons);
+ QWindowSystemInterfacePrivate::windowSystemEventQueue.prepend(newMouseEvent); // just in case the move triggers a new event loop
+ stateChange = Qt::NoButton;
+ }
+
+ QWidget * tlw = e->widget.data();
+
+ QPoint localPoint = e->localPos;
+ QPoint globalPoint = e->globalPos;
+ QWidget *mouseWindow = tlw;
+
+ Qt::MouseButton button = Qt::NoButton;
+
+
+ if (qt_last_x != globalPoint.x() || qt_last_y != globalPoint.y()) {
+ type = QEvent::MouseMove;
+ qt_last_x = globalPoint.x();
+ qt_last_y = globalPoint.y();
+ if (qAbs(globalPoint.x() - mousePressX) > mouse_double_click_distance||
+ qAbs(globalPoint.y() - mousePressY) > mouse_double_click_distance)
+ mousePressButton = Qt::NoButton;
+ }
+ else { // check to see if a new button has been pressed/released
+ for (int check = Qt::LeftButton;
+ check <= Qt::XButton2;
+ check = check << 1) {
+ if (check & stateChange) {
+ button = Qt::MouseButton(check);
+ break;
+ }
+ }
+ if (button == Qt::NoButton) {
+ // Ignore mouse events that don't change the current state
+ return;
+ }
+ buttons = e->buttons;
+ if (button & e->buttons) {
+ if ((e->timestamp - mousePressTime) < static_cast<ulong>(QApplication::doubleClickInterval()) && button == mousePressButton) {
+ type = QEvent::MouseButtonDblClick;
+ mousePressButton = Qt::NoButton;
+ }
+ else {
+ type = QEvent::MouseButtonPress;
+ mousePressTime = e->timestamp;
+ mousePressButton = button;
+ mousePressX = qt_last_x;
+ mousePressY = qt_last_y;
+ }
+ }
+ else
+ type = QEvent::MouseButtonRelease;
+ }
+
+ if (self->inPopupMode()) {
+ //popup mouse handling is magical...
+ mouseWindow = qApp->activePopupWidget();
+
+ implicit_mouse_grabber.clear();
+ //### how should popup mode and implicit mouse grab interact?
+
+ } else if (tlw && app_do_modal && !qt_try_modal(tlw, QEvent::MouseButtonRelease) ) {
+ //even if we're blocked by modality, we should deliver the mouse release event..
+ //### this code is not completely correct: multiple buttons can be pressed simultaneously
+ if (!(implicit_mouse_grabber && buttons == Qt::NoButton)) {
+ //qDebug() << "modal blocked mouse event to" << tlw;
+ return;
+ }
+ }
+
+ // find the tlw if we didn't get it from the plugin
+ if (!mouseWindow) {
+ mouseWindow = QApplication::topLevelAt(globalPoint);
+ }
+
+ if (!mouseWindow && !implicit_mouse_grabber)
+ mouseWindow = QApplication::desktop();
+
+ if (mouseWindow && mouseWindow != tlw) {
+ //we did not get a sensible localPoint from the window system, so let's calculate it
+ localPoint = mouseWindow->mapFromGlobal(globalPoint);
+ }
+
+ // which child should have it?
+ QWidget *mouseWidget = mouseWindow;
+ if (mouseWindow) {
+ QWidget *w = mouseWindow->childAt(localPoint);
+ if (w) {
+ mouseWidget = w;
+ }
+ }
+
+ //handle implicit mouse grab
+ if (type == QEvent::MouseButtonPress && !implicit_mouse_grabber) {
+ implicit_mouse_grabber = mouseWidget;
+
+ Q_ASSERT(mouseWindow);
+ mouseWindow->activateWindow(); //focus
+ } else if (implicit_mouse_grabber) {
+ mouseWidget = implicit_mouse_grabber.data();
+ mouseWindow = mouseWidget->window();
+ if (mouseWindow != tlw)
+ localPoint = mouseWindow->mapFromGlobal(globalPoint);
+ }
+
+ Q_ASSERT(mouseWidget);
+
+ //localPoint is local to mouseWindow, but it needs to be local to mouseWidget
+ localPoint = mouseWidget->mapFrom(mouseWindow, localPoint);
+
+ if (buttons == Qt::NoButton) {
+ //qDebug() << "resetting mouse grabber";
+ implicit_mouse_grabber.clear();
+ }
+
+ if (mouseWidget != qt_last_mouse_receiver) {
+ dispatchEnterLeave(mouseWidget, qt_last_mouse_receiver);
+ qt_last_mouse_receiver = mouseWidget;
+ }
+
+ // Remember, we might enter a modal event loop when sending the event,
+ // so think carefully before adding code below this point.
+
+ // qDebug() << "sending mouse ev." << ev.type() << localPoint << globalPoint << ev.button() << ev.buttons() << mouseWidget << "mouse grabber" << implicit_mouse_grabber;
+
+ QMouseEvent ev(type, localPoint, globalPoint, button, buttons, QApplication::keyboardModifiers());
+
+ QList<QWeakPointer<QPlatformCursor> > cursors = QPlatformCursorPrivate::getInstances();
+ foreach (QWeakPointer<QPlatformCursor> cursor, cursors) {
+ if (cursor)
+ cursor.data()->pointerEvent(ev);
+ }
+
+ int oldOpenPopupCount = openPopupCount;
+ QApplication::sendSpontaneousEvent(mouseWidget, &ev);
+
+#ifndef QT_NO_CONTEXTMENU
+ if (type == QEvent::MouseButtonPress && button == Qt::RightButton && (openPopupCount == oldOpenPopupCount)) {
+ QContextMenuEvent e(QContextMenuEvent::Mouse, localPoint, globalPoint, QApplication::keyboardModifiers());
+ QApplication::sendSpontaneousEvent(mouseWidget, &e);
+ }
+#endif // QT_NO_CONTEXTMENU
+}
+
+
+//### there's a lot of duplicated logic here -- refactoring required!
+
+void QApplicationPrivate::processWheelEvent(QWindowSystemInterfacePrivate::WheelEvent *e)
+{
+// QPoint localPoint = ev.pos();
+ QPoint globalPoint = e->globalPos;
+// bool trustLocalPoint = !!tlw; //is there something the local point can be local to?
+ QWidget *mouseWidget;
+
+ qt_last_x = globalPoint.x();
+ qt_last_y = globalPoint.y();
+
+ QWidget *mouseWindow = e->widget.data();
+
+ // find the tlw if we didn't get it from the plugin
+ if (!mouseWindow) {
+ mouseWindow = QApplication::topLevelAt(globalPoint);
+ }
+
+ if (!mouseWindow)
+ return;
+
+ mouseWidget = mouseWindow;
+
+ if (app_do_modal && !qt_try_modal(mouseWindow, QEvent::Wheel) ) {
+ qDebug() << "modal blocked wheel event" << mouseWindow;
+ return;
+ }
+ QPoint p = mouseWindow->mapFromGlobal(globalPoint);
+ QWidget *w = mouseWindow->childAt(p);
+ if (w) {
+ mouseWidget = w;
+ p = mouseWidget->mapFromGlobal(globalPoint);
+ }
+
+ QWheelEvent ev(p, globalPoint, e->delta, buttons, QApplication::keyboardModifiers(),
+ e->orient);
+ QApplication::sendSpontaneousEvent(mouseWidget, &ev);
+}
+
+
+
+// Remember, Qt convention is: keyboard state is state *before*
+
+void QApplicationPrivate::processKeyEvent(QWindowSystemInterfacePrivate::KeyEvent *e)
+{
+ QWidget *focusW = 0;
+ if (self->inPopupMode()) {
+ QWidget *popupW = qApp->activePopupWidget();
+ focusW = popupW->focusWidget() ? popupW->focusWidget() : popupW;
+ }
+ if (!focusW)
+ focusW = QApplication::focusWidget();
+ if (!focusW) {
+ focusW = e->widget.data();
+ }
+ if (!focusW)
+ focusW = QApplication::activeWindow();
+
+ //qDebug() << "handleKeyEvent" << hex << e->key() << e->modifiers() << e->text() << "widget" << focusW;
+
+ if (!focusW)
+ return;
+ if (app_do_modal && !qt_try_modal(focusW, e->keyType))
+ return;
+
+ if (e->nativeScanCode || e->nativeVirtualKey || e->nativeModifiers) {
+ QKeyEventEx ev(e->keyType, e->key, e->modifiers, e->unicode, e->repeat, e->repeatCount,
+ e->nativeScanCode, e->nativeVirtualKey, e->nativeModifiers);
+ QApplication::sendSpontaneousEvent(focusW, &ev);
+ } else {
+ QKeyEvent ev(e->keyType, e->key, e->modifiers, e->unicode, e->repeat, e->repeatCount);
+ QApplication::sendSpontaneousEvent(focusW, &ev);
+ }
+}
+
+void QApplicationPrivate::processEnterEvent(QWindowSystemInterfacePrivate::EnterEvent *e)
+{
+ QApplicationPrivate::dispatchEnterLeave(e->enter.data(),0);
+ qt_last_mouse_receiver = e->enter.data();
+}
+
+void QApplicationPrivate::processLeaveEvent(QWindowSystemInterfacePrivate::LeaveEvent *e)
+{
+ QApplicationPrivate::dispatchEnterLeave(0,qt_last_mouse_receiver);
+
+ if (e->leave.data() && !e->leave.data()->isAncestorOf(qt_last_mouse_receiver)) //(???) this should not happen
+ QApplicationPrivate::dispatchEnterLeave(0, e->leave.data());
+ qt_last_mouse_receiver = 0;
+
+}
+
+void QApplicationPrivate::processActivatedEvent(QWindowSystemInterfacePrivate::ActivatedWindowEvent *e)
+{
+ QApplication::setActiveWindow(e->activated.data());
+}
+
+void QApplicationPrivate::processGeometryChangeEvent(QWindowSystemInterfacePrivate::GeometryChangeEvent *e)
+{
+ if (e->tlw.isNull())
+ return;
+ QWidget *tlw = e->tlw.data();
+ if (!tlw->isWindow())
+ return; //geo of native child widgets is controlled by lighthouse
+ //so we already have sent the events; besides this new rect
+ //is not mapped to parent
+
+ QRect newRect = e->newGeometry;
+ QRect cr(tlw->geometry());
+ bool isResize = cr.size() != newRect.size();
+ bool isMove = cr.topLeft() != newRect.topLeft();
+ tlw->data->crect = newRect;
+ if (isResize) {
+ QResizeEvent e(tlw->data->crect.size(), cr.size());
+ QApplication::sendSpontaneousEvent(tlw, &e);
+ tlw->update();
+ }
+
+ if (isMove) {
+ //### frame geometry
+ QMoveEvent e(tlw->data->crect.topLeft(), cr.topLeft());
+ QApplication::sendSpontaneousEvent(tlw, &e);
+ }
+}
+
+void QApplicationPrivate::processCloseEvent(QWindowSystemInterfacePrivate::CloseEvent *e)
+{
+ if (e->topLevel.isNull()) {
+ //qDebug() << "QApplicationPrivate::processCloseEvent NULL";
+ return;
+ }
+ e->topLevel.data()->d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
+}
+
+void QApplicationPrivate::processTouchEvent(QWindowSystemInterfacePrivate::TouchEvent *e)
+{
+ translateRawTouchEvent(e->widget.data(), e->devType, e->points);
+}
+
+void QApplicationPrivate::reportScreenCount(QWindowSystemInterfacePrivate::ScreenCountEvent *e)
+{
+ // This operation only makes sense after the QApplication constructor runs
+ if (QCoreApplication::startingUp())
+ return;
+
+ QApplication::desktop()->d_func()->updateScreenList();
+ // signal anything listening for creation or deletion of screens
+ QDesktopWidget *desktop = QApplication::desktop();
+ emit desktop->screenCountChanged(e->count);
+}
+
+void QApplicationPrivate::reportGeometryChange(QWindowSystemInterfacePrivate::ScreenGeometryEvent *e)
+{
+ // This operation only makes sense after the QApplication constructor runs
+ if (QCoreApplication::startingUp())
+ return;
+
+ QApplication::desktop()->d_func()->updateScreenList();
+
+ // signal anything listening for screen geometry changes
+ QDesktopWidget *desktop = QApplication::desktop();
+ emit desktop->resized(e->index);
+
+ // make sure maximized and fullscreen windows are updated
+ QWidgetList list = QApplication::topLevelWidgets();
+ for (int i = list.size() - 1; i >= 0; --i) {
+ QWidget *w = list.at(i);
+ if (w->isFullScreen())
+ w->d_func()->setFullScreenSize_helper();
+ else if (w->isMaximized())
+ w->d_func()->setMaxWindowState_helper();
+ }
+}
+
+void QApplicationPrivate::reportAvailableGeometryChange(
+ QWindowSystemInterfacePrivate::ScreenAvailableGeometryEvent *e)
+{
+ // This operation only makes sense after the QApplication constructor runs
+ if (QCoreApplication::startingUp())
+ return;
+
+ QApplication::desktop()->d_func()->updateScreenList();
+
+ // signal anything listening for screen geometry changes
+ QDesktopWidget *desktop = QApplication::desktop();
+ emit desktop->workAreaResized(e->index);
+
+ // make sure maximized and fullscreen windows are updated
+ QWidgetList list = QApplication::topLevelWidgets();
+ for (int i = list.size() - 1; i >= 0; --i) {
+ QWidget *w = list.at(i);
+ if (w->isFullScreen())
+ w->d_func()->setFullScreenSize_helper();
+ else if (w->isMaximized())
+ w->d_func()->setMaxWindowState_helper();
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/gui/kernel/qapplication_qws.cpp b/src/gui/kernel/qapplication_qws.cpp
new file mode 100644
index 0000000000..642d3e6afc
--- /dev/null
+++ b/src/gui/kernel/qapplication_qws.cpp
@@ -0,0 +1,3797 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qglobal.h"
+#include "qlibrary.h"
+#include "qcursor.h"
+#include "qapplication.h"
+#include "private/qapplication_p.h"
+#include "qwidget.h"
+#include "qbitarray.h"
+#include "qpainter.h"
+#include "qpixmapcache.h"
+#include "qdatetime.h"
+#include "qtextcodec.h"
+#include "qdatastream.h"
+#include "qbuffer.h"
+#include "qsocketnotifier.h"
+#include "qsessionmanager.h"
+#include "qclipboard.h"
+#include "qbitmap.h"
+#include "qwssocket_qws.h"
+#include "qtransportauth_qws.h"
+#include "private/qtransportauth_qws_p.h"
+#include "qwsevent_qws.h"
+#include "private/qwscommand_qws_p.h"
+#include "qwsproperty_qws.h"
+#include "qscreen_qws.h"
+#include "qscreenproxy_qws.h"
+#include "qcopchannel_qws.h"
+#include "private/qlock_p.h"
+#include "private/qwslock_p.h"
+//#include "qmemorymanager_qws.h"
+#include "qwsmanager_qws.h"
+//#include "qwsregionmanager_qws.h"
+#include "qwindowsystem_qws.h"
+#include "private/qwindowsystem_p.h"
+#include "qdecorationfactory_qws.h"
+
+#include "qwsdisplay_qws.h"
+#include "private/qwsdisplay_qws_p.h"
+#include "private/qwsinputcontext_p.h"
+#include "qfile.h"
+#include "qhash.h"
+#include "qdesktopwidget.h"
+#include "qcolormap.h"
+#include "private/qcursor_p.h"
+#include "qsettings.h"
+#include "qdebug.h"
+#include "qeventdispatcher_qws_p.h"
+#if !defined(QT_NO_GLIB)
+# include "qeventdispatcher_glib_qws_p.h"
+#endif
+
+
+#include "private/qwidget_p.h"
+#include "private/qbackingstore_p.h"
+#include "private/qwindowsurface_qws_p.h"
+#include "private/qfont_p.h"
+
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <locale.h>
+#include <errno.h>
+#include <fcntl.h>
+#ifdef Q_OS_VXWORKS
+# include <sys/times.h>
+#else
+# include <sys/time.h>
+#endif
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <qvfbhdr.h>
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+#ifdef QT_NO_QSHM
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#ifndef Q_OS_DARWIN
+# include <sys/sem.h>
+#endif
+#include <sys/socket.h>
+#else
+#include "private/qwssharedmemory_p.h"
+#endif
+#endif
+
+QT_BEGIN_NAMESPACE
+
+#ifndef QT_NO_DIRECTPAINTER
+class QDirectPainter;
+extern void qt_directpainter_region(QDirectPainter *dp, const QRegion &alloc, int type);
+#ifndef QT_NO_QWSEMBEDWIDGET
+extern void qt_directpainter_embedevent(QDirectPainter *dp,
+ const QWSEmbedEvent *e);
+#endif
+#endif // QT_NO_DIRECTPAINTER
+
+const int qwsSharedRamSize = 1 * 1024; // misc data, written by server, read by clients
+
+extern QApplication::Type qt_appType;
+extern QDesktopWidget *qt_desktopWidget;
+
+//these used to be environment variables, they are initialized from
+//environment variables in
+
+bool qws_savefonts = false;
+bool qws_screen_is_interlaced=false; //### should be detected
+bool qws_shared_memory = false;
+bool qws_sw_cursor = true;
+bool qws_accel = true; // ### never set
+QByteArray qws_display_spec(":0");
+Q_GUI_EXPORT int qws_display_id = 0;
+Q_GUI_EXPORT int qws_client_id = 0;
+QWidget *qt_pressGrab = 0;
+QWidget *qt_mouseGrb = 0;
+int *qt_last_x = 0;
+int *qt_last_y = 0;
+
+static int mouse_x_root = -1;
+static int mouse_y_root = -1;
+static int mouse_state = 0;
+static int mouse_double_click_distance = 5;
+
+int qt_servershmid = -1;
+
+bool qws_overrideCursor = false;
+#ifndef QT_NO_QWS_MANAGER
+
+extern Q_GUI_EXPORT QWSServer *qwsServer;
+
+static QDecoration *qws_decoration = 0;
+#endif
+
+#if defined(QT_DEBUG)
+/*
+extern "C" void dumpmem(const char* m)
+{
+ static int init=0;
+ static int prev=0;
+ FILE* f = fopen("/proc/meminfo","r");
+ // char line[100];
+ int total=0,used=0,free=0,shared=0,buffers=0,cached=0;
+ fscanf(f,"%*[^M]Mem: %d %d %d %d %d %d",&total,&used,&free,&shared,&buffers,&cached);
+ used -= buffers + cached;
+ if (!init) {
+ init=used;
+ } else {
+ printf("%40s: %+8d = %8d\n",m,used-init-prev,used-init);
+ prev = used-init;
+ }
+ fclose(f);
+}
+*/
+#endif
+
+// Get the name of the directory where Qt for Embedded Linux temporary data should
+// live.
+QString qws_dataDir()
+{
+ static QString result;
+ if (!result.isEmpty())
+ return result;
+ result = QT_VFB_DATADIR(qws_display_id);
+ QByteArray dataDir = result.toLocal8Bit();
+
+#if defined(Q_OS_INTEGRITY)
+ /* ensure filesystem is ready before starting requests */
+ WaitForFileSystemInitialization();
+#endif
+
+ if (QT_MKDIR(dataDir, 0700)) {
+ if (errno != EEXIST) {
+ qFatal("Cannot create Qt for Embedded Linux data directory: %s", dataDir.constData());
+ }
+ }
+
+ QT_STATBUF buf;
+ if (QT_LSTAT(dataDir, &buf))
+ qFatal("stat failed for Qt for Embedded Linux data directory: %s", dataDir.constData());
+
+ if (!S_ISDIR(buf.st_mode))
+ qFatal("%s is not a directory", dataDir.constData());
+
+#if !defined(Q_OS_INTEGRITY) && !defined(Q_OS_VXWORKS)
+ if (buf.st_uid != getuid())
+ qFatal("Qt for Embedded Linux data directory is not owned by user %d", getuid());
+
+ if ((buf.st_mode & 0677) != 0600)
+ qFatal("Qt for Embedded Linux data directory has incorrect permissions: %s", dataDir.constData());
+#endif
+
+ result.append("/");
+ return result;
+}
+
+// Get the filename of the pipe Qt for Embedded Linux uses for server/client comms
+Q_GUI_EXPORT QString qws_qtePipeFilename()
+{
+ qws_dataDir();
+ return QTE_PIPE(qws_display_id);
+}
+
+static void setMaxWindowRect(const QRect &rect)
+{
+ const QList<QScreen*> subScreens = qt_screen->subScreens();
+ QScreen *screen = qt_screen;
+ int screenNo = 0;
+ for (int i = 0; i < subScreens.size(); ++i) {
+ if (subScreens.at(i)->region().contains(rect)) {
+ screen = subScreens.at(i);
+ screenNo = i;
+ break;
+ }
+ }
+
+ QApplicationPrivate *ap = QApplicationPrivate::instance();
+ ap->setMaxWindowRect(screen, screenNo, rect);
+}
+
+void QApplicationPrivate::setMaxWindowRect(const QScreen *screen, int screenNo,
+ const QRect &rect)
+{
+ if (maxWindowRects.value(screen) == rect)
+ return;
+
+ maxWindowRects[screen] = rect;
+
+ // Re-resize any maximized windows
+ QWidgetList l = QApplication::topLevelWidgets();
+ for (int i = 0; i < l.size(); ++i) {
+ QWidget *w = l.at(i);
+ QScreen *s = w->d_func()->getScreen();
+ if (w->isMaximized() && s == screen)
+ w->d_func()->setMaxWindowState_helper();
+ }
+
+ if ( qt_desktopWidget ) // XXX workaround crash
+ emit QApplication::desktop()->workAreaResized(screenNo);
+}
+
+#ifndef QT_NO_QWS_DYNAMICSCREENTRANSFORMATION
+
+typedef void (*TransformFunc)(QScreen *, int);
+#ifndef QT_NO_QWS_TRANSFORMED
+extern "C" void qws_setScreenTransformation(QScreen *, int);
+#endif
+static TransformFunc getTransformationFunction()
+{
+ static TransformFunc func = 0;
+
+ if (!func) {
+#ifdef QT_NO_QWS_TRANSFORMED
+# ifndef QT_NO_LIBRARY
+ // symbol is not built into the library, search for the plugin
+ const QStringList paths = QApplication::libraryPaths();
+ foreach (const QString &path, paths) {
+ const QString file = path + QLatin1String("/gfxdrivers/libqgfxtransformed");
+ func = (TransformFunc)QLibrary::resolve(file,
+ "qws_setScreenTransformation");
+ if (func)
+ break;
+ }
+# endif
+#else
+ func = qws_setScreenTransformation;
+#endif
+ if (!func)
+ func = (TransformFunc)-1;
+ }
+
+ if (func == (TransformFunc)-1)
+ return 0;
+
+ return func;
+}
+
+static void setScreenTransformation(int screenNo, int transformation)
+{
+ QScreen *screen = QScreen::instance();
+ const QList<QScreen*> subScreens = screen->subScreens();
+
+ if (screenNo == -1)
+ screenNo = 0;
+
+ if (screenNo == -1 && !subScreens.isEmpty())
+ screenNo = 0;
+
+ if (subScreens.isEmpty() && screenNo == 0) {
+ // nothing
+ } else if (screenNo < 0 || screenNo >= subScreens.size()) {
+ qWarning("setScreenTransformation: invalid screen %i", screenNo);
+ return;
+ }
+
+ if (screenNo < subScreens.size())
+ screen = subScreens.at(screenNo);
+
+ QApplicationPrivate *ap = QApplicationPrivate::instance();
+ ap->setScreenTransformation(screen, screenNo, transformation);
+}
+
+void QApplicationPrivate::setScreenTransformation(QScreen *screen,
+ int screenNo,
+ int transformation)
+{
+ QScreen *transformed = screen;
+
+ while (transformed->classId() == QScreen::ProxyClass)
+ transformed = static_cast<QProxyScreen*>(transformed)->screen();
+
+ if (transformed->classId() != QScreen::TransformedClass)
+ return;
+
+ TransformFunc setScreenTransformation = getTransformationFunction();
+ if (!setScreenTransformation)
+ return;
+
+ setScreenTransformation(transformed, transformation);
+
+ // need to re-configure() proxies bottom-up
+ if (screen->classId() == QScreen::ProxyClass) {
+ QList<QProxyScreen*> proxies;
+ QScreen *s = screen;
+
+ do {
+ QProxyScreen *proxy = static_cast<QProxyScreen*>(s);
+ proxies.append(proxy);
+ s = proxy->screen();
+ } while (s->classId() == QScreen::ProxyClass);
+
+ do {
+ QProxyScreen *proxy = proxies.takeLast();
+ proxy->setScreen(proxy->screen()); // triggers configure()
+ } while (!proxies.isEmpty());
+ }
+
+ if (qt_desktopWidget) { // XXX workaround crash for early screen transform events
+ QDesktopWidget *desktop = QApplication::desktop();
+
+ emit desktop->resized(screenNo);
+ if (maxWindowRect(screen).isEmpty()) // not explicitly set
+ emit desktop->workAreaResized(screenNo);
+ }
+
+ QWSServer *server = QWSServer::instance();
+ if (server) {
+ server->updateWindowRegions();
+ QRegion r = screen->region();
+ server->refresh(r);
+ }
+
+ // make sure maximized and fullscreen windows are updated
+ QWidgetList list = QApplication::topLevelWidgets();
+ for (int i = list.size() - 1; i >= 0; --i) {
+ QWidget *w = list.at(i);
+ if (w->isFullScreen())
+ w->d_func()->setFullScreenSize_helper();
+ else if (w->isMaximized())
+ w->d_func()->setMaxWindowState_helper();
+ }
+}
+
+#endif // QT_NO_QWS_DYNAMICSCREENTRANSFORMATION
+
+/*****************************************************************************
+ Internal variables and functions
+ *****************************************************************************/
+
+
+static QString appName; // application name
+static const char *appFont = 0; // application font
+static const char *appBGCol = 0; // application bg color
+static const char *appFGCol = 0; // application fg color
+static const char *appBTNCol = 0; // application btn color
+static const char *mwGeometry = 0; // main widget geometry
+static const char *mwTitle = 0; // main widget title
+//static bool mwIconic = false; // main widget iconified
+
+static bool app_do_modal = false; // modal mode
+Q_GUI_EXPORT QWSDisplay *qt_fbdpy = 0; // QWS `display'
+QLock *QWSDisplay::lock = 0;
+
+static int mouseButtonPressed = 0; // last mouse button pressed
+static int mouseButtonPressTime = 0; // when was a button pressed
+static short mouseXPos, mouseYPos; // mouse position in act window
+
+extern QWidgetList *qt_modal_stack; // stack of modal widgets
+
+static QWidget *popupButtonFocus = 0;
+static QWidget *popupOfPopupButtonFocus = 0;
+static bool popupCloseDownMode = false;
+static bool popupGrabOk;
+static QPointer<QWidget> *mouseInWidget = 0;
+QPointer<QWidget> qt_last_mouse_receiver = 0;
+
+static bool sm_blockUserInput = false; // session management
+
+QWidget *qt_button_down = 0; // widget got last button-down
+WId qt_last_cursor = 0xffffffff; // Was -1, but WIds are unsigned
+
+class QWSMouseEvent;
+class QWSKeyEvent;
+
+class QETWidget : public QWidget // event translator widget
+{
+public:
+ bool translateMouseEvent(const QWSMouseEvent *, int oldstate);
+ bool translateKeyEvent(const QWSKeyEvent *, bool grab);
+ bool translateRegionEvent(const QWSRegionEvent *);
+#ifndef QT_NO_QWSEMBEDWIDGET
+ void translateEmbedEvent(const QWSEmbedEvent *event);
+#endif
+ bool translateWheelEvent(const QWSMouseEvent *me);
+ void repaintDecoration(QRegion r, bool post);
+ void updateRegion();
+
+ bool raiseOnClick()
+ {
+ // With limited windowmanagement/taskbar/etc., raising big windows
+ // (eg. spreadsheet) over the top of everything else (eg. calculator)
+ // is just annoying.
+ return !isMaximized() && !isFullScreen();
+ }
+};
+
+void QApplicationPrivate::createEventDispatcher()
+{
+ Q_Q(QApplication);
+#if !defined(QT_NO_GLIB)
+ if (qgetenv("QT_NO_GLIB").isEmpty() && QEventDispatcherGlib::versionSupported())
+ eventDispatcher = (q->type() != QApplication::Tty
+ ? new QWSEventDispatcherGlib(q)
+ : new QEventDispatcherGlib(q));
+ else
+#endif
+ eventDispatcher = (q->type() != QApplication::Tty
+ ? new QEventDispatcherQWS(q)
+ : new QEventDispatcherUNIX(q));
+}
+
+// Single-process stuff. This should maybe move into qwindowsystem_qws.cpp
+
+static bool qws_single_process;
+static QList<QWSEvent*> incoming;
+static QList<QWSCommand*> outgoing;
+
+void qt_client_enqueue(const QWSEvent *event)
+{
+ QWSEvent *copy = QWSEvent::factory(event->type);
+ copy->copyFrom(event);
+ incoming.append(copy);
+}
+
+QList<QWSCommand*> *qt_get_server_queue()
+{
+ return &outgoing;
+}
+
+void qt_server_enqueue(const QWSCommand *command)
+{
+ QWSCommand *copy = QWSCommand::factory(command->type);
+ QT_TRY {
+ copy->copyFrom(command);
+ outgoing.append(copy);
+ } QT_CATCH(...) {
+ delete copy;
+ QT_RETHROW;
+ }
+}
+
+QWSDisplay::Data::Data(QObject* parent, bool singleProcess)
+{
+#ifdef QT_NO_QWS_MULTIPROCESS
+ Q_UNUSED(parent);
+ Q_UNUSED(singleProcess);
+#else
+ if (singleProcess)
+ csocket = 0;
+ else {
+ csocket = new QWSSocket(parent);
+ QObject::connect(csocket, SIGNAL(disconnected()),
+ qApp, SLOT(quit()));
+ }
+ clientLock = 0;
+#endif
+ init();
+}
+
+QWSDisplay::Data::~Data()
+{
+// delete rgnMan; rgnMan = 0;
+// delete memorymanager; memorymanager = 0;
+ qt_screen->disconnect();
+ delete qt_screen; qt_screen = 0;
+#ifndef QT_NO_QWS_CURSOR
+ delete qt_screencursor; qt_screencursor = 0;
+#endif
+#ifndef QT_NO_QWS_MULTIPROCESS
+ shm.detach();
+ if (csocket) {
+ QWSCommand shutdownCmd(QWSCommand::Shutdown, 0, 0);
+ shutdownCmd.write(csocket);
+ csocket->flush(); // may be pending QCop message, eg.
+ delete csocket;
+ }
+ delete clientLock;
+ clientLock = 0;
+#endif
+ delete connected_event;
+ delete mouse_event;
+ delete current_event;
+ qDeleteAll(queue);
+#ifndef QT_NO_COP
+ delete qcop_response;
+#endif
+}
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+bool QWSDisplay::Data::lockClient(QWSLock::LockType type, int timeout)
+{
+ return !clientLock || clientLock->lock(type, timeout);
+}
+
+void QWSDisplay::Data::unlockClient(QWSLock::LockType type)
+{
+ if (clientLock) clientLock->unlock(type);
+}
+
+bool QWSDisplay::Data::waitClient(QWSLock::LockType type, int timeout)
+{
+ return !clientLock || clientLock->wait(type, timeout);
+}
+
+QWSLock* QWSDisplay::Data::getClientLock()
+{
+ return clientLock;
+}
+#endif // QT_NO_QWS_MULTIPROCESS
+
+void QWSDisplay::Data::flush()
+{
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket) {
+ csocket->waitForReadyRead(0);
+ csocket->flush();
+ }
+#endif
+}
+
+#if 0
+void QWSDisplay::Data::debugQueue() {
+ for (int i = 0; i < queue.size(); ++i) {
+ QWSEvent *e = queue.at(i);
+ qDebug( " ev %d type %d sl %d rl %d", i, e->type, e->simpleLen, e->rawLen);
+ }
+}
+#endif
+
+bool QWSDisplay::Data::queueNotEmpty()
+{
+ return mouse_event/*||region_event*/||queue.count() > 0;
+}
+QWSEvent* QWSDisplay::Data::dequeue()
+{
+ QWSEvent *r=0;
+ if (queue.count()) {
+ r = queue.first();
+ queue.removeFirst();
+ if (r->type == QWSEvent::Region)
+ region_events_count--;
+ } else if (mouse_event) {
+ r = mouse_event;
+ mouse_event = 0;
+#ifdef QAPPLICATION_EXTRA_DEBUG
+ mouse_event_count = 0;
+#endif
+ }
+ return r;
+}
+
+QWSEvent* QWSDisplay::Data::peek()
+{
+ return queue.first();
+}
+
+bool QWSDisplay::Data::directServerConnection()
+{
+#ifndef QT_NO_QWS_MULTIPROCESS
+ return csocket == 0;
+#else
+ return true;
+#endif
+}
+
+void QWSDisplay::Data::create(int n)
+{
+ QWSCreateCommand cmd(n);
+ sendCommand(cmd);
+}
+
+void QWSDisplay::Data::flushCommands()
+{
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket)
+ csocket->flush();
+#endif
+}
+
+void QWSDisplay::Data::sendCommand(QWSCommand & cmd)
+{
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket)
+ cmd.write(csocket);
+ else
+#endif
+ qt_server_enqueue(&cmd);
+}
+
+void QWSDisplay::Data::sendSynchronousCommand(QWSCommand & cmd)
+{
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket) {
+ lockClient(QWSLock::Communication);
+ cmd.write(csocket);
+ bool ok = true;
+ while (csocket->bytesToWrite() > 0) {
+ if (!csocket->waitForBytesWritten(-1)) {
+ qCritical("QWSDisplay::Data::sendSynchronousCommand: %s",
+ qPrintable(csocket->errorString()));
+ ok = false;
+ break;
+ }
+ }
+ if (ok)
+ waitClient(QWSLock::Communication);
+ } else
+#endif
+ qt_server_enqueue(&cmd);
+}
+
+int QWSDisplay::Data::takeId()
+{
+ int unusedIdCount = unused_identifiers.count();
+ if (unusedIdCount <= 10)
+ create(15);
+ if (unusedIdCount == 0) {
+ create(1); // Make sure we have an incoming id to wait for, just in case we're recursive
+ waitForCreation();
+ }
+
+ return unused_identifiers.takeFirst();
+}
+
+void QWSDisplay::Data::setMouseFilter(void (*filter)(QWSMouseEvent*))
+{
+ mouseFilter = filter;
+}
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+
+QWSLock* QWSDisplay::Data::clientLock = 0;
+
+void Q_GUI_EXPORT qt_app_reinit( const QString& newAppName )
+{
+ qt_fbdpy->d->reinit( newAppName );
+}
+
+#endif // QT_NO_QWS_MULTIPROCESS
+
+class QDesktopWidget;
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+void QWSDisplay::Data::reinit( const QString& newAppName )
+{
+ Q_ASSERT(csocket);
+
+ delete connected_event;
+ connected_event = 0;
+ region_events_count = 0;
+// region_ack = 0;
+ delete mouse_event;
+ mouse_event = 0;
+// region_event = 0;
+ region_offset_window = 0;
+#ifndef QT_NO_COP
+ delete qcop_response;
+ qcop_response = 0;
+#endif
+ delete current_event;
+ current_event = 0;
+#ifdef QAPPLICATION_EXTRA_DEBUG
+ mouse_event_count = 0;
+#endif
+ mouseFilter = 0;
+
+ qt_desktopWidget = 0;
+ delete QWSDisplay::Data::clientLock;
+ QWSDisplay::Data::clientLock = 0;
+
+ QString pipe = qws_qtePipeFilename();
+
+ // QWS client
+ // Cleanup all cached ids
+ unused_identifiers.clear();
+ delete csocket;
+
+ appName = newAppName;
+ qApp->setObjectName( appName );
+
+ csocket = new QWSSocket();
+ QObject::connect(csocket, SIGNAL(disconnected()),
+ qApp, SLOT(quit()));
+ csocket->connectToLocalFile(pipe);
+
+ QWSDisplay::Data::clientLock = new QWSLock();
+
+ QWSIdentifyCommand cmd;
+ cmd.setId(appName, QWSDisplay::Data::clientLock->id());
+
+#ifndef QT_NO_SXE
+ QTransportAuth *a = QTransportAuth::getInstance();
+ QTransportAuth::Data *d = a->connectTransport(
+ QTransportAuth::UnixStreamSock |
+ QTransportAuth::Trusted,
+ csocket->socketDescriptor());
+ QAuthDevice *ad = a->authBuf( d, csocket );
+ ad->setClient( csocket );
+
+ cmd.write(ad);
+#else
+ cmd.write(csocket);
+#endif
+
+ // wait for connect confirmation
+ waitForConnection();
+
+ qws_client_id = connected_event->simpleData.clientId;
+
+ if (!QWSDisplay::initLock(pipe, false))
+ qFatal("Cannot get display lock");
+
+ if (shm.attach(connected_event->simpleData.servershmid)) {
+ sharedRam = static_cast<uchar *>(shm.address());
+ QScreen *s = qt_get_screen(qws_display_id, qws_display_spec.constData());
+ if (s)
+ sharedRamSize += s->memoryNeeded(QLatin1String(qws_display_spec.constData()));
+ } else {
+ perror("QWSDisplay::Data::init");
+ qFatal("Client can't attach to main ram memory.");
+ }
+
+ qApp->desktop();
+
+ // We wait for creation mainly so that we can process important
+ // initialization events such as MaxWindowRect that are sent
+ // before object id creation. Waiting here avoids later window
+ // resizing since we have the MWR before windows are displayed.
+ waitForCreation();
+
+ sharedRamSize -= sizeof(int);
+ qt_last_x = reinterpret_cast<int *>(sharedRam + sharedRamSize);
+ sharedRamSize -= sizeof(int);
+ qt_last_y = reinterpret_cast<int *>(sharedRam + sharedRamSize);
+
+#ifndef QT_NO_COP
+ QCopChannel::reregisterAll();
+#endif
+ csocket->flush();
+}
+#endif
+
+void QWSDisplay::Data::init()
+{
+ connected_event = 0;
+ region_events_count = 0;
+// region_ack = 0;
+ mouse_event = 0;
+ mouse_state = -1;
+ mouse_winid = 0;
+// region_event = 0;
+ region_offset_window = 0;
+#ifndef QT_NO_COP
+ qcop_response = 0;
+#endif
+ current_event = 0;
+#ifdef QAPPLICATION_EXTRA_DEBUG
+ mouse_event_count = 0;
+#endif
+ mouseFilter = 0;
+
+ QString pipe = qws_qtePipeFilename();
+
+ sharedRamSize = qwsSharedRamSize;
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket) {
+ // QWS client
+
+ connectToPipe();
+
+ QWSDisplay::Data::clientLock = new QWSLock();
+
+ QWSIdentifyCommand cmd;
+ cmd.setId(appName, QWSDisplay::Data::clientLock->id());
+#ifndef QT_NO_SXE
+ QTransportAuth *a = QTransportAuth::getInstance();
+ QTransportAuth::Data *d = a->connectTransport(
+ QTransportAuth::UnixStreamSock |
+ QTransportAuth::Trusted,
+ csocket->socketDescriptor());
+ QAuthDevice *ad = a->authBuf( d, csocket );
+ ad->setClient( csocket );
+ cmd.write(ad);
+#else
+ cmd.write(csocket);
+#endif
+
+ // create(30); // not necessary, server will send ids anyway
+ waitForConnection();
+
+ qws_client_id = connected_event->simpleData.clientId;
+
+ // now we want to get the exact display spec to use if we haven't
+ // specified anything.
+ if (qws_display_spec.at(0) == ':')
+ qws_display_spec = connected_event->display;
+
+ if (!QWSDisplay::initLock(pipe, false))
+ qFatal("Cannot get display lock");
+
+ if (shm.attach(connected_event->simpleData.servershmid)) {
+ sharedRam = static_cast<uchar *>(shm.address());
+ QScreen *s = qt_get_screen(qws_display_id, qws_display_spec.constData());
+ if (s)
+ sharedRamSize += s->memoryNeeded(QLatin1String(qws_display_spec.constData()));
+ } else {
+ perror("QWSDisplay::Data::init");
+ qFatal("Client can't attach to main ram memory.");
+ }
+
+ // We wait for creation mainly so that we can process important
+ // initialization events such as MaxWindowRect that are sent
+ // before object id creation. Waiting here avoids later window
+ // resizing since we have the MWR before windows are displayed.
+ waitForCreation();
+ } else
+#endif
+ {
+ create(30);
+
+ // QWS server
+ if (!QWSDisplay::initLock(pipe, true))
+ qFatal("Cannot get display lock");
+
+ QScreen *s = qt_get_screen(qws_display_id, qws_display_spec.constData());
+ if (s)
+ sharedRamSize += s->memoryNeeded(QLatin1String(qws_display_spec.constData()));
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+
+ if (!shm.create(sharedRamSize)) {
+ perror("Cannot create main ram shared memory\n");
+ qFatal("Unable to allocate %d bytes of shared memory", sharedRamSize);
+ }
+ qt_servershmid = shm.id();
+ sharedRam = static_cast<uchar *>(shm.address());
+#else
+ sharedRam=static_cast<uchar *>(malloc(sharedRamSize));
+#endif
+ // Need to zero index count at end of block, might as well zero
+ // the rest too
+ memset(sharedRam,0,sharedRamSize);
+
+ QWSIdentifyCommand cmd;
+ cmd.setId(appName, -1);
+ qt_server_enqueue(&cmd);
+ }
+
+ // Allow some memory for the graphics driver too
+ //### Note that sharedRamSize() has side effects; it must be called
+ //### once, and only once, and before initDevice()
+ sharedRamSize -= qt_screen->sharedRamSize(sharedRam+sharedRamSize);
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if(!csocket)
+#endif
+ {
+ //QWS server process
+ if (!qt_screen->initDevice())
+ qFatal("Unable to initialize screen driver!");
+ }
+
+ sharedRamSize -= sizeof(int);
+ qt_last_x = reinterpret_cast<int *>(sharedRam + sharedRamSize);
+ sharedRamSize -= sizeof(int);
+ qt_last_y = reinterpret_cast<int *>(sharedRam + sharedRamSize);
+
+ /* Initialise framebuffer memory manager */
+ /* Add 4k for luck and to avoid clobbering hardware cursor */
+// int screensize=qt_screen->screenSize();
+// memorymanager=new QMemoryManager(qt_screen->base()+screensize+4096,
+// qt_screen->totalSize()-(screensize+4096),0);
+
+// #ifndef QT_NO_QWS_MULTIPROCESS
+// rgnMan = new QWSRegionManager(pipe, csocket);
+// #else
+// rgnMan = new QWSRegionManager(pipe, 0); //####### not necessary
+// #endif
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket)
+ csocket->flush();
+#endif
+}
+
+
+QWSEvent* QWSDisplay::Data::readMore()
+{
+#ifdef QT_NO_QWS_MULTIPROCESS
+ return incoming.isEmpty() ? 0 : incoming.takeFirst();
+#else
+ if (!csocket)
+ return incoming.isEmpty() ? 0 : incoming.takeFirst();
+ // read next event
+ if (!current_event) {
+ int event_type = qws_read_uint(csocket);
+
+ if (event_type >= 0) {
+ current_event = QWSEvent::factory(event_type);
+ }
+ }
+
+ if (current_event) {
+ if (current_event->read(csocket)) {
+ // Finished reading a whole event.
+ QWSEvent* result = current_event;
+ current_event = 0;
+ return result;
+ }
+ }
+
+ // Not finished reading a whole event.
+ return 0;
+#endif
+}
+
+void QWSDisplay::Data::fillQueue()
+{
+ QWSServer::processEventQueue();
+ QWSEvent *e = readMore();
+#ifndef QT_NO_QWS_MULTIPROCESS
+ int bytesAvailable = csocket ? csocket->bytesAvailable() : 0;
+ int bytesRead = 0;
+#endif
+ while (e) {
+#ifndef QT_NO_QWS_MULTIPROCESS
+ bytesRead += QWS_PROTOCOL_ITEM_SIZE((*e));
+#endif
+ if (e->type == QWSEvent::Connected) {
+ connected_event = static_cast<QWSConnectedEvent *>(e);
+ return;
+ } else if (e->type == QWSEvent::Creation) {
+ QWSCreationEvent *ce = static_cast<QWSCreationEvent*>(e);
+ int id = ce->simpleData.objectid;
+ int count = ce->simpleData.count;
+ for (int i = 0; i < count; ++i)
+ unused_identifiers.append(id++);
+ delete e;
+ } else if (e->type == QWSEvent::Mouse) {
+ if (!qt_screen) {
+ delete e;
+ } else {
+ QWSMouseEvent *me = static_cast<QWSMouseEvent*>(e);
+ if (mouseFilter)
+ mouseFilter(me);
+#ifdef QAPPLICATION_EXTRA_DEBUG
+ static const char *defaultAction= "INITIAL";
+ const char * action = defaultAction;
+#endif
+ delete mouse_event;
+ if (mouse_winid != me->window ()
+ || mouse_state != me->simpleData.state) {
+ queue.append(me);
+ mouse_winid = me->window();
+ mouse_state = me->simpleData.state;
+ mouse_event = 0;
+#ifdef QAPPLICATION_EXTRA_DEBUG
+ mouse_event_count = 0;
+ action = "ENQUEUE";
+#endif
+ } else {
+#ifdef QAPPLICATION_EXTRA_DEBUG
+ if (mouse_event)
+ action = "COMPRESS";
+ mouse_event_count++;
+#endif
+ mouse_event = me;
+ }
+#ifdef QAPPLICATION_EXTRA_DEBUG
+ if (me->simpleData.state !=0 || action != defaultAction || mouse_event_count != 0)
+ qDebug("fillQueue %s (%d,%d), state %x win %d count %d", action,
+ me->simpleData.x_root, me->simpleData.y_root, me->simpleData.state,
+ me->window(), mouse_event_count);
+#endif
+ }
+#ifndef QT_NO_QWS_MULTIPROCESS
+ } else if (e->type == QWSEvent::Region && clientLock) {
+ // not really an unlock, decrements the semaphore
+ region_events_count++;
+ clientLock->unlock(QWSLock::RegionEvent);
+ queue.append(e);
+#endif
+#ifndef QT_NO_QWS_PROPERTIES
+ } else if (e->type == QWSEvent::PropertyReply) {
+ QWSPropertyReplyEvent *pe = static_cast<QWSPropertyReplyEvent*>(e);
+ int len = pe->simpleData.len;
+ char *data;
+ if (len <= 0) {
+ data = 0;
+ } else {
+ data = new char[len];
+ memcpy(data, pe->data, len) ;
+ }
+ QPaintDevice::qwsDisplay()->getPropertyLen = len;
+ QPaintDevice::qwsDisplay()->getPropertyData = data;
+ delete e;
+#endif // QT_NO_QWS_PROPERTIES
+ } else if (e->type==QWSEvent::MaxWindowRect && qt_screen) {
+ // Process this ASAP, in case new widgets are created (startup)
+ setMaxWindowRect((static_cast<QWSMaxWindowRectEvent*>(e))->simpleData.rect);
+ delete e;
+#ifndef QT_NO_QWS_DYNAMICSCREENTRANSFORMATION
+ } else if (e->type == QWSEvent::ScreenTransformation) {
+ QWSScreenTransformationEvent *pe = static_cast<QWSScreenTransformationEvent*>(e);
+ setScreenTransformation(pe->simpleData.screen,
+ pe->simpleData.transformation);
+ delete e;
+#endif
+#ifndef QT_NO_COP
+ } else if (e->type == QWSEvent::QCopMessage) {
+ QWSQCopMessageEvent *pe = static_cast<QWSQCopMessageEvent*>(e);
+ if (pe->simpleData.is_response) {
+ qcop_response = pe;
+ } else {
+ queue.append(e);
+ }
+#endif
+ } else {
+ queue.append(e);
+ }
+ //debugQueue();
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket && bytesRead >= bytesAvailable)
+ break;
+#endif
+ e = readMore();
+ }
+}
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+
+static int qws_connection_timeout = 5;
+
+void QWSDisplay::Data::connectToPipe()
+{
+ Q_ASSERT(csocket);
+
+ int timeout = qgetenv("QWS_CONNECTION_TIMEOUT").toInt();
+ if (timeout)
+ qws_connection_timeout = timeout;
+
+ const QString pipe = qws_qtePipeFilename();
+ int i = 0;
+ while (!csocket->connectToLocalFile(pipe)) {
+ if (++i > qws_connection_timeout) {
+ qWarning("No Qt for Embedded Linux server appears to be running.");
+ qWarning("If you want to run this program as a server,");
+ qWarning("add the \"-qws\" command-line option.");
+ exit(1);
+ }
+ sleep(1);
+ }
+}
+
+void QWSDisplay::Data::waitForConnection()
+{
+ connected_event = 0;
+
+ for (int i = 0; i < qws_connection_timeout; i++) {
+ fillQueue();
+ if (connected_event)
+ return;
+ csocket->flush();
+ csocket->waitForReadyRead(1000);
+ }
+
+ csocket->flush();
+ if (!connected_event)
+ qFatal("Did not receive a connection event from the qws server");
+}
+
+void QWSDisplay::Data::waitForRegionAck(int winId)
+{
+ QWSEvent *ack = 0;
+
+ if (csocket) { // GuiClient
+ int i = 0;
+ while (!ack) {
+ fillQueue();
+
+ while (i < queue.size()) {
+ QWSEvent *e = queue.at(i);
+ if (e->type == QWSEvent::Region && e->window() == winId) {
+ ack = e;
+ queue.removeAt(i);
+ break;
+ }
+ ++i;
+ }
+
+ if (!ack) {
+ csocket->flush();
+ csocket->waitForReadyRead(1000);
+ }
+ }
+ } else { // GuiServer
+ fillQueue();
+ for (int i = 0; i < queue.size(); /* nothing */) {
+ QWSEvent *e = queue.at(i);
+ if (e->type == QWSEvent::Region && e->window() == winId) {
+ ack = e;
+ queue.removeAt(i);
+ break;
+ }
+ ++i;
+ }
+ if (!ack) // already processed
+ return;
+ }
+
+ Q_ASSERT(ack);
+
+ qApp->qwsProcessEvent(ack);
+ delete ack;
+ region_events_count--;
+}
+
+void QWSDisplay::Data::waitForRegionEvents(int winId, bool ungrabDisplay)
+{
+ if (!clientLock)
+ return;
+
+ int removedEventsCount = 0;
+
+ // fill queue with unreceived region events
+ if (!clientLock->hasLock(QWSLock::RegionEvent)) {
+ bool ungrabbed = false;
+ if (ungrabDisplay && QWSDisplay::grabbed()) {
+ QWSDisplay::ungrab();
+ ungrabbed = true;
+ }
+
+ for (;;) {
+ fillQueue();
+ if (clientLock->hasLock(QWSLock::RegionEvent))
+ break;
+ csocket->flush();
+ csocket->waitForReadyRead(1000);
+ }
+
+ if (ungrabbed)
+ QWSDisplay::grab(true);
+ }
+
+ // check the queue for pending region events
+ QWSEvent *regionEvent = 0;
+ for (int i = 0; i < queue.size(); /* nothing */) {
+ QWSEvent *e = queue.at(i);
+ if (e->type == QWSEvent::Region && e->window() == winId) {
+ QWSRegionEvent *re = static_cast<QWSRegionEvent*>(e);
+ if (re->simpleData.type == QWSRegionEvent::Allocation) {
+ delete regionEvent;
+ regionEvent = re;
+ }
+ queue.removeAt(i);
+ removedEventsCount++;
+ } else {
+ ++i;
+ }
+ }
+
+ if (regionEvent) {
+ qApp->qwsProcessEvent(regionEvent);
+ delete regionEvent;
+ }
+ region_events_count -= removedEventsCount;
+}
+
+bool QWSDisplay::Data::hasPendingRegionEvents() const
+{
+ if (clientLock && !clientLock->hasLock(QWSLock::RegionEvent))
+ return true;
+
+ return region_events_count > 0;
+}
+
+#endif // QT_NO_QWS_MULTIPROCESS
+
+void QWSDisplay::Data::waitForCreation()
+{
+ fillQueue();
+#ifndef QT_NO_QWS_MULTIPROCESS
+ while (unused_identifiers.count() == 0) {
+ if (csocket) {
+ csocket->flush();
+ csocket->waitForReadyRead(1000);
+ }
+ fillQueue();
+ }
+#endif
+}
+
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+void QWSDisplay::Data::waitForPropertyReply()
+{
+ if (!csocket)
+ return;
+ fillQueue();
+ while (qt_fbdpy->getPropertyLen == -2) {
+ csocket->flush();
+ csocket->waitForReadyRead(1000);
+ fillQueue();
+ }
+}
+#endif
+
+#ifndef QT_NO_COP
+void QWSDisplay::Data::waitForQCopResponse()
+{
+ for (;;) {
+ fillQueue();
+ if (qcop_response)
+ break;
+#ifndef QT_NO_QWS_MULTIPROCESS
+ if (csocket) {
+ csocket->flush();
+ csocket->waitForReadyRead(1000);
+ }
+#endif
+ }
+ queue.prepend(qcop_response);
+ qcop_response = 0;
+}
+#endif
+
+/*!
+ \class QWSDisplay
+ \brief The QWSDisplay class provides a display for QWS; it is an internal class.
+
+ \internal
+
+ \ingroup qws
+*/
+
+QWSDisplay::QWSDisplay()
+{
+ d = new Data(0, qws_single_process);
+}
+
+QWSDisplay::~QWSDisplay()
+{
+ delete d;
+ delete lock;
+ lock = 0;
+}
+
+bool QWSDisplay::grabbed()
+{
+ return lock->locked();
+}
+
+void QWSDisplay::grab()
+{
+ lock->lock(QLock::Read);
+}
+
+void QWSDisplay::grab(bool write)
+{
+ lock->lock(write ? QLock::Write : QLock::Read);
+
+}
+void QWSDisplay::ungrab()
+{
+ lock->unlock();
+}
+
+#if 0
+QWSRegionManager *QWSDisplay::regionManager() const
+{
+ return d->rgnMan;
+}
+#endif
+
+bool QWSDisplay::eventPending() const
+{
+#ifndef QT_NO_QWS_MULTIPROCESS
+ d->flush();
+#endif
+ d->fillQueue();
+ return d->queueNotEmpty();
+}
+
+
+/*
+ Caller must delete return value!
+ */
+QWSEvent *QWSDisplay::getEvent()
+{
+ d->fillQueue();
+ Q_ASSERT(d->queueNotEmpty());
+ QWSEvent* e = d->dequeue();
+
+ return e;
+}
+
+uchar* QWSDisplay::frameBuffer() const { return qt_screen->base(); }
+int QWSDisplay::width() const { return qt_screen->width(); }
+int QWSDisplay::height() const { return qt_screen->height(); }
+int QWSDisplay::depth() const { return qt_screen->depth(); }
+int QWSDisplay::pixmapDepth() const { return qt_screen->pixmapDepth(); }
+bool QWSDisplay::supportsDepth(int depth) const { return qt_screen->supportsDepth(depth); }
+uchar *QWSDisplay::sharedRam() const { return d->sharedRam; }
+int QWSDisplay::sharedRamSize() const { return d->sharedRamSize; }
+
+#ifndef QT_NO_QWS_PROPERTIES
+
+void QWSDisplay::addProperty(int winId, int property)
+{
+ QWSAddPropertyCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.property = property;
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::setProperty(int winId, int property, int mode, const QByteArray &data)
+{
+ QWSSetPropertyCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.property = property;
+ cmd.simpleData.mode = mode;
+ cmd.setData(data.constData(), data.size());
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::setProperty(int winId, int property, int mode,
+ const char * data)
+{
+ QWSSetPropertyCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.property = property;
+ cmd.simpleData.mode = mode;
+ cmd.setData(data, strlen(data));
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::removeProperty(int winId, int property)
+{
+ QWSRemovePropertyCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.property = property;
+ d->sendCommand(cmd);
+}
+
+/*
+ It is the caller's responsibility to delete[] \a data.
+ */
+bool QWSDisplay::getProperty(int winId, int property, char *&data, int &len)
+{
+ if (d->directServerConnection()) {
+ const char *propertyData;
+ bool retval = qwsServer->d_func()->get_property(winId, property, propertyData, len);
+ if (len <= 0) {
+ data = 0;
+ } else {
+ data = new char[len];
+ memcpy(data, propertyData, len) ;
+ }
+ return retval;
+ }
+ QWSGetPropertyCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.property = property;
+ d->sendCommand(cmd);
+
+ getPropertyLen = -2;
+ getPropertyData = 0;
+
+#ifndef QT_NO_QWS_MULTIPROCESS
+ d->waitForPropertyReply();
+#endif
+
+ len = getPropertyLen;
+ data = getPropertyData;
+
+ getPropertyLen = -2;
+ getPropertyData = 0;
+
+ return len != -1;
+}
+
+#endif // QT_NO_QWS_PROPERTIES
+
+void QWSDisplay::setAltitude(int winId, int alt, bool fixed)
+{
+ QWSChangeAltitudeCommand cmd;
+#ifdef QT_DEBUG
+ memset(cmd.simpleDataPtr, 0, sizeof(cmd.simpleData)); //shut up Valgrind
+#endif
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.altitude = QWSChangeAltitudeCommand::Altitude(alt);
+ cmd.simpleData.fixed = fixed;
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->set_altitude(&cmd);
+ } else {
+ d->sendSynchronousCommand(cmd);
+ }
+}
+
+void QWSDisplay::setOpacity(int winId, int opacity)
+{
+ QWSSetOpacityCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.opacity = opacity;
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->set_opacity(&cmd);
+ } else {
+ d->sendCommand(cmd);
+ }
+}
+
+
+
+void QWSDisplay::requestFocus(int winId, bool get)
+{
+ QWSRequestFocusCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.flag = get;
+ if (d->directServerConnection())
+ qwsServer->d_func()->request_focus(&cmd);
+ else
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::setIdentity(const QString &appName)
+{
+ QWSIdentifyCommand cmd;
+#ifdef QT_NO_QWS_MULTIPROCESS
+ const int id = -1;
+#else
+ const int id = QWSDisplay::Data::clientLock ? QWSDisplay::Data::clientLock->id() : -1;
+#endif
+ cmd.setId(appName, id);
+ if (d->directServerConnection())
+ qwsServer->d_func()->set_identity(&cmd);
+ else
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::nameRegion(int winId, const QString& n, const QString &c)
+{
+ QWSRegionNameCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.setName(n, c);
+ if (d->directServerConnection())
+ qwsServer->d_func()->name_region(&cmd);
+ else
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::requestRegion(int winId, const QString &surfaceKey,
+ const QByteArray &surfaceData,
+ const QRegion &region)
+{
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->request_region(winId, surfaceKey,
+ surfaceData, region);
+ } else {
+ QWSRegionCommand cmd;
+ cmd.setData(winId, surfaceKey, surfaceData, region);
+ d->sendSynchronousCommand(cmd);
+ }
+}
+
+void QWSDisplay::repaintRegion(int winId, int windowFlags, bool opaque, QRegion r)
+{
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->repaint_region(winId, windowFlags, opaque, r);
+ } else {
+ QVector<QRect> ra = r.rects();
+
+ /*
+ for (int i = 0; i < ra.size(); i++) {
+ QRect r(ra[i]);
+ qDebug("rect: %d %d %d %d", r.x(), r.y(), r.right(), r.bottom());
+ }
+ */
+
+ QWSRepaintRegionCommand cmd;
+ /* XXX QWSRegionCommand is padded out in a compiler dependent way.
+ Zeroed out to avoid valgrind reporting uninitialized memory usage.
+ */
+#ifdef QT_DEBUG
+ memset(cmd.simpleDataPtr, 0, sizeof(cmd.simpleData)); //shut up Valgrind
+#endif
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.windowFlags = windowFlags;
+ cmd.simpleData.opaque = opaque;
+ cmd.simpleData.nrectangles = ra.count();
+ cmd.setData(reinterpret_cast<const char *>(ra.constData()),
+ ra.count() * sizeof(QRect), false);
+
+ d->sendSynchronousCommand(cmd);
+ }
+}
+
+
+void QWSDisplay::moveRegion(int winId, int dx, int dy)
+{
+ QWSRegionMoveCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.dx = dx;
+ cmd.simpleData.dy = dy;
+
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->move_region(&cmd);
+ } else {
+ d->sendSynchronousCommand(cmd);
+ }
+// d->offsetPendingExpose(winId, QPoint(cmd.simpleData.dx, cmd.simpleData.dy));
+}
+
+void QWSDisplay::destroyRegion(int winId)
+{
+ QWSRegionDestroyCommand cmd;
+ cmd.simpleData.windowid = winId;
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->destroy_region(&cmd);
+ } else {
+ d->sendCommand(cmd);
+ }
+}
+
+#ifndef QT_NO_QWS_INPUTMETHODS
+
+void QWSDisplay::sendIMUpdate(int type, int winId, int widgetid)
+{
+ QWSIMUpdateCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.widgetid = widgetid;
+
+ cmd.simpleData.type = type;
+
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->im_update(&cmd);
+ } else {
+ d->sendCommand(cmd);
+ }
+}
+
+void QWSDisplay::sendIMResponse(int winId, int property, const QVariant &result)
+{
+ QWSIMResponseCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.property = property;
+
+ cmd.setResult(result);
+
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->im_response(&cmd);
+ } else {
+ d->sendCommand(cmd);
+ }
+}
+
+void QWSDisplay::resetIM()
+{
+ sendIMUpdate(QWSInputMethod::Reset, -1, -1);
+}
+
+void QWSDisplay::sendIMMouseEvent(int index, bool isPress)
+{
+ QWSIMMouseCommand cmd;
+ cmd.simpleData.index = index;
+ cmd.simpleData.state = isPress ? QWSServer::MousePress : QWSServer::MouseRelease;
+ if (d->directServerConnection()) {
+ qwsServer->d_func()->send_im_mouse(&cmd);
+ } else {
+ d->sendCommand(cmd);
+ }
+}
+
+#endif
+
+int QWSDisplay::takeId()
+{
+ return d->takeId();
+}
+
+bool QWSDisplay::initLock(const QString &filename, bool create)
+{
+ if (!lock) {
+ lock = new QLock(filename, 'd', create);
+
+ if (!lock->isValid()) {
+ delete lock;
+ lock = 0;
+ return false;
+ }
+ }
+
+ return true;
+}
+
+void QWSDisplay::setSelectionOwner(int winId, const QTime &time)
+{
+ QWSSetSelectionOwnerCommand cmd;
+ cmd.simpleData.windowid = winId;
+ cmd.simpleData.hour = time.hour();
+ cmd.simpleData.minute = time.minute();
+ cmd.simpleData.sec = time.second();
+ cmd.simpleData.ms = time.msec();
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::convertSelection(int winId, int selectionProperty, const QString &mimeTypes)
+{
+#ifdef QT_NO_QWS_PROPERTIES
+ Q_UNUSED(mimeTypes);
+#else
+ // ### we need the atom/property thingy like in X here
+ addProperty(winId, QT_QWS_PROPERTY_CONVERTSELECTION);
+ setProperty(winId, QT_QWS_PROPERTY_CONVERTSELECTION,
+ int(QWSPropertyManager::PropReplace), mimeTypes.toLatin1());
+#endif
+ QWSConvertSelectionCommand cmd;
+ cmd.simpleData.requestor = winId;
+ cmd.simpleData.selection = selectionProperty;
+ cmd.simpleData.mimeTypes = QT_QWS_PROPERTY_CONVERTSELECTION;
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::defineCursor(int id, const QBitmap &curs, const QBitmap &mask,
+ int hotX, int hotY)
+{
+ const QImage cursImg = curs.toImage().convertToFormat(QImage::Format_MonoLSB);
+ const QImage maskImg = mask.toImage().convertToFormat(QImage::Format_MonoLSB);
+
+ QWSDefineCursorCommand cmd;
+ cmd.simpleData.width = curs.width();
+ cmd.simpleData.height = curs.height();
+ cmd.simpleData.hotX = hotX;
+ cmd.simpleData.hotY = hotY;
+ cmd.simpleData.id = id;
+
+
+ // must copy each scanline since there might be gaps between them
+ const int height = curs.height();
+ const int width = curs.width();
+ const int dst_bpl = (width + 7) / 8;
+
+ int dataLen = dst_bpl * height;
+ uchar *data = new uchar[dataLen*2];
+ uchar *dst = data;
+
+ int src_bpl = cursImg.bytesPerLine();
+ const uchar *cursSrc = cursImg.bits();
+ for (int i = 0; i < height; ++i) {
+ memcpy(dst, cursSrc + i*src_bpl, dst_bpl);
+ dst += dst_bpl;
+ }
+
+ src_bpl = maskImg.bytesPerLine();
+ const uchar *maskSrc = maskImg.bits();
+ for (int i = 0; i < height; ++i) {
+ memcpy(dst, maskSrc + i*src_bpl, dst_bpl);
+ dst += dst_bpl;
+ }
+
+ cmd.setData(reinterpret_cast<char*>(data), dataLen*2);
+ delete [] data;
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::destroyCursor(int id)
+{
+ QWSDefineCursorCommand cmd;
+ cmd.simpleData.width = 0;
+ cmd.simpleData.height = 0;
+ cmd.simpleData.hotX = 0;
+ cmd.simpleData.hotY = 0;
+ cmd.simpleData.id = id;
+ cmd.setData(0, 0);
+
+ d->sendCommand(cmd);
+}
+
+#ifndef QT_NO_SOUND
+void QWSDisplay::playSoundFile(const QString& f)
+{
+ QWSPlaySoundCommand cmd;
+ cmd.setFileName(f);
+ d->sendCommand(cmd);
+}
+#endif
+
+#ifndef QT_NO_COP
+void QWSDisplay::registerChannel(const QString& channel)
+{
+ QWSQCopRegisterChannelCommand reg;
+ reg.setChannel(channel);
+ qt_fbdpy->d->sendCommand(reg);
+}
+
+void QWSDisplay::sendMessage(const QString &channel, const QString &msg,
+ const QByteArray &data)
+{
+ QWSQCopSendCommand com;
+ com.setMessage(channel, msg, data);
+ qt_fbdpy->d->sendCommand(com);
+}
+
+void QWSDisplay::flushCommands()
+{
+ qt_fbdpy->d->flushCommands();
+}
+
+/*
+ caller deletes result
+*/
+QWSQCopMessageEvent* QWSDisplay::waitForQCopResponse()
+{
+ qt_fbdpy->d->waitForQCopResponse();
+ QWSQCopMessageEvent *e = static_cast<QWSQCopMessageEvent*>(qt_fbdpy->d->dequeue());
+ Q_ASSERT(e->type == QWSEvent::QCopMessage);
+ return e;
+}
+#endif
+
+void QWSDisplay::sendFontCommand(int type, const QByteArray &fontName)
+{
+ QWSFontCommand cmd;
+ cmd.simpleData.type = type;
+ cmd.setFontName(fontName);
+ d->sendCommand(cmd);
+}
+
+void QWSDisplay::setWindowCaption(QWidget *w, const QString &c)
+{
+ if (w->isWindow()) {
+ nameRegion(w->internalWinId(), w->objectName(), c);
+ static_cast<QETWidget *>(w)->repaintDecoration(qApp->desktop()->rect(), true);
+ }
+}
+
+void QWSDisplay::selectCursor(QWidget *w, unsigned int cursId)
+{
+ if (cursId != qt_last_cursor)
+ {
+ QWidget *top = w->window();
+ qt_last_cursor = cursId;
+ QWSSelectCursorCommand cmd;
+ cmd.simpleData.windowid = top->internalWinId();
+ cmd.simpleData.id = cursId;
+ d->sendCommand(cmd);
+ d->flush();
+ }
+}
+
+void QWSDisplay::setCursorPosition(int x, int y)
+{
+ QWSPositionCursorCommand cmd;
+ cmd.simpleData.newX = x;
+ cmd.simpleData.newY = y;
+ d->sendCommand(cmd);
+ d->flush();
+}
+
+void QWSDisplay::grabMouse(QWidget *w, bool grab)
+{
+ QWidget *top = w->window();
+ QWSGrabMouseCommand cmd;
+#ifdef QT_DEBUG
+ memset(cmd.simpleDataPtr, 0, sizeof(cmd.simpleData)); //shut up Valgrind
+#endif
+ cmd.simpleData.windowid = top->winId();
+ cmd.simpleData.grab = grab;
+ d->sendCommand(cmd);
+ d->flush();
+}
+
+void QWSDisplay::grabKeyboard(QWidget *w, bool grab)
+{
+ QWidget *top = w->window();
+ QWSGrabKeyboardCommand cmd;
+#ifdef QT_DEBUG
+ memset(cmd.simpleDataPtr, 0, sizeof(cmd.simpleData)); //shut up Valgrind
+#endif
+ cmd.simpleData.windowid = top->winId();
+ cmd.simpleData.grab = grab;
+ d->sendCommand(cmd);
+ d->flush();
+}
+
+QList<QWSWindowInfo> QWSDisplay::windowList()
+{
+ QList<QWSWindowInfo> ret;
+ if(d->directServerConnection()) {
+ QList<QWSInternalWindowInfo*> * qin=QWSServer::windowList();
+ for (int i = 0; i < qin->count(); ++i) {
+ QWSInternalWindowInfo * qwi = qin->at(i);
+ QWSWindowInfo tmp;
+ tmp.winid = qwi->winid;
+ tmp.clientid = qwi->clientid;
+ tmp.name = QString(qwi->name);
+ ret.append(tmp);
+ }
+ qDeleteAll(*qin);
+ delete qin;
+ }
+ return ret;
+}
+
+int QWSDisplay::windowAt(const QPoint &p)
+{
+ //### currently only implemented for the server process
+ int ret = 0;
+ if(d->directServerConnection()) {
+ QWSWindow *win = qwsServer->windowAt(p);
+ if (win)
+ return win->winId();
+ }
+ return ret;
+}
+
+void QWSDisplay::setRawMouseEventFilter(void (*filter)(QWSMouseEvent *))
+{
+ if (qt_fbdpy)
+ qt_fbdpy->d->setMouseFilter(filter);
+}
+
+/*!
+ \relates QScreen
+
+ Here it is. \a transformation and \a screenNo
+ */
+void QWSDisplay::setTransformation(int transformation, int screenNo)
+{
+ QWSScreenTransformCommand cmd;
+ cmd.setTransformation(screenNo, transformation);
+ QWSDisplay::instance()->d->sendCommand(cmd);
+}
+
+static bool qt_try_modal(QWidget *, QWSEvent *);
+
+/*****************************************************************************
+ qt_init() - initializes Qt/FB
+ *****************************************************************************/
+
+static void qt_set_qws_resources()
+
+{
+ if (QApplication::desktopSettingsAware())
+ QApplicationPrivate::qws_apply_settings();
+
+ if (appFont)
+ QApplication::setFont(QFont(QString::fromLocal8Bit(appFont)));
+
+ if (appBGCol || appBTNCol || appFGCol) {
+ (void) QApplication::style(); // trigger creation of application style and system palettes
+ QColor btn;
+ QColor bg;
+ QColor fg;
+ if (appBGCol)
+ bg = QColor(appBGCol);
+ else
+ bg = QApplicationPrivate::sys_pal->color(QPalette::Window);
+ if (appFGCol)
+ fg = QColor(appFGCol);
+ else
+ fg = QApplicationPrivate::sys_pal->color(QPalette::WindowText);
+ if (appBTNCol)
+ btn = QColor(appBTNCol);
+ else
+ btn = QApplicationPrivate::sys_pal->color(QPalette::Button);
+
+ int h,s,v;
+ fg.getHsv(&h,&s,&v);
+ QColor base = Qt::white;
+ bool bright_mode = false;
+ if (v >= 255 - 50) {
+ base = btn.darker(150);
+ bright_mode = true;
+ }
+
+ QPalette pal(fg, btn, btn.lighter(), btn.darker(), btn.darker(150), fg, Qt::white, base, bg);
+ if (bright_mode) {
+ pal.setColor(QPalette::HighlightedText, base);
+ pal.setColor(QPalette::Highlight, Qt::white);
+ } else {
+ pal.setColor(QPalette::HighlightedText, Qt::white);
+ pal.setColor(QPalette::Highlight, Qt::darkBlue);
+ }
+ QColor disabled((fg.red() + btn.red()) / 2,
+ (fg.green() + btn.green())/ 2,
+ (fg.blue() + btn.blue()) / 2);
+ pal.setColorGroup(QPalette::Disabled, disabled, btn, btn.lighter(125),
+ btn.darker(), btn.darker(150), disabled, Qt::white, Qt::white, bg);
+ if (bright_mode) {
+ pal.setColor(QPalette::Disabled, QPalette::HighlightedText, base);
+ pal.setColor(QPalette::Disabled, QPalette::Highlight, Qt::white);
+ } else {
+ pal.setColor(QPalette::Disabled, QPalette::HighlightedText, Qt::white);
+ pal.setColor(QPalette::Disabled, QPalette::Highlight, Qt::darkBlue);
+ }
+ QApplicationPrivate::setSystemPalette(pal);
+
+ }
+}
+
+void QApplicationPrivate::initializeWidgetPaletteHash()
+{
+}
+
+/*! \internal
+ apply the settings to the application
+*/
+bool QApplicationPrivate::qws_apply_settings()
+{
+#ifndef QT_NO_SETTINGS
+ QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
+ settings.beginGroup(QLatin1String("Qt"));
+
+ QStringList strlist;
+ int i;
+ QPalette pal(Qt::black);
+ int groupCount = 0;
+ strlist = settings.value(QLatin1String("Palette/active")).toStringList();
+ if (strlist.count() == QPalette::NColorRoles) {
+ ++groupCount;
+ for (i = 0; i < QPalette::NColorRoles; i++)
+ pal.setColor(QPalette::Active, (QPalette::ColorRole) i,
+ QColor(strlist[i]));
+ }
+ strlist = settings.value(QLatin1String("Palette/inactive")).toStringList();
+ if (strlist.count() == QPalette::NColorRoles) {
+ ++groupCount;
+ for (i = 0; i < QPalette::NColorRoles; i++)
+ pal.setColor(QPalette::Inactive, (QPalette::ColorRole) i,
+ QColor(strlist[i]));
+ }
+ strlist = settings.value(QLatin1String("Palette/disabled")).toStringList();
+ if (strlist.count() == QPalette::NColorRoles) {
+ ++groupCount;
+ for (i = 0; i < QPalette::NColorRoles; i++)
+ pal.setColor(QPalette::Disabled, (QPalette::ColorRole) i,
+ QColor(strlist[i]));
+ }
+
+
+ if (groupCount == QPalette::NColorGroups)
+ QApplicationPrivate::setSystemPalette(pal);
+
+ QString str = settings.value(QLatin1String("font")).toString();
+ if (!str.isEmpty()) {
+ QFont font(QApplication::font());
+ font.fromString(str);
+ QApplicationPrivate::setSystemFont(font);
+ }
+
+ // read library (ie. plugin) path list
+ QString libpathkey =
+ QString::fromLatin1("%1.%2/libraryPath")
+ .arg(QT_VERSION >> 16)
+ .arg((QT_VERSION & 0xff00) >> 8);
+ QStringList pathlist = settings.value(libpathkey).toString().split(QLatin1Char(':'));
+#ifndef QT_NO_LIBRARY
+ if (! pathlist.isEmpty()) {
+ QStringList::ConstIterator it = pathlist.constBegin();
+ while (it != pathlist.constEnd())
+ QApplication::addLibraryPath(*it++);
+ }
+#endif
+
+ // read new QStyle
+ QString stylename = settings.value(QLatin1String("style")).toString();
+ if (QCoreApplication::startingUp()) {
+ if (!stylename.isEmpty() && QApplicationPrivate::styleOverride.isNull())
+ QApplicationPrivate::styleOverride = stylename;
+ } else {
+ QApplication::setStyle(stylename);
+ }
+
+ int num =
+ settings.value(QLatin1String("doubleClickInterval"),
+ QApplication::doubleClickInterval()).toInt();
+ QApplication::setDoubleClickInterval(num);
+
+ num =
+ settings.value(QLatin1String("cursorFlashTime"),
+ QApplication::cursorFlashTime()).toInt();
+ QApplication::setCursorFlashTime(num);
+
+#ifndef QT_NO_WHEELEVENT
+ num =
+ settings.value(QLatin1String("wheelScrollLines"),
+ QApplication::wheelScrollLines()).toInt();
+ QApplication::setWheelScrollLines(num);
+#endif
+
+ QString colorspec = settings.value(QLatin1String("colorSpec"),
+ QVariant(QLatin1String("default"))).toString();
+ if (colorspec == QLatin1String("normal"))
+ QApplication::setColorSpec(QApplication::NormalColor);
+ else if (colorspec == QLatin1String("custom"))
+ QApplication::setColorSpec(QApplication::CustomColor);
+ else if (colorspec == QLatin1String("many"))
+ QApplication::setColorSpec(QApplication::ManyColor);
+ else if (colorspec != QLatin1String("default"))
+ colorspec = QLatin1String("default");
+
+#ifndef QT_NO_TEXTCODEC
+ QString defaultcodec = settings.value(QLatin1String("defaultCodec"),
+ QVariant(QLatin1String("none"))).toString();
+ if (defaultcodec != QLatin1String("none")) {
+ QTextCodec *codec = QTextCodec::codecForName(defaultcodec.toLatin1());
+ if (codec)
+ QTextCodec::setCodecForTr(codec);
+ }
+#endif
+
+ int w = settings.value(QLatin1String("globalStrut/width")).toInt();
+ int h = settings.value(QLatin1String("globalStrut/height")).toInt();
+ QSize strut(w, h);
+ if (strut.isValid())
+ QApplication::setGlobalStrut(strut);
+
+ QStringList effects = settings.value(QLatin1String("GUIEffects")).toStringList();
+ QApplication::setEffectEnabled(Qt::UI_General,
+ effects.contains(QLatin1String("general")));
+ QApplication::setEffectEnabled(Qt::UI_AnimateMenu,
+ effects.contains(QLatin1String("animatemenu")));
+ QApplication::setEffectEnabled(Qt::UI_FadeMenu,
+ effects.contains(QLatin1String("fademenu")));
+ QApplication::setEffectEnabled(Qt::UI_AnimateCombo,
+ effects.contains(QLatin1String("animatecombo")));
+ QApplication::setEffectEnabled(Qt::UI_AnimateTooltip,
+ effects.contains(QLatin1String("animatetooltip")));
+ QApplication::setEffectEnabled(Qt::UI_FadeTooltip,
+ effects.contains(QLatin1String("fadetooltip")));
+ QApplication::setEffectEnabled(Qt::UI_AnimateToolBox,
+ effects.contains(QLatin1String("animatetoolbox")));
+
+ settings.beginGroup(QLatin1String("Font Substitutions"));
+ QStringList fontsubs = settings.childKeys();
+ if (!fontsubs.isEmpty()) {
+ QStringList::Iterator it = fontsubs.begin();
+ for (; it != fontsubs.end(); ++it) {
+ QString fam = *it;
+ QStringList subs = settings.value(fam).toStringList();
+ QFont::insertSubstitutions(fam, subs);
+ }
+ }
+ settings.endGroup();
+
+ settings.endGroup(); // Qt
+
+ settings.beginGroup(QLatin1String("QWS Font Fallbacks"));
+ if (!settings.childKeys().isEmpty()) {
+ // from qfontdatabase_qws.cpp
+ extern void qt_applyFontDatabaseSettings(const QSettings &);
+ qt_applyFontDatabaseSettings(settings);
+ }
+ settings.endGroup();
+
+ return true;
+#else
+ return false;
+#endif // QT_NO_SETTINGS
+}
+
+
+
+static void init_display()
+{
+ if (qt_fbdpy) return; // workaround server==client case
+
+ // Connect to FB server
+ qt_fbdpy = new QWSDisplay();
+
+ // Get display parameters
+ // Set paintdevice parameters
+ // XXX initial info sent from server
+ // Misc. initialization
+
+ QColormap::initialize();
+ QFont::initialize();
+#ifndef QT_NO_CURSOR
+ QCursorData::initialize();
+#endif
+
+ qApp->setObjectName(appName);
+
+ if (!QApplicationPrivate::sys_font) {
+#ifdef QT_NO_FREETYPE
+ QFont f = QFont(QLatin1String("helvetica"), 10);
+#else
+ QFont f = QFont(QLatin1String("DejaVu Sans"), 12);
+#endif
+ QApplicationPrivate::setSystemFont(f);
+ }
+ qt_set_qws_resources();
+}
+
+void qt_init_display()
+{
+ qt_is_gui_used = true;
+ qws_single_process = true;
+ init_display();
+}
+
+static bool read_bool_env_var(const char *var, bool defaultvalue)
+{
+ // returns true if env variable is set to non-zero
+ // returns false if env var is set to zero
+ // returns defaultvalue if env var not set
+ char *x = ::getenv(var);
+ return (x && *x) ? (strcmp(x,"0") != 0) : defaultvalue;
+}
+
+static int read_int_env_var(const char *var, int defaultvalue)
+{
+ bool ok;
+ int r = qgetenv(var).toInt(&